@pixelzx/genesis 2026.5.10-6 → 2026.5.14

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 (1028) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-HsdssCm5.js +201 -0
  4. package/dist/abort.runtime-CCiGbChf.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-BFdBk-JK.js +2 -0
  7. package/dist/accounts-C93knB2s.js +107 -0
  8. package/dist/accounts-CmWsTjc0.js +104 -0
  9. package/dist/acp-cli-DerK-OOs.js +2193 -0
  10. package/dist/acp-spawn-BXgd3xI4.js +1093 -0
  11. package/dist/acp-spawn-B_VTJ7Y3.js +2 -0
  12. package/dist/acp-stateful-target-driver-ChbWn2a3.js +89 -0
  13. package/dist/action-agents-DI3KPI_N.js +67 -0
  14. package/dist/action-focus-DFMGx7SK.js +132 -0
  15. package/dist/action-help-BoiR_V75.js +7 -0
  16. package/dist/action-info-DhsQByAT.js +101 -0
  17. package/dist/action-kill-BvLdE33h.js +33 -0
  18. package/dist/action-list-BdsPBG-p.js +21 -0
  19. package/dist/action-log-FKCTIRib.js +30 -0
  20. package/dist/action-send-yDRdacms.js +39 -0
  21. package/dist/action-spawn-BCejeGeY.js +47 -0
  22. package/dist/action-unfocus-BzOqmgPU.js +29 -0
  23. package/dist/actions.runtime-D2P74T6w.js +5 -0
  24. package/dist/actions.runtime-D2TU2HDQ.js +18 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-Dk8aCj39.js +2 -0
  27. package/dist/agent-command-nDMak9eq.js +874 -0
  28. package/dist/agent-harness-runtime-DH30C-dS.js +144 -0
  29. package/dist/agent-runner-utils-BxVxCzAT.js +239 -0
  30. package/dist/agent-runner.runtime-BzmWPM3N.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-8VQ2K9_7.js +18 -0
  33. package/dist/agents-2uoNPaT4.js +5 -0
  34. package/dist/agents-BlglPCvL.js +954 -0
  35. package/dist/aliases-Bf_TGZ-c.js +2 -0
  36. package/dist/aliases-D20LuLYC.js +96 -0
  37. package/dist/api-BuT2hZuJ.js +5 -0
  38. package/dist/api-CZyjZafs.js +139 -0
  39. package/dist/api-Cv2GRmrG.js +3 -0
  40. package/dist/approval-gateway-resolver-CiWquy07.js +29 -0
  41. package/dist/approval-gateway-runtime-DZ1EiNI9.js +2 -0
  42. package/dist/approval-handler-runtime--jMnqEut.js +439 -0
  43. package/dist/approval-native-runtime-C2hO4jly.js +729 -0
  44. package/dist/attempt-execution.runtime-DJNzLYN5.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-DLSwcGBM.js +221 -0
  47. package/dist/attempt.tool-run-context-BoeZy-CS.js +933 -0
  48. package/dist/audit-D8jh81of.js +939 -0
  49. package/dist/audit.runtime-CYiZEzKA.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-CbSjx6pr.js +2 -0
  52. package/dist/auth-DrAeMvc-.js +383 -0
  53. package/dist/auth-order-BhL6XklB.js +96 -0
  54. package/dist/auth-order-E6NyjyTf.js +2 -0
  55. package/dist/bash-tools-0Usmy4nq.js +2824 -0
  56. package/dist/bash-tools-GMTXdvXa.js +3 -0
  57. package/dist/binding-routing-hI8tQvXL.js +85 -0
  58. package/dist/binding-targets-D80eeoHa.js +121 -0
  59. package/dist/bridge-server-Dc0X-vM1.js +113 -0
  60. package/dist/browser-control-auth-BMdI0YJq.js +2 -0
  61. package/dist/browser-node-runtime-Cnl0XBZe.js +12 -0
  62. package/dist/browser-profiles-Bu6WocI8.js +2 -0
  63. package/dist/browser-runtime-CX7uywM2.js +387 -0
  64. package/dist/browser-setup-tools-Cak8k4lw.js +13 -0
  65. package/dist/build-Dxz1bcgC.js +550 -0
  66. package/dist/build-info.json +3 -3
  67. package/dist/bundled/boot-md/handler.js +2 -2
  68. package/dist/bundled/session-memory/handler.js +1 -1
  69. package/dist/call-Bp0Jzgai.js +331 -0
  70. package/dist/call-ZEnbBS5L.js +3 -0
  71. package/dist/call.runtime--tSMAZqa.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-BeTXYxno.js +1401 -0
  74. package/dist/catchup-9Bs6o39S.js +300 -0
  75. package/dist/channel-B9W0Z9Gi.js +226 -0
  76. package/dist/channel-BG4gtmvb.js +491 -0
  77. package/dist/channel-BV__eBQr.js +595 -0
  78. package/dist/channel-BeXA2BKn.js +1100 -0
  79. package/dist/channel-Bmx1aNLl.js +453 -0
  80. package/dist/channel-C89uvKbR.js +1320 -0
  81. package/dist/channel-D--fTzTz.js +297 -0
  82. package/dist/channel-D6MPpTUg.js +350 -0
  83. package/dist/channel-DN2fjFsR.js +840 -0
  84. package/dist/channel-M2J7R2Uv.js +1174 -0
  85. package/dist/channel-Wgrgw00y.js +1802 -0
  86. package/dist/channel-core-CNZTbaGa.js +5 -0
  87. package/dist/channel-inbound-D7oY6hxH.js +31 -0
  88. package/dist/channel-plugin-runtime-QQGS9Z2H.js +771 -0
  89. package/dist/channel-runtime-DLDS3f8E.js +425 -0
  90. package/dist/channel.runtime-BLqQ7wNr.js +89 -0
  91. package/dist/channel.runtime-D9mveP3w.js +34702 -0
  92. package/dist/channel.runtime-DDzl79Y5.js +4 -0
  93. package/dist/channel.runtime-DVck4iX6.js +109 -0
  94. package/dist/channel.runtime-DupGtAcQ.js +2364 -0
  95. package/dist/channel.runtime-VOb32ff2.js +576 -0
  96. package/dist/channel.runtime-pkdv8znq.js +430 -0
  97. package/dist/channel.runtime.js +1 -1
  98. package/dist/channel.setup-CzFeQSCf.js +10 -0
  99. package/dist/channels-B7nMUZmE.js +733 -0
  100. package/dist/channels-cli-D3b6qIoT.js +268 -0
  101. package/dist/chat-DJi7i8_v.js +2830 -0
  102. package/dist/clawbot-cli-Dd5BJrHn.js +9 -0
  103. package/dist/cli/daemon-cli.js +3 -3
  104. package/dist/cli-Chkhwlxd.js +72 -0
  105. package/dist/cli-ClfUUpJc.js +219 -0
  106. package/dist/cli-D7DXwMop.js +2 -0
  107. package/dist/cli-FGYk8Lc-.js +2 -0
  108. package/dist/cli-runner-B8NFm0F2.js +286 -0
  109. package/dist/cli-runner.runtime-9NiLdc0u.js +4 -0
  110. package/dist/cli-runner.runtime-CQBiLTnc.js +3 -0
  111. package/dist/cli-runner.runtime.js +1 -1
  112. package/dist/cli-startup-metadata.json +2 -2
  113. package/dist/cli.runtime-DLaMMW9D.js +1261 -0
  114. package/dist/cli.runtime.js +1 -1
  115. package/dist/client-DdVTC4AU.js +713 -0
  116. package/dist/client-Rl2m8YtH.js +138 -0
  117. package/dist/command-auth-CtaUnehF.js +76 -0
  118. package/dist/command-config-resolution-41LV2AE4.js +23 -0
  119. package/dist/command-config-resolution-Dl6771wK.js +2 -0
  120. package/dist/command-config-resolution.runtime-IjOZSz-Z.js +2 -0
  121. package/dist/command-config-resolution.runtime.js +1 -1
  122. package/dist/command-registry-BSLEuvaP.js +9 -0
  123. package/dist/command-registry-Di4H88Ex.js +4 -0
  124. package/dist/command-registry-core-CVLFeMly.js +106 -0
  125. package/dist/command-secret-gateway-CeBdQ0UB.js +528 -0
  126. package/dist/command-status.runtime-CcK3WYAj.js +87 -0
  127. package/dist/command-status.runtime.js +1 -1
  128. package/dist/commands-acp-CbKfCUs1.js +77 -0
  129. package/dist/commands-compact.runtime-Bz_yPSEn.js +10 -0
  130. package/dist/commands-compact.runtime.js +1 -1
  131. package/dist/commands-handlers.runtime-B1OY0W5c.js +4597 -0
  132. package/dist/commands-handlers.runtime.js +1 -1
  133. package/dist/commands-status-38xkzOM8.js +16 -0
  134. package/dist/commands-status.runtime-CA10fo5C.js +3 -0
  135. package/dist/commands-status.runtime.js +1 -1
  136. package/dist/commands-subagents-control.runtime-BcAzwFRp.js +3 -0
  137. package/dist/commands-subagents-control.runtime-BrMEYAIb.js +2 -0
  138. package/dist/commands-subagents-control.runtime.js +1 -1
  139. package/dist/commands-system-prompt-D7bZ82UZ.js +2 -0
  140. package/dist/commands-system-prompt-DnEDYPgk.js +158 -0
  141. package/dist/commands.runtime-Ds9vP6rq.js +167 -0
  142. package/dist/commands.runtime.js +1 -1
  143. package/dist/compact-BIdDCBoG.js +1118 -0
  144. package/dist/compact.runtime-DgjjAE5U.js +12 -0
  145. package/dist/compact.runtime.js +1 -1
  146. package/dist/completion-cli-Dy3M9WA7.js +328 -0
  147. package/dist/config-9L6gNFMn.js +252 -0
  148. package/dist/config-cli-p0tyYOTV.js +1078 -0
  149. package/dist/configure-BuUHBLfl.js +2 -0
  150. package/dist/configure-Dt7mjt4p.js +1252 -0
  151. package/dist/connect-options-C3qcuxrZ.js +699 -0
  152. package/dist/control-auth-BO5NLVkM.js +125 -0
  153. package/dist/control-service-Iw7H8uVc.js +156 -0
  154. package/dist/conversation-id-Ch1pkxe7.js +38 -0
  155. package/dist/conversation-id-DeXgCGeL.js +235 -0
  156. package/dist/conversation-runtime-d5Fy5tiD.js +31 -0
  157. package/dist/core-Bg858J0J.js +275 -0
  158. package/dist/cron-cli-ou_QWbdu.js +713 -0
  159. package/dist/daemon-cli-CU4aPfqj.js +12 -0
  160. package/dist/dashboard-CMgYveXv.js +2 -0
  161. package/dist/dashboard-iIYTjC3l.js +81 -0
  162. package/dist/delegate-DXPsB5ax.js +64 -0
  163. package/dist/detached-task-runtime-BCoJPrqs.js +73 -0
  164. package/dist/devices-cli-DWhHW_FQ.js +498 -0
  165. package/dist/diagnostics-D9WvAZg8.js +154 -0
  166. package/dist/direct-dm-eIMRqu_f.js +64 -0
  167. package/dist/dispatch-CtoAa2rI.js +1131 -0
  168. package/dist/dispatch-acp-manager.runtime-hPvhU-sq.js +3 -0
  169. package/dist/dispatch-acp-manager.runtime.js +1 -1
  170. package/dist/dispatch-acp-yznhwktL.js +981 -0
  171. package/dist/dispatch-acp.runtime-CaMfHhpp.js +19 -0
  172. package/dist/dispatch-acp.runtime.js +1 -1
  173. package/dist/doctor-device-pairing-BgzU7Aob.js +307 -0
  174. package/dist/doctor-gateway-daemon-flow-DAOcd3zs.js +250 -0
  175. package/dist/doctor-gateway-health-DyLSbbAN.js +63 -0
  176. package/dist/doctor-health-CAlZJHoi.js +59 -0
  177. package/dist/doctor-health-contributions-6cs3TVfN.js +493 -0
  178. package/dist/doctor-prompter-C8ODnxH4.js +56 -0
  179. package/dist/doctor-workspace-status-4zFHdM4x.js +75 -0
  180. package/dist/dreaming-narrative-CJu_lIBP.js +595 -0
  181. package/dist/dreaming-zJ9qLCLz.js +1574 -0
  182. package/dist/embedded-gateway-stub.runtime-B9vZ4p3F.js +9 -0
  183. package/dist/embedded-gateway-stub.runtime.js +1 -1
  184. package/dist/entry.js +2 -2
  185. package/dist/exec-approvals-cli-l4tPjQfT.js +498 -0
  186. package/dist/extensionAPI.js +1 -1
  187. package/dist/extensions/active-memory/index.js +1 -1
  188. package/dist/extensions/bluebubbles/api.js +3 -3
  189. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  190. package/dist/extensions/browser/browser-bridge.js +1 -1
  191. package/dist/extensions/browser/browser-config.js +4 -4
  192. package/dist/extensions/browser/browser-control-auth.js +2 -2
  193. package/dist/extensions/browser/browser-doctor.js +2 -2
  194. package/dist/extensions/browser/browser-maintenance.js +2 -2
  195. package/dist/extensions/browser/browser-profiles.js +2 -2
  196. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  197. package/dist/extensions/browser/index.js +1 -1
  198. package/dist/extensions/browser/plugin-registration.js +1 -1
  199. package/dist/extensions/browser/register.runtime.js +3 -3
  200. package/dist/extensions/browser/runtime-api.js +11 -11
  201. package/dist/extensions/browser/test-support.js +1 -1
  202. package/dist/extensions/device-pair/api.js +2 -2
  203. package/dist/extensions/device-pair/index.js +4 -4
  204. package/dist/extensions/device-pair/notify.js +1 -1
  205. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  206. package/dist/extensions/device-pair/qr-image.js +2 -2
  207. package/dist/extensions/google-meet/index.js +2 -2
  208. package/dist/extensions/imessage/api.js +3 -3
  209. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  210. package/dist/extensions/imessage/runtime-api.js +4 -4
  211. package/dist/extensions/irc/api.js +2 -2
  212. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  213. package/dist/extensions/line/api.js +2 -2
  214. package/dist/extensions/line/channel-plugin-api.js +1 -1
  215. package/dist/extensions/line/contract-api.js +1 -1
  216. package/dist/extensions/line/runtime-api.js +4 -4
  217. package/dist/extensions/line/setup-api.js +1 -1
  218. package/dist/extensions/llm-task/index.js +2 -2
  219. package/dist/extensions/lobster/index.js +3 -3
  220. package/dist/extensions/lobster/runtime-api.js +1 -1
  221. package/dist/extensions/mattermost/api.js +1 -1
  222. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  223. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  224. package/dist/extensions/mattermost/policy-api.js +1 -1
  225. package/dist/extensions/mattermost/runtime-api.js +5 -5
  226. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  227. package/dist/extensions/memory-core/api.js +1 -1
  228. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  229. package/dist/extensions/memory-core/index.js +3 -3
  230. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  231. package/dist/extensions/microsoft/index.js +1 -1
  232. package/dist/extensions/microsoft/speech-provider.js +1 -1
  233. package/dist/extensions/microsoft/test-api.js +1 -1
  234. package/dist/extensions/minimax/index.js +1 -1
  235. package/dist/extensions/minimax/speech-provider.js +1 -1
  236. package/dist/extensions/msteams/api.js +1 -1
  237. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  238. package/dist/extensions/msteams/runtime-api.js +3 -3
  239. package/dist/extensions/msteams/test-api.js +1 -1
  240. package/dist/extensions/nextcloud-talk/api.js +1 -1
  241. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  242. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  243. package/dist/extensions/openshell/index.js +2 -2
  244. package/dist/extensions/signal/api.js +6 -6
  245. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  246. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  247. package/dist/extensions/signal/runtime-api.js +8 -8
  248. package/dist/extensions/skill-workshop/api.js +1 -1
  249. package/dist/extensions/skill-workshop/index.js +1 -1
  250. package/dist/extensions/synology-chat/api.js +1 -1
  251. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  252. package/dist/extensions/tlon/api.js +2 -2
  253. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  254. package/dist/extensions/tlon/runtime-api.js +1 -1
  255. package/dist/extensions/tlon/test-api.js +1 -1
  256. package/dist/extensions/twitch/api.js +1 -1
  257. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  258. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  259. package/dist/extensions/zalo/api.js +3 -3
  260. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  261. package/dist/extensions/zalo/runtime-api.js +2 -2
  262. package/dist/extensions/zalo/setup-api.js +2 -2
  263. package/dist/extensions/zalouser/api.js +3 -3
  264. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  265. package/dist/extensions/zalouser/runtime-api.js +6 -6
  266. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  267. package/dist/extensions/zalouser/test-api.js +1 -1
  268. package/dist/fallbacks-5e-X8fPt.js +31 -0
  269. package/dist/fallbacks-DCbURZMd.js +2 -0
  270. package/dist/fallbacks-shared-Bzjcr5w5.js +111 -0
  271. package/dist/gateway-CjuxvsvZ.js +115 -0
  272. package/dist/gateway-cli-CQA4nImt.js +1283 -0
  273. package/dist/gateway-rpc-Bbusy08n.js +14 -0
  274. package/dist/gateway-rpc.runtime-DD6cH5Yg.js +23 -0
  275. package/dist/gateway-rpc.runtime.js +1 -1
  276. package/dist/gateway-runtime-XDPnn5V4.js +15 -0
  277. package/dist/gateway-status-CPFyNBd0.js +584 -0
  278. package/dist/genesis-tools-D2gYU2tu.js +9164 -0
  279. package/dist/genesis-tools.runtime-Cl9HUQIe.js +2 -0
  280. package/dist/genesis-tools.runtime.js +1 -1
  281. package/dist/get-reply-BDKmBVkD.js +3880 -0
  282. package/dist/get-reply-from-config.runtime-BFQNABFO.js +2 -0
  283. package/dist/get-reply-from-config.runtime.js +1 -1
  284. package/dist/graph-users-2xdXE-Yn.js +1337 -0
  285. package/dist/health-BKHuEUZk.js +469 -0
  286. package/dist/health-CrfIv62B.js +3 -0
  287. package/dist/health-route-ZaUKCbwz.js +2 -0
  288. package/dist/health-route-crfn8Wzd.js +41 -0
  289. package/dist/heartbeat-runner-Bv2kAmU3.js +1292 -0
  290. package/dist/heartbeat-runner-DvgfwtQR.js +5 -0
  291. package/dist/heartbeat-runner.runtime-BImjQx8_.js +4 -0
  292. package/dist/heartbeat-runner.runtime.js +1 -1
  293. package/dist/hooks-cli-CR3_XqU-.js +433 -0
  294. package/dist/image-fallbacks-BvD9lpty.js +31 -0
  295. package/dist/image-fallbacks-Cdj3ONWG.js +2 -0
  296. package/dist/inbound-reply-dispatch-t08o6FPz.js +73 -0
  297. package/dist/index.js +2 -2
  298. package/dist/infra-runtime-BcnTWNNa.js +39 -0
  299. package/dist/init-JuJvpNrf.js +59 -0
  300. package/dist/library-DFJNZjXk.js +45 -0
  301. package/dist/lifecycle-C9Me6GOM.js +571 -0
  302. package/dist/lifecycle-UVNzY9hW.js +229 -0
  303. package/dist/lifecycle.runtime-CD2Ez3hz.js +2 -0
  304. package/dist/lifecycle.runtime.js +1 -1
  305. package/dist/list-BSz9542X.js +2 -0
  306. package/dist/list-JnFZd5Tm.js +1212 -0
  307. package/dist/list-LwlQhQNC.js +2 -0
  308. package/dist/list-kEb2jXCm.js +131 -0
  309. package/dist/list.probe-C_fNmtOl.js +419 -0
  310. package/dist/llm-slug-generator-BxS18aoP.js +79 -0
  311. package/dist/llm-slug-generator.js +1 -1
  312. package/dist/load-config-D93X3FB6.js +35 -0
  313. package/dist/local-dispatch.runtime-DlNzE_mQ.js +8 -0
  314. package/dist/local-dispatch.runtime.js +1 -1
  315. package/dist/logs-cli-DI36s-Kp.js +265 -0
  316. package/dist/logs-cli.runtime-VLqJH6Q_.js +2 -0
  317. package/dist/logs-cli.runtime.js +1 -1
  318. package/dist/main-session-restart-recovery-CtEnOm_t.js +206 -0
  319. package/dist/managed-image-attachments-8-nMKMv0.js +2 -0
  320. package/dist/managed-image-attachments-D880KVE3.js +635 -0
  321. package/dist/manager-CM_-KIGk.js +2057 -0
  322. package/dist/manager-DCbgzw4f.js +2 -0
  323. package/dist/markdown-to-line-DetuLbSn.js +790 -0
  324. package/dist/mcp/plugin-tools-serve.js +1 -1
  325. package/dist/mcp-cli-D-Ip2Nfl.js +725 -0
  326. package/dist/mcp-http-0RwmPOAs.js +529 -0
  327. package/dist/media-runtime-DFk_-1jK.js +329 -0
  328. package/dist/memory-core-host-runtime-cli-sTNTqMrk.js +9 -0
  329. package/dist/message-Bv8VSWOM.js +232 -0
  330. package/dist/message-action-runner-DNNLPZC7.js +2 -0
  331. package/dist/message-action-runner-Dx2CS7oR.js +1407 -0
  332. package/dist/message-actions-CgX0jETB.js +143 -0
  333. package/dist/message.gateway.runtime-CagO8Iac.js +2 -0
  334. package/dist/message.gateway.runtime.js +1 -1
  335. package/dist/models-auth-status-BezWkV1s.js +201 -0
  336. package/dist/models-cli-Dt2_1fvN.js +219 -0
  337. package/dist/monitor-BBOMX-8b.js +2 -0
  338. package/dist/monitor-B_8XDUsF.js +788 -0
  339. package/dist/monitor-BiZHF-1H.js +1661 -0
  340. package/dist/monitor-C3q2KiwU.js +671 -0
  341. package/dist/monitor-C4CoLdAg.js +1459 -0
  342. package/dist/monitor-Dzx5XR6B.js +1237 -0
  343. package/dist/monitor-auth-BDQGS1tC.js +207 -0
  344. package/dist/monitor-processing-D0-PAnz5.js +1974 -0
  345. package/dist/monitor.runtime-C5Heb5v6.js +2 -0
  346. package/dist/monitor.runtime.js +1 -1
  347. package/dist/monitor.webhook-Bxdlvgn0.js +180 -0
  348. package/dist/msteams-QG8Vc9EL.js +35 -0
  349. package/dist/native-hook-relay-7HRINE7k.js +519 -0
  350. package/dist/nextcloud-talk-CK88yG5C.js +17 -0
  351. package/dist/node-cli-CLt0UUmz.js +2506 -0
  352. package/dist/nodes-cli-Dj_WT-Rq.js +1046 -0
  353. package/dist/nodes-utils-CC3x1gph.js +84 -0
  354. package/dist/nodes.helpers-cLg2WJmu.js +34 -0
  355. package/dist/notify-CtXjN-ys.js +315 -0
  356. package/dist/onboard-Be9lmIdQ.js +70 -0
  357. package/dist/onboard-DYjJGj6b.js +2 -0
  358. package/dist/onboard-helpers-BloAlYat.js +6 -0
  359. package/dist/onboard-helpers-CaHkv2LW.js +204 -0
  360. package/dist/onboard-interactive-CQwv1-Vb.js +24 -0
  361. package/dist/onboard-non-interactive-7rZAm6_U.js +548 -0
  362. package/dist/onboard-remote-CFgdaVPu.js +2 -0
  363. package/dist/onboard-remote-CGvm5X7J.js +193 -0
  364. package/dist/onboard-skills-B6GPMwGy.js +2 -0
  365. package/dist/onboard-skills-SowW-8L8.js +134 -0
  366. package/dist/openai-http-BJvlHsCo.js +500 -0
  367. package/dist/openresponses-http-CtSmB-cl.js +1128 -0
  368. package/dist/operator-approvals-client-DBZk6yms.js +68 -0
  369. package/dist/outbound.runtime-DDjUHXqj.js +2 -0
  370. package/dist/outbound.runtime.js +1 -1
  371. package/dist/pair-command-approve-C9z_wKa7.js +44 -0
  372. package/dist/persistent-bindings.lifecycle-DN37iCp9.js +2 -0
  373. package/dist/persistent-bindings.lifecycle-XxRr7GHW.js +85 -0
  374. package/dist/pi-embedded-CFdaZ8Aq.js +2905 -0
  375. package/dist/pi-embedded-D5ZS7RLO.js +4 -0
  376. package/dist/pi-embedded.runtime-CHKkjB2P.js +4 -0
  377. package/dist/pi-embedded.runtime.js +1 -1
  378. package/dist/pi-tool-definition-adapter-BY94dt6N.js +229 -0
  379. package/dist/pi-tools-BbWZboe_.js +1057 -0
  380. package/dist/pi-tools.before-tool-call-BqjF6O4b.js +2 -0
  381. package/dist/pi-tools.before-tool-call-DELpyAv3.js +433 -0
  382. package/dist/plugin-NgUr445Z.js +12195 -0
  383. package/dist/plugin-enabled-C28BqYaN.js +140 -0
  384. package/dist/plugin-registration-DXfHWNi7.js +23 -0
  385. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  386. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  387. package/dist/plugin-sdk/acp-runtime.js +2 -2
  388. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  389. package/dist/plugin-sdk/agent-harness.js +6 -6
  390. package/dist/plugin-sdk/agent-runtime.js +2 -2
  391. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  392. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  393. package/dist/plugin-sdk/approval-runtime.js +1 -1
  394. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  395. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  396. package/dist/plugin-sdk/browser-support.js +7 -7
  397. package/dist/plugin-sdk/channel-core.js +2 -2
  398. package/dist/plugin-sdk/channel-inbound.js +2 -2
  399. package/dist/plugin-sdk/command-auth.js +1 -1
  400. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  401. package/dist/plugin-sdk/compat.js +1 -1
  402. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  403. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  404. package/dist/plugin-sdk/core.js +2 -2
  405. package/dist/plugin-sdk/direct-dm.js +1 -1
  406. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  407. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  408. package/dist/plugin-sdk/index.js +1 -1
  409. package/dist/plugin-sdk/infra-runtime.js +3 -3
  410. package/dist/plugin-sdk/irc.js +2 -2
  411. package/dist/plugin-sdk/matrix.js +1 -1
  412. package/dist/plugin-sdk/media-runtime.js +1 -1
  413. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  414. package/dist/plugin-sdk/memory-core.js +2 -2
  415. package/dist/plugin-sdk/msteams.js +2 -2
  416. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  417. package/dist/plugin-sdk/nostr.js +1 -1
  418. package/dist/plugin-sdk/outbound-runtime.js +1 -1
  419. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  420. package/dist/plugin-sdk/reply-runtime.js +4 -4
  421. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  422. package/dist/plugin-sdk/runtime.js +2 -2
  423. package/dist/plugin-sdk/session-visibility.js +1 -1
  424. package/dist/plugin-sdk/testing.js +4 -4
  425. package/dist/plugin-sdk/tlon.js +1 -1
  426. package/dist/plugin-sdk/zalo.js +1 -1
  427. package/dist/plugin-sdk/zalouser.js +1 -1
  428. package/dist/plugin-service-CDV_mv3L.js +2892 -0
  429. package/dist/plugins/runtime/index.js +1 -1
  430. package/dist/policy-DRGdB4kC.js +328 -0
  431. package/dist/postinstall-inventory.json +419 -419
  432. package/dist/prepare.runtime-CFJ7xlZZ.js +815 -0
  433. package/dist/prepare.runtime.js +1 -1
  434. package/dist/probe-B0d4k1H7.js +2 -0
  435. package/dist/probe-BYEt-jaP.js +74 -0
  436. package/dist/probe-C0Pjr8zL.js +45 -0
  437. package/dist/probe-DjVR1LrS.js +241 -0
  438. package/dist/probe-DnmHmpaU.js +2 -0
  439. package/dist/probe-DsUVRbVb.js +1443 -0
  440. package/dist/probe-w8GKa3jg.js +2205 -0
  441. package/dist/program-CHFQxiK1.js +111 -0
  442. package/dist/prompt-select-styled-MW9hiyyE.js +20 -0
  443. package/dist/protocol-Bi30vNUf.js +2372 -0
  444. package/dist/provider-dispatcher-DCiHm7Dg.js +22 -0
  445. package/dist/provider-dispatcher-Ks3eXZ3r.js +2 -0
  446. package/dist/qr-cli-BwTOLrea.js +2 -0
  447. package/dist/qr-cli-a2oAONMy.js +349 -0
  448. package/dist/qr-image-C-WXbr_t.js +2 -0
  449. package/dist/reaction-runtime-api-DllSQaK2.js +116 -0
  450. package/dist/reactions-CtYkzUsM.js +998 -0
  451. package/dist/register-service-commands-DG8RhR0h.js +71 -0
  452. package/dist/register.agent-C5MuWuAI.js +248 -0
  453. package/dist/register.configure-DwJQJbMd.js +15 -0
  454. package/dist/register.maintenance-DdU9NAfX.js +363 -0
  455. package/dist/register.message-Nus2qnvZ.js +329 -0
  456. package/dist/register.onboard-C17EAKsi.js +88 -0
  457. package/dist/register.runtime-DZQmSuuE.js +81 -0
  458. package/dist/register.runtime.js +1 -1
  459. package/dist/register.setup-VfQ0EfuW.js +150 -0
  460. package/dist/register.status-health-sessions-ZXf1H1GV.js +1215 -0
  461. package/dist/register.subclis-DHGEDg3U.js +3 -0
  462. package/dist/register.subclis-DOj2-50Q.js +29 -0
  463. package/dist/register.subclis-core-BlO3pEGb.js +249 -0
  464. package/dist/reply-dispatch-runtime-DEnHPuaZ.js +13 -0
  465. package/dist/reply-runtime-CoU12wu8.js +11 -0
  466. package/dist/reply.runtime-C382Aob0.js +2 -0
  467. package/dist/reply.runtime.js +1 -1
  468. package/dist/restart-health-DTZnhp2p.js +2 -0
  469. package/dist/restart-health-DpdAym4_.js +202 -0
  470. package/dist/root-help-DO2HwKh-.js +44 -0
  471. package/dist/routes-C3tRd8KD.js +2 -0
  472. package/dist/routes-D5U1TqcB.js +3341 -0
  473. package/dist/rpc-Cv9FENmZ.js +61 -0
  474. package/dist/rpc.runtime-DKRihP-V.js +21 -0
  475. package/dist/rpc.runtime.js +1 -1
  476. package/dist/run-delivery.runtime-DjJnQg0K.js +530 -0
  477. package/dist/run-delivery.runtime.js +1 -1
  478. package/dist/run-embedded.runtime-BjtHBy_E.js +4 -0
  479. package/dist/run-embedded.runtime.js +1 -1
  480. package/dist/run-execution-cli.runtime-CjJ8yH76.js +4 -0
  481. package/dist/run-execution-cli.runtime.js +1 -1
  482. package/dist/run-executor.runtime-j9H0lPOP.js +277 -0
  483. package/dist/run-executor.runtime.js +1 -1
  484. package/dist/run-main-klOr7Cqz.js +567 -0
  485. package/dist/run-subagent-registry.runtime-kFupl53V.js +2 -0
  486. package/dist/run-subagent-registry.runtime.js +1 -1
  487. package/dist/run-wait-CGf-jyTN.js +135 -0
  488. package/dist/runtime-Dex5AVsy.js +973 -0
  489. package/dist/runtime-Ds1GYJd_.js +9 -0
  490. package/dist/runtime-api-Cbh9Emf7.js +14 -0
  491. package/dist/runtime-api-CvE1wcNP.js +4 -0
  492. package/dist/runtime-api-DLwlT7Ms.js +9 -0
  493. package/dist/runtime-api-DRLIbnWL.js +9 -0
  494. package/dist/runtime-embedded-pi.runtime-CbAS-qIU.js +2 -0
  495. package/dist/runtime-embedded-pi.runtime.js +1 -1
  496. package/dist/runtime-internal-CC7f86-l.js +2 -0
  497. package/dist/runtime-options-DQL_qa4f.js +275 -0
  498. package/dist/runtime-schema-B7_BXHMl.js +28250 -0
  499. package/dist/sanitize-text-RhEEAlk4.js +26 -0
  500. package/dist/scan-B6ovye2n.js +523 -0
  501. package/dist/scan-C1b-2fE3.js +2 -0
  502. package/dist/secrets-cli-DVdMayB8.js +2101 -0
  503. package/dist/security-cli-CfGlkbRX.js +486 -0
  504. package/dist/selection-Dl7400B7.js +7764 -0
  505. package/dist/selection-TbbYnGm_.js +2 -0
  506. package/dist/send-C5OD4jgd.js +102 -0
  507. package/dist/send-DHsH1Uj5.js +156 -0
  508. package/dist/send.runtime-CEMrmW9b.js +2 -0
  509. package/dist/send.runtime.js +1 -1
  510. package/dist/server-BQsyu4ws.js +13 -0
  511. package/dist/server-context-B6XEIceO.js +847 -0
  512. package/dist/server-context-Dsf1Dbvg.js +2 -0
  513. package/dist/server-jgippPyH.js +77 -0
  514. package/dist/server-node-events-ClFTdjSU.js +481 -0
  515. package/dist/server-plugin-bootstrap-BudcQZcm.js +11676 -0
  516. package/dist/server-plugin-bootstrap-DHPKtp9H.js +2 -0
  517. package/dist/server-restart-sentinel-BHMcnf9r.js +697 -0
  518. package/dist/server.impl-CO_m2W0l.js +12822 -0
  519. package/dist/session-kill-http-DuMqbMXv.js +110 -0
  520. package/dist/session-reset-service-DQ3zBf6H.js +471 -0
  521. package/dist/session-route-C0ajBRkR.js +93 -0
  522. package/dist/session-status.runtime-ODxZyNVp.js +2 -0
  523. package/dist/session-status.runtime.js +1 -1
  524. package/dist/session-subagent-reactivation.runtime-Cpy_a-zg.js +2 -0
  525. package/dist/session-subagent-reactivation.runtime.js +1 -1
  526. package/dist/session-tab-registry-B2s-S4d4.js +581 -0
  527. package/dist/session-visibility-CrxEX801.js +147 -0
  528. package/dist/sessions-helpers-Vz4f1hvT.js +304 -0
  529. package/dist/sessions-history-http-5_1TBMSH.js +383 -0
  530. package/dist/sessions-patch-BX7iYA64.js +309 -0
  531. package/dist/sessions-resolve-D32Jcpgp.js +174 -0
  532. package/dist/sessions.runtime-DPNPiNHe.js +2 -0
  533. package/dist/sessions.runtime.js +1 -1
  534. package/dist/setup-4SiKEpy8.js +505 -0
  535. package/dist/setup-api-DUzR1S4R.js +29 -0
  536. package/dist/setup-core-BSBr6Pj_.js +171 -0
  537. package/dist/setup-core-BcPpRVrx.js +176 -0
  538. package/dist/setup-surface-CdBTw2Eg.js +403 -0
  539. package/dist/setup-surface-CqT2hFaX.js +286 -0
  540. package/dist/setup-surface-DWBtQcYb.js +219 -0
  541. package/dist/setup.finalize-DkmUKM2x.js +547 -0
  542. package/dist/setup.gateway-config-CsCCLMdt.js +250 -0
  543. package/dist/shared-CWefinij.js +198 -0
  544. package/dist/shared-D8yOAH4J.js +76 -0
  545. package/dist/shared-qo8aYCCh.js +121 -0
  546. package/dist/slash-state-B7AhPKgR.js +1911 -0
  547. package/dist/speech-provider-BXTE69LP.js +216 -0
  548. package/dist/speech-provider-DPMXFY5I.js +209 -0
  549. package/dist/src-D9PdC_K5.js +3974 -0
  550. package/dist/startup-context-Cdq0HEIV.js +312 -0
  551. package/dist/status-8IIsheAc.js +2 -0
  552. package/dist/status-BJP7r5uA.js +190 -0
  553. package/dist/status-Cdur_Eon.js +209 -0
  554. package/dist/status-DgCUfWiF.js +3 -0
  555. package/dist/status-PGA6vfbr.js +2 -0
  556. package/dist/status-WdUoiEUc.js +397 -0
  557. package/dist/status-all-vuhPAE2d.js +498 -0
  558. package/dist/status-json-DxeLDn8o.js +14 -0
  559. package/dist/status-json-command-CvIjZ-xZ.js +84 -0
  560. package/dist/status-runtime-shared-D99uIbyE.js +257 -0
  561. package/dist/status-subagents.runtime-2y2nwrhw.js +18 -0
  562. package/dist/status-subagents.runtime.js +1 -1
  563. package/dist/status-text-DwM6HyFM.js +237 -0
  564. package/dist/status.gateway-connection.runtime-BaKyeGbr.js +2 -0
  565. package/dist/status.gateway-connection.runtime.js +1 -1
  566. package/dist/status.gather-BD-vuAG8.js +292 -0
  567. package/dist/status.gather-BqdxXBwt.js +2 -0
  568. package/dist/status.runtime-CsIkfeib.js +2 -0
  569. package/dist/status.runtime.js +1 -1
  570. package/dist/status.scan-BRdOxBej.js +65 -0
  571. package/dist/status.scan-overview-CHv-UdJq.js +379 -0
  572. package/dist/status.scan.fast-json-XWvYdzZC.js +2 -0
  573. package/dist/status.scan.fast-json-hRSDzu6s.js +132 -0
  574. package/dist/status.summary-B5WfdvKK.js +2 -0
  575. package/dist/status.summary-DSkKBr8q.js +214 -0
  576. package/dist/subagent-announce-OpyqZYNN.js +351 -0
  577. package/dist/subagent-announce-delivery-BAMZjBEV.js +726 -0
  578. package/dist/subagent-announce-output-CqDcI5I6.js +364 -0
  579. package/dist/subagent-control-CM9lT4vl.js +506 -0
  580. package/dist/subagent-followup.runtime-CR44FiBO.js +68 -0
  581. package/dist/subagent-followup.runtime.js +1 -1
  582. package/dist/subagent-orphan-recovery-BNbipusU.js +305 -0
  583. package/dist/subagent-registry-BfN0RLXV.js +1753 -0
  584. package/dist/subagent-registry-Bswr8A9-.js +3 -0
  585. package/dist/subagent-registry.runtime.js +1 -1
  586. package/dist/subagent-spawn-DyxKFJGQ.js +1005 -0
  587. package/dist/system-cli-BPuSHk_a.js +59 -0
  588. package/dist/targets-Bb2X0wpo.js +67 -0
  589. package/dist/task-executor-BE-vjvwg.js +360 -0
  590. package/dist/task-owner-access-DsZtMsIH.js +74 -0
  591. package/dist/task-registry-ChDYRLl7.js +2366 -0
  592. package/dist/task-registry-delivery-runtime-DhWPfYvw.js +3 -0
  593. package/dist/task-registry-delivery-runtime-q940cKFL.js +2 -0
  594. package/dist/task-registry.maintenance-CvV-xVDy.js +416 -0
  595. package/dist/task-registry.maintenance-DotcNuAs.js +2 -0
  596. package/dist/telegram/token.js +1 -1
  597. package/dist/testing-Cw4JbTOp.js +575 -0
  598. package/dist/text-report-DecCG1x4.js +587 -0
  599. package/dist/tool-resolution-DYC_qbpg.js +90 -0
  600. package/dist/tools-effective-inventory-CO4A7g_O.js +152 -0
  601. package/dist/tools-invoke-http-Dt_fZcFV.js +206 -0
  602. package/dist/trash-DbJ2bPtc.js +24 -0
  603. package/dist/tui-cli-CjdIn-8A.js +4575 -0
  604. package/dist/update-cli-CPxTR9aO.js +1759 -0
  605. package/dist/upgrade-DHE0MALL.js +1226 -0
  606. package/dist/video-generation-task-status-SX-Gxvqj.js +163 -0
  607. package/dist/wait-for-idle-before-flush-cclJNaLR.js +5986 -0
  608. package/dist/wizard-models-m6nipCKM.js +334 -0
  609. package/package.json +1 -1
  610. package/dist/abort-CqiLyOMB.js +0 -201
  611. package/dist/abort.runtime-BpXRzsLj.js +0 -2
  612. package/dist/accounts-6IvVo72A.js +0 -2
  613. package/dist/accounts-BmACEW7s.js +0 -104
  614. package/dist/accounts-C9uNrkct.js +0 -107
  615. package/dist/acp-cli-D2S21TxV.js +0 -2193
  616. package/dist/acp-spawn-BMgHbAc5.js +0 -1093
  617. package/dist/acp-spawn-BqLsEEHD.js +0 -2
  618. package/dist/acp-stateful-target-driver-BmOTqZdI.js +0 -89
  619. package/dist/action-agents-DYP92ace.js +0 -67
  620. package/dist/action-focus-B8s7ksx-.js +0 -132
  621. package/dist/action-help-CY5q8XCj.js +0 -7
  622. package/dist/action-info-DWqUy9uz.js +0 -101
  623. package/dist/action-kill-D4rAuGq9.js +0 -33
  624. package/dist/action-list-0yUjBIDE.js +0 -21
  625. package/dist/action-log-CKBj3mHC.js +0 -30
  626. package/dist/action-send-CWh69c9t.js +0 -39
  627. package/dist/action-spawn-Dpp7Z-BO.js +0 -47
  628. package/dist/action-unfocus-DZtTBpCS.js +0 -29
  629. package/dist/actions.runtime-CPxP9pyB.js +0 -18
  630. package/dist/actions.runtime-DayGrQn8.js +0 -5
  631. package/dist/agent-C62zxu7u.js +0 -2
  632. package/dist/agent-command-Op7xIkWg.js +0 -874
  633. package/dist/agent-harness-runtime-BmNppBZ3.js +0 -144
  634. package/dist/agent-runner-utils-0CcASp86.js +0 -239
  635. package/dist/agent-runner.runtime-B1oOU1Bw.js +0 -3455
  636. package/dist/agent-runtime-CvEaaXu9.js +0 -18
  637. package/dist/agents-EBSus7Mg.js +0 -954
  638. package/dist/agents-NeAmjdPi.js +0 -5
  639. package/dist/aliases-1Uc-n_1q.js +0 -2
  640. package/dist/aliases-YtwtRNzs.js +0 -96
  641. package/dist/api-Bx5oGELA.js +0 -3
  642. package/dist/api-CKLPVXxC.js +0 -5
  643. package/dist/api-Ci3dd5nd.js +0 -139
  644. package/dist/approval-gateway-resolver-pw5uLSnz.js +0 -29
  645. package/dist/approval-gateway-runtime-D5yfX4lb.js +0 -2
  646. package/dist/approval-handler-runtime-DAatKPqp.js +0 -439
  647. package/dist/approval-native-runtime-BHPyBEk0.js +0 -729
  648. package/dist/attempt-execution.runtime-oUHAJ-Om.js +0 -509
  649. package/dist/attempt.prompt-helpers-C9CycBsI.js +0 -221
  650. package/dist/attempt.tool-run-context-BFcTr7AO.js +0 -933
  651. package/dist/audit-CQsDqONq.js +0 -939
  652. package/dist/audit.runtime-BblT8466.js +0 -7
  653. package/dist/auth-CKftnDDk.js +0 -383
  654. package/dist/auth-CXf9ty-v.js +0 -2
  655. package/dist/auth-order-332srkoc.js +0 -2
  656. package/dist/auth-order-Cd5b5W5z.js +0 -96
  657. package/dist/bash-tools-B7VoFXVR.js +0 -2824
  658. package/dist/bash-tools-muiZPPw2.js +0 -3
  659. package/dist/binding-routing-CIdvjhiL.js +0 -85
  660. package/dist/binding-targets-5PvzDLkv.js +0 -121
  661. package/dist/bridge-server-vZhpHaL3.js +0 -113
  662. package/dist/browser-control-auth-CrVnzyc-.js +0 -2
  663. package/dist/browser-node-runtime-yx5pLsn8.js +0 -12
  664. package/dist/browser-profiles-DA1JDuB-.js +0 -2
  665. package/dist/browser-runtime-BeRzkP2v.js +0 -387
  666. package/dist/browser-setup-tools-Cje3slBs.js +0 -13
  667. package/dist/build-B5gv1Hk6.js +0 -550
  668. package/dist/call-B3RFOu31.js +0 -3
  669. package/dist/call-CXrNXZSG.js +0 -331
  670. package/dist/call.runtime-Bugio2d3.js +0 -2
  671. package/dist/capability-cli-pJGFzz-O.js +0 -1401
  672. package/dist/catchup-CrbPmaLg.js +0 -300
  673. package/dist/channel-B4WFO5kS.js +0 -453
  674. package/dist/channel-Bps0dGDE.js +0 -350
  675. package/dist/channel-CJLpeJSt.js +0 -1174
  676. package/dist/channel-CYUpkO0S.js +0 -226
  677. package/dist/channel-D5z-JQQQ.js +0 -491
  678. package/dist/channel-DLMr2JrX.js +0 -840
  679. package/dist/channel-DN2Bbxr4.js +0 -297
  680. package/dist/channel-DnTz8nIj.js +0 -1320
  681. package/dist/channel-Do6Sn82m.js +0 -595
  682. package/dist/channel-DosZChc4.js +0 -1100
  683. package/dist/channel-core-CEJMwy5d.js +0 -5
  684. package/dist/channel-inbound-CTbUo5I-.js +0 -31
  685. package/dist/channel-lph4ihq7.js +0 -1802
  686. package/dist/channel-plugin-runtime-B8s8ZgGV.js +0 -771
  687. package/dist/channel-runtime-CXO7-2uH.js +0 -425
  688. package/dist/channel.runtime-7upS71Wm.js +0 -430
  689. package/dist/channel.runtime-C4N2Orn2.js +0 -2364
  690. package/dist/channel.runtime-Cq6zvOWk.js +0 -576
  691. package/dist/channel.runtime-Cu-K5Rnl.js +0 -89
  692. package/dist/channel.runtime-DSJtd27W.js +0 -34702
  693. package/dist/channel.runtime-hmlZOuOr.js +0 -109
  694. package/dist/channel.runtime-qZUF4q1y.js +0 -4
  695. package/dist/channel.setup-EtswhZ-5.js +0 -10
  696. package/dist/channels-DlLgFIEL.js +0 -733
  697. package/dist/channels-cli-Cv1aSrVt.js +0 -268
  698. package/dist/chat-cgThhSDG.js +0 -2830
  699. package/dist/clawbot-cli-BfueYVG9.js +0 -9
  700. package/dist/cli-BG5RGg3f.js +0 -2
  701. package/dist/cli-BgLyfMwF.js +0 -2
  702. package/dist/cli-CvaQw4bU.js +0 -219
  703. package/dist/cli-Dm7xZ13s.js +0 -72
  704. package/dist/cli-runner-BlgWVJXo.js +0 -286
  705. package/dist/cli-runner.runtime--S1ZJ4lZ.js +0 -3
  706. package/dist/cli-runner.runtime-CVCseHnV.js +0 -4
  707. package/dist/cli.runtime-CTTdFUzW.js +0 -1261
  708. package/dist/client-B9lOwn8c.js +0 -138
  709. package/dist/client-BEau5APW.js +0 -713
  710. package/dist/command-auth-DTahFy32.js +0 -76
  711. package/dist/command-config-resolution-D6OJJ7Rx.js +0 -2
  712. package/dist/command-config-resolution-DiPUCFaM.js +0 -23
  713. package/dist/command-config-resolution.runtime-Drw1DXrn.js +0 -2
  714. package/dist/command-registry-C84yTXlB.js +0 -4
  715. package/dist/command-registry-Dxs8vM2D.js +0 -9
  716. package/dist/command-registry-core-Ci-C0_aS.js +0 -106
  717. package/dist/command-secret-gateway-Dr4ZAWS0.js +0 -528
  718. package/dist/command-status.runtime-Dda0Zd8Z.js +0 -87
  719. package/dist/commands-acp-CrTmAH0X.js +0 -77
  720. package/dist/commands-compact.runtime-B8cmiAKp.js +0 -10
  721. package/dist/commands-handlers.runtime-DG9yo8q0.js +0 -4597
  722. package/dist/commands-status-B5WDtORx.js +0 -16
  723. package/dist/commands-status.runtime-BlsKZMk-.js +0 -3
  724. package/dist/commands-subagents-control.runtime-DpDJPuAt.js +0 -2
  725. package/dist/commands-subagents-control.runtime-LNEBP7S3.js +0 -3
  726. package/dist/commands-system-prompt-BlFAeIVs.js +0 -158
  727. package/dist/commands-system-prompt-D4tPPH2P.js +0 -2
  728. package/dist/commands.runtime-DuMRNQqD.js +0 -167
  729. package/dist/compact-CcTt-yl3.js +0 -1118
  730. package/dist/compact.runtime-wk_IPIX4.js +0 -12
  731. package/dist/completion-cli-CGlwqB-U.js +0 -328
  732. package/dist/config-KFRmI8ry.js +0 -252
  733. package/dist/config-cli-BF30K5jV.js +0 -1078
  734. package/dist/configure-DIvlblA7.js +0 -2
  735. package/dist/configure-xBBTFz12.js +0 -1252
  736. package/dist/connect-options-CmaVhl_a.js +0 -699
  737. package/dist/control-auth-7X91W5px.js +0 -125
  738. package/dist/control-service-gjyEQF5a.js +0 -156
  739. package/dist/conversation-id-Cm3M-EMu.js +0 -235
  740. package/dist/conversation-id-DSsIe83N.js +0 -38
  741. package/dist/conversation-runtime-D7csjEbc.js +0 -31
  742. package/dist/core-N5bGL7AS.js +0 -275
  743. package/dist/cron-cli-Dr60mrYn.js +0 -713
  744. package/dist/daemon-cli-BopomDRN.js +0 -12
  745. package/dist/dashboard-7inYLFoi.js +0 -2
  746. package/dist/dashboard-DkdAh9Cf.js +0 -81
  747. package/dist/delegate-B1wy3gyc.js +0 -64
  748. package/dist/detached-task-runtime-BonDnVGC.js +0 -73
  749. package/dist/devices-cli-D7Nym2Vg.js +0 -498
  750. package/dist/diagnostics-CKNsdABM.js +0 -154
  751. package/dist/direct-dm-BVYzdHiR.js +0 -64
  752. package/dist/dispatch-D2neSygE.js +0 -1131
  753. package/dist/dispatch-acp-Cohc4UYZ.js +0 -981
  754. package/dist/dispatch-acp-manager.runtime-DyRSpzhQ.js +0 -3
  755. package/dist/dispatch-acp.runtime-C17WGk85.js +0 -19
  756. package/dist/doctor-device-pairing-BB4zYdvg.js +0 -307
  757. package/dist/doctor-gateway-daemon-flow-QS9Fn3wN.js +0 -250
  758. package/dist/doctor-gateway-health-Bjr7AYDQ.js +0 -63
  759. package/dist/doctor-health-contributions-DowVYP_2.js +0 -493
  760. package/dist/doctor-health-u-RIUrNN.js +0 -59
  761. package/dist/doctor-prompter-C023W0vl.js +0 -56
  762. package/dist/doctor-workspace-status-Cw-cxdZG.js +0 -75
  763. package/dist/dreaming-BLHjEO-I.js +0 -1574
  764. package/dist/dreaming-narrative-BIsrYHc-.js +0 -595
  765. package/dist/embedded-gateway-stub.runtime-_lrYgFYo.js +0 -9
  766. package/dist/exec-approvals-cli-COkHlKzv.js +0 -498
  767. package/dist/fallbacks-BZ3NAd6v.js +0 -2
  768. package/dist/fallbacks-BZDGcLX6.js +0 -31
  769. package/dist/fallbacks-shared-CV6RVK4N.js +0 -111
  770. package/dist/gateway-cli-t10GNoWH.js +0 -1283
  771. package/dist/gateway-rpc-5f_FcBY1.js +0 -14
  772. package/dist/gateway-rpc.runtime-DYgojvBy.js +0 -23
  773. package/dist/gateway-runtime-Cbuk348j.js +0 -15
  774. package/dist/gateway-status-CoN-uDs8.js +0 -584
  775. package/dist/gateway-y4hbduse.js +0 -115
  776. package/dist/genesis-tools-BK7CnQKf.js +0 -9164
  777. package/dist/genesis-tools.runtime-0e_8eGGf.js +0 -2
  778. package/dist/get-reply-I0lMWdk8.js +0 -3880
  779. package/dist/get-reply-from-config.runtime-DDGGbL2i.js +0 -2
  780. package/dist/graph-users-BbbBkeu1.js +0 -1337
  781. package/dist/health-BQgAuj3n.js +0 -3
  782. package/dist/health-D4Kme7Dj.js +0 -469
  783. package/dist/health-route-BGHkUIrO.js +0 -41
  784. package/dist/health-route-DhHWHsOA.js +0 -2
  785. package/dist/heartbeat-runner-DCOhCcbJ.js +0 -5
  786. package/dist/heartbeat-runner-KRt3as14.js +0 -1292
  787. package/dist/heartbeat-runner.runtime-tqTiAsRJ.js +0 -4
  788. package/dist/hooks-cli-BV7EjR50.js +0 -433
  789. package/dist/image-fallbacks-BOV085zj.js +0 -2
  790. package/dist/image-fallbacks-CmXv64-q.js +0 -31
  791. package/dist/inbound-reply-dispatch-CCuTxi-T.js +0 -73
  792. package/dist/infra-runtime-D9FXWduH.js +0 -39
  793. package/dist/init-COvt7ThV.js +0 -59
  794. package/dist/library-MofkSYji.js +0 -45
  795. package/dist/lifecycle-C6kgqUbK.js +0 -229
  796. package/dist/lifecycle-CD4f62EF.js +0 -571
  797. package/dist/lifecycle.runtime-DUAiPJmF.js +0 -2
  798. package/dist/list-BonQsImY.js +0 -1212
  799. package/dist/list-Dtgubw__.js +0 -131
  800. package/dist/list-DuKAR9ei.js +0 -2
  801. package/dist/list-rr2_wvIB.js +0 -2
  802. package/dist/list.probe-DmCIIJZC.js +0 -419
  803. package/dist/llm-slug-generator-BGBzQWBi.js +0 -79
  804. package/dist/load-config-7ex3EkOv.js +0 -35
  805. package/dist/local-dispatch.runtime-CfgwapOU.js +0 -8
  806. package/dist/logs-cli-BELqEP8x.js +0 -265
  807. package/dist/logs-cli.runtime-zHhD6OSM.js +0 -2
  808. package/dist/main-session-restart-recovery-CEHasKb8.js +0 -206
  809. package/dist/managed-image-attachments-B9zAWYoW.js +0 -635
  810. package/dist/managed-image-attachments-CwpVLMeW.js +0 -2
  811. package/dist/manager-BQ-MUySl.js +0 -2
  812. package/dist/manager-CXmW50LU.js +0 -2057
  813. package/dist/markdown-to-line-D9wWNuYb.js +0 -790
  814. package/dist/mcp-cli-jTRNaa3W.js +0 -725
  815. package/dist/mcp-http-CZ1GgkfK.js +0 -529
  816. package/dist/media-runtime-B8-p8rcH.js +0 -329
  817. package/dist/memory-core-host-runtime-cli-Bkz5i6cR.js +0 -9
  818. package/dist/message-C_kshl7t.js +0 -232
  819. package/dist/message-action-runner-CTBYH3lG.js +0 -1407
  820. package/dist/message-action-runner-_oTHWXmy.js +0 -2
  821. package/dist/message-actions-CESdKiT8.js +0 -143
  822. package/dist/message.gateway.runtime-zmg8lqAq.js +0 -2
  823. package/dist/models-auth-status-BCx_AP1m.js +0 -201
  824. package/dist/models-cli-cax8Y7Qo.js +0 -219
  825. package/dist/monitor-BQNOgBfD.js +0 -1237
  826. package/dist/monitor-CNQ6gNpm.js +0 -2
  827. package/dist/monitor-CzvKNz0m.js +0 -1459
  828. package/dist/monitor-DAv3ZVJR.js +0 -671
  829. package/dist/monitor-DZDb1o_H.js +0 -1661
  830. package/dist/monitor-DrMqV1QN.js +0 -788
  831. package/dist/monitor-auth-CgQbaax8.js +0 -207
  832. package/dist/monitor-processing-B8p8ZzFV.js +0 -1974
  833. package/dist/monitor.runtime-CXPPZg89.js +0 -2
  834. package/dist/monitor.webhook-AXn2WwgR.js +0 -180
  835. package/dist/msteams-D-vjmlfB.js +0 -35
  836. package/dist/native-hook-relay-BNGqmIqP.js +0 -519
  837. package/dist/nextcloud-talk-CEb1u8ek.js +0 -17
  838. package/dist/node-cli-4O8-M9Bu.js +0 -2506
  839. package/dist/nodes-cli-Dp2OFP9C.js +0 -1046
  840. package/dist/nodes-utils-BQt-uuAy.js +0 -84
  841. package/dist/nodes.helpers-CR-REmRH.js +0 -34
  842. package/dist/notify-jWXMxIvz.js +0 -315
  843. package/dist/onboard-aFjTZo55.js +0 -2
  844. package/dist/onboard-helpers-Clk6YSB9.js +0 -6
  845. package/dist/onboard-helpers-WR8JC0sA.js +0 -204
  846. package/dist/onboard-interactive-CDL7gkJZ.js +0 -24
  847. package/dist/onboard-non-interactive-axuzhiqk.js +0 -548
  848. package/dist/onboard-remote-BebS0FvR.js +0 -193
  849. package/dist/onboard-remote-DBP9N9uh.js +0 -2
  850. package/dist/onboard-skills-BgYjlRl7.js +0 -134
  851. package/dist/onboard-skills-C2y9_grG.js +0 -2
  852. package/dist/onboard-vwvBfbu_.js +0 -70
  853. package/dist/openai-http-DwZFshcj.js +0 -500
  854. package/dist/openresponses-http-BO_-y-oL.js +0 -1128
  855. package/dist/operator-approvals-client-C7wUX5Ax.js +0 -68
  856. package/dist/outbound.runtime-DSddkqDF.js +0 -2
  857. package/dist/pair-command-approve-B-CbIXIO.js +0 -44
  858. package/dist/persistent-bindings.lifecycle-DMAuvd6i.js +0 -85
  859. package/dist/persistent-bindings.lifecycle-Dcg3uwBq.js +0 -2
  860. package/dist/pi-embedded-CvOg7wcF.js +0 -4
  861. package/dist/pi-embedded-DQaGB-R4.js +0 -2905
  862. package/dist/pi-embedded.runtime-8t4OGTNV.js +0 -4
  863. package/dist/pi-tool-definition-adapter-BhlKYDVK.js +0 -229
  864. package/dist/pi-tools-DdvLMQ3u.js +0 -1057
  865. package/dist/pi-tools.before-tool-call-BCXQH58o.js +0 -2
  866. package/dist/pi-tools.before-tool-call-Cy-n6vrl.js +0 -433
  867. package/dist/plugin-enabled-GMSZvoao.js +0 -140
  868. package/dist/plugin-laexn8kY.js +0 -12195
  869. package/dist/plugin-registration-CvaFhw6L.js +0 -23
  870. package/dist/plugin-service-trW8WHEK.js +0 -2892
  871. package/dist/policy-CMs3DL1U.js +0 -328
  872. package/dist/prepare.runtime-B2Ftte6a.js +0 -815
  873. package/dist/probe-Be9MFi-d.js +0 -241
  874. package/dist/probe-C-ZzogLP.js +0 -2
  875. package/dist/probe-CQlOVRaa.js +0 -2205
  876. package/dist/probe-CufvT4KQ.js +0 -1443
  877. package/dist/probe-DnrtsKGF.js +0 -45
  878. package/dist/probe-Vu0yRTL1.js +0 -74
  879. package/dist/probe-sEWN4BGj.js +0 -2
  880. package/dist/program-Bs9MRY9c.js +0 -111
  881. package/dist/prompt-select-styled-CGtVsUOS.js +0 -20
  882. package/dist/protocol-D7tGgtdQ.js +0 -2372
  883. package/dist/provider-dispatcher-ChMpF7-7.js +0 -22
  884. package/dist/provider-dispatcher-ClZbJIZe.js +0 -2
  885. package/dist/qr-cli-D_20PuX-.js +0 -349
  886. package/dist/qr-cli-L-xkvLJB.js +0 -2
  887. package/dist/qr-image-BbjltFeM.js +0 -2
  888. package/dist/reaction-runtime-api-CgQ5EpV8.js +0 -116
  889. package/dist/reactions-z8cZhMQS.js +0 -998
  890. package/dist/register-service-commands-CCrrihXZ.js +0 -71
  891. package/dist/register.agent-ChtGYOfw.js +0 -248
  892. package/dist/register.configure-COxo_hIE.js +0 -15
  893. package/dist/register.maintenance-DnHQDu4T.js +0 -363
  894. package/dist/register.message-CKAW7WCM.js +0 -329
  895. package/dist/register.onboard-DqEkyhrT.js +0 -88
  896. package/dist/register.runtime-BY3ycMNz.js +0 -81
  897. package/dist/register.setup-BinpG73l.js +0 -150
  898. package/dist/register.status-health-sessions-DOUnNyO2.js +0 -1215
  899. package/dist/register.subclis-CU4u9EcO.js +0 -3
  900. package/dist/register.subclis-D0jzK960.js +0 -29
  901. package/dist/register.subclis-core-C-EI-6S4.js +0 -249
  902. package/dist/reply-dispatch-runtime-BFdthUjd.js +0 -13
  903. package/dist/reply-runtime-kNWD7YKe.js +0 -11
  904. package/dist/reply.runtime-B-Jl6fmq.js +0 -2
  905. package/dist/restart-health-BhaX-Pty.js +0 -202
  906. package/dist/restart-health-Iq6YJfXC.js +0 -2
  907. package/dist/root-help-DXADcbxs.js +0 -44
  908. package/dist/routes-CaBn__dI.js +0 -2
  909. package/dist/routes-DzONgo3O.js +0 -3341
  910. package/dist/rpc-TEA1EWn2.js +0 -61
  911. package/dist/rpc.runtime-BbuRkBYg.js +0 -21
  912. package/dist/run-delivery.runtime-BVEcJuw3.js +0 -530
  913. package/dist/run-embedded.runtime-Bgu-BcLh.js +0 -4
  914. package/dist/run-execution-cli.runtime-DkGD5vIe.js +0 -4
  915. package/dist/run-executor.runtime-k_OPvI-2.js +0 -277
  916. package/dist/run-main-B6pYjgw6.js +0 -567
  917. package/dist/run-subagent-registry.runtime-C02oJGJ0.js +0 -2
  918. package/dist/run-wait-BERZZe_n.js +0 -135
  919. package/dist/runtime-Cc-woQCq.js +0 -973
  920. package/dist/runtime-DZFBse20.js +0 -9
  921. package/dist/runtime-api-Ajj7BCx-.js +0 -14
  922. package/dist/runtime-api-B0xZ4nEY.js +0 -4
  923. package/dist/runtime-api-CZ8HC4j8.js +0 -9
  924. package/dist/runtime-api-DUOrTrka.js +0 -9
  925. package/dist/runtime-embedded-pi.runtime-tnnBA49e.js +0 -2
  926. package/dist/runtime-internal-BnOKjKJw.js +0 -2
  927. package/dist/runtime-options-Dtk_3gHA.js +0 -275
  928. package/dist/runtime-schema-BWZYiV_d.js +0 -28250
  929. package/dist/sanitize-text-DRc9fwAb.js +0 -26
  930. package/dist/scan-BwZdHVy1.js +0 -523
  931. package/dist/scan-DCoFSZdN.js +0 -2
  932. package/dist/secrets-cli-BubH9FE5.js +0 -2101
  933. package/dist/security-cli-BsSUnMYe.js +0 -486
  934. package/dist/selection-BD1Uck1e.js +0 -7764
  935. package/dist/selection-DDFlJOQT.js +0 -2
  936. package/dist/send-DF0muFvI.js +0 -102
  937. package/dist/send-DG3mpua5.js +0 -156
  938. package/dist/send.runtime-DqL5NAUQ.js +0 -2
  939. package/dist/server-DLrf094d.js +0 -13
  940. package/dist/server-LFbvHfac.js +0 -77
  941. package/dist/server-context-qD0sYHp9.js +0 -847
  942. package/dist/server-context-wxNlgoCi.js +0 -2
  943. package/dist/server-node-events-0NztN4d_.js +0 -481
  944. package/dist/server-plugin-bootstrap-COMPgJRl.js +0 -11676
  945. package/dist/server-plugin-bootstrap-qTnE3JsA.js +0 -2
  946. package/dist/server-restart-sentinel-Cp8cFKA8.js +0 -697
  947. package/dist/server.impl-DS1IsVAk.js +0 -12822
  948. package/dist/session-kill-http-C84Uo9c_.js +0 -110
  949. package/dist/session-reset-service-cYmNWDfY.js +0 -471
  950. package/dist/session-route-jcFA4V4z.js +0 -93
  951. package/dist/session-status.runtime-DqQ4rLiE.js +0 -2
  952. package/dist/session-subagent-reactivation.runtime-CqoWaNFA.js +0 -2
  953. package/dist/session-tab-registry-DA1BZ9QF.js +0 -581
  954. package/dist/session-visibility-DhV7N2Pi.js +0 -147
  955. package/dist/sessions-helpers-B-g8n5mW.js +0 -304
  956. package/dist/sessions-history-http-0LvIW-7e.js +0 -383
  957. package/dist/sessions-patch-DMy4G3Eu.js +0 -309
  958. package/dist/sessions-resolve-C9OvN0xm.js +0 -174
  959. package/dist/sessions.runtime-UTiDYDgG.js +0 -2
  960. package/dist/setup-B6pSihNi.js +0 -505
  961. package/dist/setup-api-D2MFym1w.js +0 -29
  962. package/dist/setup-core-CFwlqZAq.js +0 -171
  963. package/dist/setup-core-yUQ2ET1t.js +0 -176
  964. package/dist/setup-surface-CgsDht94.js +0 -219
  965. package/dist/setup-surface-DUVBHVB5.js +0 -286
  966. package/dist/setup-surface-Dwo7B1MF.js +0 -403
  967. package/dist/setup.finalize-DIHLSogt.js +0 -547
  968. package/dist/setup.gateway-config-CYweAHjs.js +0 -250
  969. package/dist/shared-CtsGiWGX.js +0 -121
  970. package/dist/shared-Cxs6ZTG6.js +0 -198
  971. package/dist/shared-D0_fkOes.js +0 -76
  972. package/dist/slash-state-B6OljZFV.js +0 -1911
  973. package/dist/speech-provider-CniAck7S.js +0 -209
  974. package/dist/speech-provider-D3mHiAUJ.js +0 -216
  975. package/dist/src-BSaFmwjO.js +0 -3974
  976. package/dist/startup-context-CylpwAvi.js +0 -312
  977. package/dist/status-Bbe3bSQ7.js +0 -3
  978. package/dist/status-BeKbJtNe.js +0 -397
  979. package/dist/status-BxxIIMMc.js +0 -190
  980. package/dist/status-D78J6vFR.js +0 -209
  981. package/dist/status-DHUoYUAy.js +0 -2
  982. package/dist/status-DXCQZdA3.js +0 -2
  983. package/dist/status-all-RpxA8QNU.js +0 -498
  984. package/dist/status-json-Cm0_z6uV.js +0 -14
  985. package/dist/status-json-command-IYMsErWj.js +0 -84
  986. package/dist/status-runtime-shared-jZGl7M1u.js +0 -257
  987. package/dist/status-subagents.runtime-D9ASiL_W.js +0 -18
  988. package/dist/status-text-BDWCyjPZ.js +0 -237
  989. package/dist/status.gateway-connection.runtime-D38pAArd.js +0 -2
  990. package/dist/status.gather-BeQKVWmL.js +0 -292
  991. package/dist/status.gather-Bs6DyO_l.js +0 -2
  992. package/dist/status.runtime-Dd-4IvgW.js +0 -2
  993. package/dist/status.scan-BQ2rWJwx.js +0 -65
  994. package/dist/status.scan-overview-bDkVoMWI.js +0 -379
  995. package/dist/status.scan.fast-json-BDzskgig.js +0 -132
  996. package/dist/status.scan.fast-json-BZap0hwW.js +0 -2
  997. package/dist/status.summary-BVVCmDxX.js +0 -214
  998. package/dist/status.summary-DEjaPu97.js +0 -2
  999. package/dist/subagent-announce-BHMghSij.js +0 -351
  1000. package/dist/subagent-announce-delivery-2H9ziRB5.js +0 -726
  1001. package/dist/subagent-announce-output-CO0STTst.js +0 -364
  1002. package/dist/subagent-control-BlUvXw3O.js +0 -506
  1003. package/dist/subagent-followup.runtime-B-cXGMr3.js +0 -68
  1004. package/dist/subagent-orphan-recovery-DtevfNOh.js +0 -305
  1005. package/dist/subagent-registry-NMafO8zg.js +0 -3
  1006. package/dist/subagent-registry-kYRi3BuO.js +0 -1753
  1007. package/dist/subagent-spawn-jdyHNBeU.js +0 -1005
  1008. package/dist/system-cli-Cr-OHOKc.js +0 -59
  1009. package/dist/targets-BD8lqoiw.js +0 -67
  1010. package/dist/task-executor-C6nLwZUw.js +0 -360
  1011. package/dist/task-owner-access-CL15O6-D.js +0 -74
  1012. package/dist/task-registry-Dop4Hvgu.js +0 -2366
  1013. package/dist/task-registry-delivery-runtime-B4-WN9a1.js +0 -2
  1014. package/dist/task-registry-delivery-runtime-Cmefypxg.js +0 -3
  1015. package/dist/task-registry.maintenance-BzaKjSIp.js +0 -2
  1016. package/dist/task-registry.maintenance-CE523hMF.js +0 -416
  1017. package/dist/testing-ByMyLWYF.js +0 -575
  1018. package/dist/text-report-BjqWPSdn.js +0 -587
  1019. package/dist/tool-resolution-Bww5_SCZ.js +0 -90
  1020. package/dist/tools-effective-inventory-BgOSznr9.js +0 -152
  1021. package/dist/tools-invoke-http-B2vzHENc.js +0 -206
  1022. package/dist/trash-Ck-S6m2U.js +0 -24
  1023. package/dist/tui-cli-BqULRECV.js +0 -4575
  1024. package/dist/update-cli-B5M83U6A.js +0 -1759
  1025. package/dist/upgrade-CPk_uU8j.js +0 -1226
  1026. package/dist/video-generation-task-status-BEQYHgBW.js +0 -163
  1027. package/dist/wait-for-idle-before-flush-DcTql_s0.js +0 -5986
  1028. package/dist/wizard-models-h7BWimF-.js +0 -334
@@ -0,0 +1,2830 @@
1
+ import { i as formatErrorMessage } from "./errors-Jbvi20TW.js";
2
+ import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, f as readStringValue } from "./string-coerce-C1IzJjqi.js";
3
+ import { o as parseAgentSessionKey } from "./session-key-utils-BT0y7mVK.js";
4
+ import { r as normalizeProviderId } from "./provider-id-BLh32HP1.js";
5
+ import { p as resolveSessionAgentId } from "./agent-scope-CDjZLqNk.js";
6
+ import { r as setSafeTimeout } from "./timer-delay-Co_I1iPe.js";
7
+ import { a as hasGatewayClientCap, i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES, t as GATEWAY_CLIENT_CAPS } from "./client-info-CfESmEX1.js";
8
+ import { r as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-core-CtbksRwN.js";
9
+ import { n as isGatewayCliClient, o as isWebchatClient, u as normalizeMessageChannel } from "./message-channel-BbI8d0sw.js";
10
+ import { b as validateChatInjectParams, gn as errorShape, hn as ErrorCodes, t as formatValidationErrors, v as validateChatAbortParams, x as validateChatSendParams, y as validateChatHistoryParams } from "./protocol-Bi30vNUf.js";
11
+ import { a as normalizeInputProvenance } from "./input-provenance-Dr0BI482.js";
12
+ import { o as ADMIN_SCOPE } from "./method-scopes-0Sax7Hw3.js";
13
+ import { p as resolveThinkingDefault } from "./model-selection-BJS5Z_AY.js";
14
+ import { i as resolveSessionFilePath } from "./paths-DD6L4IvS.js";
15
+ import "./sessions-rtgiO_I5.js";
16
+ import { t as emitSessionTranscriptUpdate } from "./transcript-events-DlllnQhZ.js";
17
+ import { c as stripEnvelopeFromMessages, i as readSessionMessages, n as capArrayByJsonBytes, p as jsonUtf8Bytes, s as stripEnvelopeFromMessage, t as attachGenesisTranscriptMeta } from "./session-utils.fs-8ElKDDc9.js";
18
+ import { o as parseAssistantTextSignature, s as resolveAssistantMessagePhase } from "./chat-message-content-f1D-O-pU.js";
19
+ import { a as stripInlineDirectiveTagsFromMessageForDisplay, i as stripInlineDirectiveTagsForDisplay, n as sanitizeReplyDirectiveId } from "./directive-tags-Db1TRP8U.js";
20
+ import { n as stripInboundMetadata } from "./strip-inbound-meta-BpubGgAq.js";
21
+ import { a as loadSessionEntry, c as resolveDeletedAgentIdFromSessionKey, p as resolveSessionModelRef, u as resolveGatewayModelSupportsImages } from "./session-utils-R4i-HQDD.js";
22
+ import { a as isSilentReplyText, n as SILENT_REPLY_TOKEN } from "./tokens-Bq9TB3gs.js";
23
+ import { a as isAudioFileName, c as mimeTypeFromFilePath, h as mediaKindFromMime, l as normalizeMimeType } from "./mime-DucH9KF3.js";
24
+ import { i as normalizeReplyPayloadsForDelivery } from "./payloads-UZ7eO_3Y.js";
25
+ import { m as resolveSendableOutboundReplyParts } from "./reply-payload-ChFsXpe2.js";
26
+ import { a as safeFileURLToPath, t as assertNoWindowsNetworkPath } from "./local-file-access-DgmtufHS.js";
27
+ import { r as getAgentScopedMediaLocalRoots, t as appendLocalMediaParentRoots } from "./local-roots-CENIlVYe.js";
28
+ import { l as saveMediaBuffer } from "./store-BLvGOOM1.js";
29
+ import { n as assertLocalMediaAllowed, t as LocalMediaAccessError } from "./local-media-access-EFjNHZJ6.js";
30
+ import { r as getSessionBindingService } from "./session-binding-service-DzTd4LUl.js";
31
+ import { t as resolveAgentTimeoutMs } from "./timeout-BSZPJ2oJ.js";
32
+ import { t as rewriteTranscriptEntriesInSessionFile } from "./transcript-rewrite-DgWJ2DVN.js";
33
+ import { u as isPluginOwnedSessionBindingRecord } from "./conversation-binding-BgzB_fBO.js";
34
+ import { n as isAbortRequestText } from "./abort-primitives-8_A98hNS.js";
35
+ import { i as createReplyDispatcher, t as dispatchInboundMessage } from "./dispatch-CtoAa2rI.js";
36
+ import { n as resolveSendPolicy } from "./send-policy-C-G8KVhh.js";
37
+ import { t as createChannelReplyPipeline } from "./channel-reply-pipeline-BWizVKPH.js";
38
+ import { t as formatForLog } from "./ws-log-BG1U86rU.js";
39
+ import { G as logLargePayload } from "./http-utils-Bvm05EsM.js";
40
+ import { n as MediaOffloadError, r as parseMessageWithAttachments, t as normalizeRpcAttachmentsToChatAttachments } from "./attachment-normalize-bkyEcvMC.js";
41
+ import { i as createManagedOutgoingImageBlocks, n as attachManagedOutgoingImagesToMessage, r as cleanupManagedOutgoingImageRecords } from "./managed-image-attachments-D880KVE3.js";
42
+ import { n as timestampOptsFromConfig, t as injectTimestamp } from "./agent-timestamp-BiqcBU_f.js";
43
+ import fs from "node:fs";
44
+ import path from "node:path";
45
+ import os from "node:os";
46
+ import { CURRENT_SESSION_VERSION, SessionManager } from "@mariozechner/pi-coding-agent";
47
+ //#region src/chat/tool-content.ts
48
+ function normalizeToolContentType(value) {
49
+ return typeof value === "string" ? value.toLowerCase() : "";
50
+ }
51
+ function isToolCallContentType(value) {
52
+ const type = normalizeToolContentType(value);
53
+ return type === "toolcall" || type === "tool_call" || type === "tooluse" || type === "tool_use";
54
+ }
55
+ function isToolResultContentType(value) {
56
+ const type = normalizeToolContentType(value);
57
+ return type === "toolresult" || type === "tool_result";
58
+ }
59
+ function isToolCallBlock(block) {
60
+ return isToolCallContentType(block.type);
61
+ }
62
+ function isToolResultBlock(block) {
63
+ return isToolResultContentType(block.type);
64
+ }
65
+ function resolveToolUseId(block) {
66
+ return typeof block.id === "string" && block.id.trim() || typeof block.tool_use_id === "string" && block.tool_use_id.trim() || typeof block.toolUseId === "string" && block.toolUseId.trim() || void 0;
67
+ }
68
+ //#endregion
69
+ //#region src/gateway/cli-session-history.claude.ts
70
+ const CLAUDE_CLI_PROVIDER = "claude-cli";
71
+ const CLAUDE_PROJECTS_RELATIVE_DIR = path.join(".claude", "projects");
72
+ function resolveHistoryHomeDir(homeDir) {
73
+ return normalizeOptionalString(homeDir) || process.env.HOME || os.homedir();
74
+ }
75
+ function resolveClaudeProjectsDir(homeDir) {
76
+ return path.join(resolveHistoryHomeDir(homeDir), CLAUDE_PROJECTS_RELATIVE_DIR);
77
+ }
78
+ function resolveClaudeCliBindingSessionId(entry) {
79
+ const bindingSessionId = normalizeOptionalString(entry?.cliSessionBindings?.[CLAUDE_CLI_PROVIDER]?.sessionId);
80
+ if (bindingSessionId) return bindingSessionId;
81
+ const legacyMapSessionId = normalizeOptionalString(entry?.cliSessionIds?.[CLAUDE_CLI_PROVIDER]);
82
+ if (legacyMapSessionId) return legacyMapSessionId;
83
+ return normalizeOptionalString(entry?.claudeCliSessionId) || void 0;
84
+ }
85
+ function resolveFiniteNumber$1(value) {
86
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
87
+ }
88
+ function resolveTimestampMs(value) {
89
+ if (typeof value !== "string") return;
90
+ const parsed = Date.parse(value);
91
+ return Number.isFinite(parsed) ? parsed : void 0;
92
+ }
93
+ function resolveClaudeCliUsage(raw) {
94
+ if (!raw || typeof raw !== "object") return;
95
+ const input = resolveFiniteNumber$1(raw.input_tokens);
96
+ const output = resolveFiniteNumber$1(raw.output_tokens);
97
+ const cacheRead = resolveFiniteNumber$1(raw.cache_read_input_tokens);
98
+ const cacheWrite = resolveFiniteNumber$1(raw.cache_creation_input_tokens);
99
+ if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0) return;
100
+ return {
101
+ ...input !== void 0 ? { input } : {},
102
+ ...output !== void 0 ? { output } : {},
103
+ ...cacheRead !== void 0 ? { cacheRead } : {},
104
+ ...cacheWrite !== void 0 ? { cacheWrite } : {}
105
+ };
106
+ }
107
+ function cloneJsonValue(value) {
108
+ return structuredClone(value);
109
+ }
110
+ function normalizeClaudeCliContent(content, toolNameRegistry) {
111
+ if (!Array.isArray(content)) return cloneJsonValue(content);
112
+ const normalized = [];
113
+ for (const item of content) {
114
+ if (!item || typeof item !== "object") {
115
+ normalized.push(cloneJsonValue(item));
116
+ continue;
117
+ }
118
+ const block = cloneJsonValue(item);
119
+ const type = typeof block.type === "string" ? block.type : "";
120
+ if (type === "tool_use") {
121
+ const id = normalizeOptionalString(block.id) ?? "";
122
+ const name = normalizeOptionalString(block.name) ?? "";
123
+ if (id && name) toolNameRegistry.set(id, name);
124
+ if (block.input !== void 0 && block.arguments === void 0) block.arguments = cloneJsonValue(block.input);
125
+ block.type = "toolcall";
126
+ delete block.input;
127
+ normalized.push(block);
128
+ continue;
129
+ }
130
+ if (type === "tool_result") {
131
+ const toolUseId = resolveToolUseId(block);
132
+ if (!block.name && toolUseId) {
133
+ const toolName = toolNameRegistry.get(toolUseId);
134
+ if (toolName) block.name = toolName;
135
+ }
136
+ normalized.push(block);
137
+ continue;
138
+ }
139
+ normalized.push(block);
140
+ }
141
+ return normalized;
142
+ }
143
+ function getMessageBlocks(message) {
144
+ if (!message || typeof message !== "object") return null;
145
+ const content = message.content;
146
+ return Array.isArray(content) ? content : null;
147
+ }
148
+ function isAssistantToolCallMessage(message) {
149
+ if (!message || typeof message !== "object") return false;
150
+ if (message.role !== "assistant") return false;
151
+ const blocks = getMessageBlocks(message);
152
+ return Boolean(blocks && blocks.length > 0 && blocks.every(isToolCallBlock));
153
+ }
154
+ function isUserToolResultMessage(message) {
155
+ if (!message || typeof message !== "object") return false;
156
+ if (message.role !== "user") return false;
157
+ const blocks = getMessageBlocks(message);
158
+ return Boolean(blocks && blocks.length > 0 && blocks.every(isToolResultBlock));
159
+ }
160
+ function coalesceClaudeCliToolMessages(messages) {
161
+ const coalesced = [];
162
+ for (let index = 0; index < messages.length; index += 1) {
163
+ const current = messages[index];
164
+ const next = messages[index + 1];
165
+ if (!isAssistantToolCallMessage(current) || !isUserToolResultMessage(next)) {
166
+ coalesced.push(current);
167
+ continue;
168
+ }
169
+ const callBlocks = getMessageBlocks(current) ?? [];
170
+ const resultBlocks = getMessageBlocks(next) ?? [];
171
+ const callIds = new Set(callBlocks.map(resolveToolUseId).filter((id) => Boolean(id)));
172
+ if (!(resultBlocks.length > 0 && resultBlocks.every((block) => {
173
+ const toolUseId = resolveToolUseId(block);
174
+ return Boolean(toolUseId && callIds.has(toolUseId));
175
+ }))) {
176
+ coalesced.push(current);
177
+ continue;
178
+ }
179
+ coalesced.push({
180
+ ...current,
181
+ content: [...callBlocks.map(cloneJsonValue), ...resultBlocks.map(cloneJsonValue)]
182
+ });
183
+ index += 1;
184
+ }
185
+ return coalesced;
186
+ }
187
+ function parseClaudeCliHistoryEntry(entry, cliSessionId, toolNameRegistry) {
188
+ if (entry.isSidechain === true || !entry.message || typeof entry.message !== "object") return null;
189
+ const type = typeof entry.type === "string" ? entry.type : void 0;
190
+ const role = typeof entry.message.role === "string" ? entry.message.role : void 0;
191
+ if (type !== "user" && type !== "assistant" || role !== type) return null;
192
+ const timestamp = resolveTimestampMs(entry.timestamp);
193
+ const baseMeta = {
194
+ importedFrom: CLAUDE_CLI_PROVIDER,
195
+ cliSessionId,
196
+ ...normalizeOptionalString(entry.uuid) ? { externalId: entry.uuid } : {}
197
+ };
198
+ const content = typeof entry.message.content === "string" || Array.isArray(entry.message.content) ? normalizeClaudeCliContent(entry.message.content, toolNameRegistry) : void 0;
199
+ if (content === void 0) return null;
200
+ if (type === "user") return attachGenesisTranscriptMeta({
201
+ role: "user",
202
+ content,
203
+ ...timestamp !== void 0 ? { timestamp } : {}
204
+ }, baseMeta);
205
+ return attachGenesisTranscriptMeta({
206
+ role: "assistant",
207
+ content,
208
+ api: "anthropic-messages",
209
+ provider: CLAUDE_CLI_PROVIDER,
210
+ ...normalizeOptionalString(entry.message.model) ? { model: entry.message.model } : {},
211
+ ...normalizeOptionalString(entry.message.stop_reason) ? { stopReason: entry.message.stop_reason } : {},
212
+ ...resolveClaudeCliUsage(entry.message.usage) ? { usage: resolveClaudeCliUsage(entry.message.usage) } : {},
213
+ ...timestamp !== void 0 ? { timestamp } : {}
214
+ }, baseMeta);
215
+ }
216
+ function resolveClaudeCliSessionFilePath(params) {
217
+ const projectsDir = resolveClaudeProjectsDir(params.homeDir);
218
+ let projectEntries;
219
+ try {
220
+ projectEntries = fs.readdirSync(projectsDir, { withFileTypes: true });
221
+ } catch {
222
+ return;
223
+ }
224
+ for (const entry of projectEntries) {
225
+ if (!entry.isDirectory()) continue;
226
+ const candidate = path.join(projectsDir, entry.name, `${params.cliSessionId}.jsonl`);
227
+ if (fs.existsSync(candidate)) return candidate;
228
+ }
229
+ }
230
+ function readClaudeCliSessionMessages(params) {
231
+ const filePath = resolveClaudeCliSessionFilePath(params);
232
+ if (!filePath) return [];
233
+ let content;
234
+ try {
235
+ content = fs.readFileSync(filePath, "utf-8");
236
+ } catch {
237
+ return [];
238
+ }
239
+ const messages = [];
240
+ const toolNameRegistry = /* @__PURE__ */ new Map();
241
+ for (const line of content.split(/\r?\n/)) {
242
+ if (!line.trim()) continue;
243
+ try {
244
+ const message = parseClaudeCliHistoryEntry(JSON.parse(line), params.cliSessionId, toolNameRegistry);
245
+ if (message) messages.push(message);
246
+ } catch {}
247
+ }
248
+ return coalesceClaudeCliToolMessages(messages);
249
+ }
250
+ //#endregion
251
+ //#region src/gateway/cli-session-history.merge.ts
252
+ const DEDUPE_TIMESTAMP_WINDOW_MS = 300 * 1e3;
253
+ function extractComparableText(message) {
254
+ if (!message || typeof message !== "object") return;
255
+ const record = message;
256
+ const role = readStringValue(record.role);
257
+ const parts = [];
258
+ const text = readStringValue(record.text);
259
+ if (text !== void 0) parts.push(text);
260
+ const content = readStringValue(record.content);
261
+ if (content !== void 0) parts.push(content);
262
+ else if (Array.isArray(record.content)) {
263
+ for (const block of record.content) if (block && typeof block === "object" && "text" in block) {
264
+ const blockText = readStringValue(block.text);
265
+ if (blockText !== void 0) parts.push(blockText);
266
+ }
267
+ }
268
+ if (parts.length === 0) return;
269
+ const joined = parts.join("\n").trim();
270
+ if (!joined) return;
271
+ return (role === "user" ? stripInboundMetadata(joined) : joined).replace(/\s+/g, " ").trim() || void 0;
272
+ }
273
+ function resolveFiniteNumber(value) {
274
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
275
+ }
276
+ function resolveComparableTimestamp(message) {
277
+ if (!message || typeof message !== "object") return;
278
+ return resolveFiniteNumber(message.timestamp);
279
+ }
280
+ function resolveComparableRole(message) {
281
+ if (!message || typeof message !== "object") return;
282
+ return readStringValue(message.role);
283
+ }
284
+ function resolveImportedExternalId(message) {
285
+ if (!message || typeof message !== "object") return;
286
+ return normalizeOptionalString(("__genesis" in message && message.__genesis && typeof message.__genesis === "object" ? message.__genesis ?? {} : void 0)?.externalId);
287
+ }
288
+ function isEquivalentImportedMessage(existing, imported) {
289
+ const importedExternalId = resolveImportedExternalId(imported);
290
+ if (importedExternalId && resolveImportedExternalId(existing) === importedExternalId) return true;
291
+ const existingRole = resolveComparableRole(existing);
292
+ const importedRole = resolveComparableRole(imported);
293
+ if (!existingRole || existingRole !== importedRole) return false;
294
+ const existingText = extractComparableText(existing);
295
+ const importedText = extractComparableText(imported);
296
+ if (!existingText || !importedText || existingText !== importedText) return false;
297
+ const existingTimestamp = resolveComparableTimestamp(existing);
298
+ const importedTimestamp = resolveComparableTimestamp(imported);
299
+ if (existingTimestamp === void 0 || importedTimestamp === void 0) return true;
300
+ return Math.abs(existingTimestamp - importedTimestamp) <= DEDUPE_TIMESTAMP_WINDOW_MS;
301
+ }
302
+ function compareHistoryMessages(a, b) {
303
+ const aTimestamp = resolveComparableTimestamp(a.message);
304
+ const bTimestamp = resolveComparableTimestamp(b.message);
305
+ if (aTimestamp !== void 0 && bTimestamp !== void 0 && aTimestamp !== bTimestamp) return aTimestamp - bTimestamp;
306
+ if (aTimestamp !== void 0 && bTimestamp === void 0) return -1;
307
+ if (aTimestamp === void 0 && bTimestamp !== void 0) return 1;
308
+ return a.order - b.order;
309
+ }
310
+ function mergeImportedChatHistoryMessages(params) {
311
+ if (params.importedMessages.length === 0) return params.localMessages;
312
+ const merged = params.localMessages.map((message, index) => ({
313
+ message,
314
+ order: index
315
+ }));
316
+ let nextOrder = merged.length;
317
+ for (const imported of params.importedMessages) {
318
+ if (merged.some((existing) => isEquivalentImportedMessage(existing.message, imported))) continue;
319
+ merged.push({
320
+ message: imported,
321
+ order: nextOrder
322
+ });
323
+ nextOrder += 1;
324
+ }
325
+ merged.sort(compareHistoryMessages);
326
+ return merged.map((entry) => entry.message);
327
+ }
328
+ //#endregion
329
+ //#region src/gateway/cli-session-history.ts
330
+ function augmentChatHistoryWithCliSessionImports(params) {
331
+ const cliSessionId = resolveClaudeCliBindingSessionId(params.entry);
332
+ if (!cliSessionId) return params.localMessages;
333
+ const normalizedProvider = normalizeProviderId(params.provider ?? "");
334
+ if (normalizedProvider && normalizedProvider !== "claude-cli" && params.localMessages.length > 0) return params.localMessages;
335
+ const importedMessages = readClaudeCliSessionMessages({
336
+ cliSessionId,
337
+ homeDir: params.homeDir
338
+ });
339
+ return mergeImportedChatHistoryMessages({
340
+ localMessages: params.localMessages,
341
+ importedMessages
342
+ });
343
+ }
344
+ //#endregion
345
+ //#region src/gateway/server-constants.ts
346
+ const MAX_PAYLOAD_BYTES = 25 * 1024 * 1024;
347
+ const MAX_BUFFERED_BYTES = 50 * 1024 * 1024;
348
+ const MAX_PREAUTH_PAYLOAD_BYTES = 64 * 1024;
349
+ let maxChatHistoryMessagesBytes = 6 * 1024 * 1024;
350
+ const getMaxChatHistoryMessagesBytes = () => maxChatHistoryMessagesBytes;
351
+ const TICK_INTERVAL_MS = 3e4;
352
+ const HEALTH_REFRESH_INTERVAL_MS = 6e4;
353
+ const DEDUPE_TTL_MS = 5 * 6e4;
354
+ const DEDUPE_MAX = 1e3;
355
+ //#endregion
356
+ //#region src/chat/canvas-render.ts
357
+ function tryParseJsonRecord(value) {
358
+ if (typeof value !== "string") return;
359
+ try {
360
+ const parsed = JSON.parse(value);
361
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
362
+ } catch {
363
+ return;
364
+ }
365
+ }
366
+ function getRecordStringField(record, key) {
367
+ const value = record?.[key];
368
+ return typeof value === "string" && value.trim() ? value : void 0;
369
+ }
370
+ function getRecordNumberField(record, key) {
371
+ const value = record?.[key];
372
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
373
+ }
374
+ function getNestedRecord(record, key) {
375
+ const value = record?.[key];
376
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
377
+ }
378
+ function normalizeSurface(value) {
379
+ return value === "assistant_message" ? value : void 0;
380
+ }
381
+ function normalizePreferredHeight(value) {
382
+ return typeof value === "number" && Number.isFinite(value) && value >= 160 ? Math.min(Math.trunc(value), 1200) : void 0;
383
+ }
384
+ function coerceCanvasPreview(record) {
385
+ if (!record) return;
386
+ if (getRecordStringField(record, "kind")?.trim().toLowerCase() !== "canvas") return;
387
+ const presentation = getNestedRecord(record, "presentation");
388
+ const view = getNestedRecord(record, "view");
389
+ const source = getNestedRecord(record, "source");
390
+ const requestedSurface = getRecordStringField(presentation, "target") ?? getRecordStringField(record, "target");
391
+ const surface = requestedSurface ? normalizeSurface(requestedSurface) : "assistant_message";
392
+ if (!surface) return;
393
+ const title = getRecordStringField(presentation, "title") ?? getRecordStringField(view, "title");
394
+ const preferredHeight = normalizePreferredHeight(getRecordNumberField(presentation, "preferred_height") ?? getRecordNumberField(presentation, "preferredHeight") ?? getRecordNumberField(view, "preferred_height") ?? getRecordNumberField(view, "preferredHeight"));
395
+ const className = getRecordStringField(presentation, "class_name") ?? getRecordStringField(presentation, "className");
396
+ const style = getRecordStringField(presentation, "style");
397
+ const viewUrl = getRecordStringField(view, "url") ?? getRecordStringField(view, "entryUrl");
398
+ const viewId = getRecordStringField(view, "id") ?? getRecordStringField(view, "docId");
399
+ if (viewUrl) return {
400
+ kind: "canvas",
401
+ surface,
402
+ render: "url",
403
+ url: viewUrl,
404
+ ...viewId ? { viewId } : {},
405
+ ...title ? { title } : {},
406
+ ...preferredHeight ? { preferredHeight } : {},
407
+ ...className ? { className } : {},
408
+ ...style ? { style } : {}
409
+ };
410
+ if (getRecordStringField(source, "type")?.trim().toLowerCase() === "url") {
411
+ const url = getRecordStringField(source, "url");
412
+ if (!url) return;
413
+ return {
414
+ kind: "canvas",
415
+ surface,
416
+ render: "url",
417
+ url,
418
+ ...title ? { title } : {},
419
+ ...preferredHeight ? { preferredHeight } : {},
420
+ ...className ? { className } : {},
421
+ ...style ? { style } : {}
422
+ };
423
+ }
424
+ }
425
+ function extractCanvasFromText(outputText, _toolName) {
426
+ return coerceCanvasPreview(tryParseJsonRecord(outputText));
427
+ }
428
+ //#endregion
429
+ //#region src/gateway/chat-abort.ts
430
+ const DEFAULT_CHAT_RUN_ABORT_GRACE_MS = 6e4;
431
+ function isChatStopCommandText(text) {
432
+ return isAbortRequestText(text);
433
+ }
434
+ function resolveChatRunExpiresAtMs(params) {
435
+ const { now, timeoutMs, graceMs = DEFAULT_CHAT_RUN_ABORT_GRACE_MS, minMs = 2 * 6e4, maxMs = 1440 * 6e4 } = params;
436
+ const target = now + Math.max(0, timeoutMs) + graceMs;
437
+ const min = now + minMs;
438
+ const max = now + maxMs;
439
+ return Math.min(max, Math.max(min, target));
440
+ }
441
+ function resolveAgentRunExpiresAtMs(params) {
442
+ const graceMs = Math.max(0, params.graceMs ?? DEFAULT_CHAT_RUN_ABORT_GRACE_MS);
443
+ return resolveChatRunExpiresAtMs({
444
+ now: params.now,
445
+ timeoutMs: params.timeoutMs,
446
+ graceMs,
447
+ minMs: graceMs,
448
+ maxMs: Math.max(0, params.timeoutMs) + graceMs
449
+ });
450
+ }
451
+ function registerChatAbortController(params) {
452
+ const controller = new AbortController();
453
+ const cleanup = () => {
454
+ if (params.chatAbortControllers.get(params.runId)?.controller === controller) params.chatAbortControllers.delete(params.runId);
455
+ };
456
+ if (!params.sessionKey || params.chatAbortControllers.has(params.runId)) return {
457
+ controller,
458
+ registered: false,
459
+ cleanup
460
+ };
461
+ const now = params.now ?? Date.now();
462
+ const entry = {
463
+ controller,
464
+ sessionId: params.sessionId,
465
+ sessionKey: params.sessionKey,
466
+ startedAtMs: now,
467
+ expiresAtMs: params.expiresAtMs ?? resolveChatRunExpiresAtMs({
468
+ now,
469
+ timeoutMs: params.timeoutMs
470
+ }),
471
+ ownerConnId: params.ownerConnId,
472
+ ownerDeviceId: params.ownerDeviceId,
473
+ kind: params.kind
474
+ };
475
+ params.chatAbortControllers.set(params.runId, entry);
476
+ return {
477
+ controller,
478
+ registered: true,
479
+ entry,
480
+ cleanup
481
+ };
482
+ }
483
+ function broadcastChatAborted(ops, params) {
484
+ const { runId, sessionKey, stopReason, partialText } = params;
485
+ const payload = {
486
+ runId,
487
+ sessionKey,
488
+ seq: (ops.agentRunSeq.get(runId) ?? 0) + 1,
489
+ state: "aborted",
490
+ stopReason,
491
+ message: partialText ? {
492
+ role: "assistant",
493
+ content: [{
494
+ type: "text",
495
+ text: partialText
496
+ }],
497
+ timestamp: Date.now()
498
+ } : void 0
499
+ };
500
+ ops.broadcast("chat", payload);
501
+ ops.nodeSendToSession(sessionKey, "chat", payload);
502
+ }
503
+ function abortChatRunById(ops, params) {
504
+ const { runId, sessionKey, stopReason } = params;
505
+ const active = ops.chatAbortControllers.get(runId);
506
+ if (!active) return { aborted: false };
507
+ if (active.sessionKey !== sessionKey) return { aborted: false };
508
+ const bufferedText = ops.chatRunBuffers.get(runId);
509
+ const partialText = bufferedText && bufferedText.trim() ? bufferedText : void 0;
510
+ ops.chatAbortedRuns.set(runId, Date.now());
511
+ active.controller.abort();
512
+ ops.chatAbortControllers.delete(runId);
513
+ ops.chatRunBuffers.delete(runId);
514
+ ops.chatDeltaSentAt.delete(runId);
515
+ ops.chatDeltaLastBroadcastLen.delete(runId);
516
+ const removed = ops.removeChatRun(runId, runId, sessionKey);
517
+ broadcastChatAborted(ops, {
518
+ runId,
519
+ sessionKey,
520
+ stopReason,
521
+ partialText
522
+ });
523
+ ops.agentRunSeq.delete(runId);
524
+ if (removed?.clientRunId) ops.agentRunSeq.delete(removed.clientRunId);
525
+ return { aborted: true };
526
+ }
527
+ //#endregion
528
+ //#region src/gateway/control-reply-text.ts
529
+ const SUPPRESSED_CONTROL_REPLY_TOKENS = [
530
+ SILENT_REPLY_TOKEN,
531
+ "ANNOUNCE_SKIP",
532
+ "REPLY_SKIP"
533
+ ];
534
+ const MIN_BARE_PREFIX_LENGTH_BY_TOKEN = {
535
+ [SILENT_REPLY_TOKEN]: 2,
536
+ ANNOUNCE_SKIP: 3,
537
+ REPLY_SKIP: 3
538
+ };
539
+ function normalizeSuppressedControlReplyFragment(text) {
540
+ const trimmed = text.trim();
541
+ if (!trimmed) return "";
542
+ const normalized = trimmed.toUpperCase();
543
+ if (/[^A-Z_]/.test(normalized)) return "";
544
+ return normalized;
545
+ }
546
+ /**
547
+ * Return true when a chat-visible reply is exactly an internal control token.
548
+ */
549
+ function isSuppressedControlReplyText(text) {
550
+ const normalized = text.trim();
551
+ return SUPPRESSED_CONTROL_REPLY_TOKENS.some((token) => isSilentReplyText(normalized, token));
552
+ }
553
+ /**
554
+ * Return true when streamed assistant text looks like the leading fragment of a control token.
555
+ */
556
+ function isSuppressedControlReplyLeadFragment(text) {
557
+ const trimmed = text.trim();
558
+ const normalized = normalizeSuppressedControlReplyFragment(text);
559
+ if (!normalized) return false;
560
+ return SUPPRESSED_CONTROL_REPLY_TOKENS.some((token) => {
561
+ const tokenUpper = token.toUpperCase();
562
+ if (normalized === tokenUpper) return false;
563
+ if (!tokenUpper.startsWith(normalized)) return false;
564
+ if (normalized.includes("_")) return true;
565
+ if (token !== "NO_REPLY" && trimmed !== trimmed.toUpperCase()) return false;
566
+ return normalized.length >= MIN_BARE_PREFIX_LENGTH_BY_TOKEN[token];
567
+ });
568
+ }
569
+ //#endregion
570
+ //#region src/gateway/server-methods/agent-wait-dedupe.ts
571
+ const AGENT_WAITERS_BY_RUN_ID = /* @__PURE__ */ new Map();
572
+ function parseRunIdFromDedupeKey(key) {
573
+ if (key.startsWith("agent:")) return key.slice(6) || null;
574
+ if (key.startsWith("chat:")) return key.slice(5) || null;
575
+ return null;
576
+ }
577
+ function asFiniteNumber(value) {
578
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
579
+ }
580
+ function removeWaiter(runId, waiter) {
581
+ const waiters = AGENT_WAITERS_BY_RUN_ID.get(runId);
582
+ if (!waiters) return;
583
+ waiters.delete(waiter);
584
+ if (waiters.size === 0) AGENT_WAITERS_BY_RUN_ID.delete(runId);
585
+ }
586
+ function addWaiter(runId, waiter) {
587
+ const normalizedRunId = runId.trim();
588
+ if (!normalizedRunId) return () => {};
589
+ const existing = AGENT_WAITERS_BY_RUN_ID.get(normalizedRunId);
590
+ if (existing) {
591
+ existing.add(waiter);
592
+ return () => removeWaiter(normalizedRunId, waiter);
593
+ }
594
+ AGENT_WAITERS_BY_RUN_ID.set(normalizedRunId, new Set([waiter]));
595
+ return () => removeWaiter(normalizedRunId, waiter);
596
+ }
597
+ function notifyWaiters(runId) {
598
+ const normalizedRunId = runId.trim();
599
+ if (!normalizedRunId) return;
600
+ const waiters = AGENT_WAITERS_BY_RUN_ID.get(normalizedRunId);
601
+ if (!waiters || waiters.size === 0) return;
602
+ for (const waiter of waiters) waiter();
603
+ }
604
+ function readTerminalSnapshotFromDedupeEntry(entry) {
605
+ const payload = entry.payload;
606
+ const status = typeof payload?.status === "string" ? payload.status : void 0;
607
+ if (status === "accepted" || status === "started" || status === "in_flight") return null;
608
+ const startedAt = asFiniteNumber(payload?.startedAt);
609
+ const endedAt = asFiniteNumber(payload?.endedAt) ?? entry.ts;
610
+ const errorMessage = typeof payload?.error === "string" ? payload.error : typeof payload?.summary === "string" ? payload.summary : entry.error?.message;
611
+ if (status === "ok" || status === "timeout") return {
612
+ status,
613
+ startedAt,
614
+ endedAt,
615
+ error: status === "timeout" ? errorMessage : void 0
616
+ };
617
+ if (status === "error" || !entry.ok) return {
618
+ status: "error",
619
+ startedAt,
620
+ endedAt,
621
+ error: errorMessage
622
+ };
623
+ return null;
624
+ }
625
+ function readTerminalSnapshotFromGatewayDedupe(params) {
626
+ if (params.ignoreAgentTerminalSnapshot) {
627
+ const chatEntry = params.dedupe.get(`chat:${params.runId}`);
628
+ if (!chatEntry) return null;
629
+ return readTerminalSnapshotFromDedupeEntry(chatEntry);
630
+ }
631
+ const chatEntry = params.dedupe.get(`chat:${params.runId}`);
632
+ const chatSnapshot = chatEntry ? readTerminalSnapshotFromDedupeEntry(chatEntry) : null;
633
+ const agentEntry = params.dedupe.get(`agent:${params.runId}`);
634
+ const agentSnapshot = agentEntry ? readTerminalSnapshotFromDedupeEntry(agentEntry) : null;
635
+ if (agentEntry) {
636
+ if (!agentSnapshot) {
637
+ if (chatSnapshot && chatEntry && chatEntry.ts > agentEntry.ts) return chatSnapshot;
638
+ return null;
639
+ }
640
+ }
641
+ if (agentSnapshot && chatSnapshot && agentEntry && chatEntry) return chatEntry.ts > agentEntry.ts ? chatSnapshot : agentSnapshot;
642
+ return agentSnapshot ?? chatSnapshot;
643
+ }
644
+ async function waitForTerminalGatewayDedupe(params) {
645
+ const initial = readTerminalSnapshotFromGatewayDedupe(params);
646
+ if (initial) return initial;
647
+ if (params.timeoutMs <= 0 || params.signal?.aborted) return null;
648
+ return await new Promise((resolve) => {
649
+ let settled = false;
650
+ let timeoutHandle;
651
+ let onAbort;
652
+ let removeWaiter;
653
+ const finish = (snapshot) => {
654
+ if (settled) return;
655
+ settled = true;
656
+ if (timeoutHandle) clearTimeout(timeoutHandle);
657
+ if (onAbort) params.signal?.removeEventListener("abort", onAbort);
658
+ removeWaiter?.();
659
+ resolve(snapshot);
660
+ };
661
+ const onWake = () => {
662
+ const snapshot = readTerminalSnapshotFromGatewayDedupe(params);
663
+ if (snapshot) finish(snapshot);
664
+ };
665
+ removeWaiter = addWaiter(params.runId, onWake);
666
+ onWake();
667
+ if (settled) return;
668
+ timeoutHandle = setSafeTimeout(() => finish(null), params.timeoutMs);
669
+ timeoutHandle.unref?.();
670
+ onAbort = () => finish(null);
671
+ params.signal?.addEventListener("abort", onAbort, { once: true });
672
+ });
673
+ }
674
+ function setGatewayDedupeEntry(params) {
675
+ params.dedupe.set(params.key, params.entry);
676
+ const runId = parseRunIdFromDedupeKey(params.key);
677
+ if (!runId) return;
678
+ if (!readTerminalSnapshotFromDedupeEntry(params.entry)) return;
679
+ notifyWaiters(runId);
680
+ }
681
+ //#endregion
682
+ //#region src/gateway/server-methods/chat-transcript-inject.ts
683
+ function resolveInjectedAssistantContent(params) {
684
+ const labelPrefix = params.label ? `[${params.label}]\n\n` : "";
685
+ if (params.content && params.content.length > 0) {
686
+ if (!labelPrefix) return params.content;
687
+ const first = params.content[0];
688
+ if (first && typeof first === "object" && first.type === "text" && typeof first.text === "string") return [{
689
+ ...first,
690
+ text: `${labelPrefix}${first.text}`
691
+ }, ...params.content.slice(1)];
692
+ return [{
693
+ type: "text",
694
+ text: labelPrefix.trim()
695
+ }, ...params.content];
696
+ }
697
+ return [{
698
+ type: "text",
699
+ text: `${labelPrefix}${params.message}`
700
+ }];
701
+ }
702
+ function appendInjectedAssistantMessageToTranscript(params) {
703
+ const now = params.now ?? Date.now();
704
+ const messageBody = {
705
+ role: "assistant",
706
+ content: resolveInjectedAssistantContent({
707
+ message: params.message,
708
+ label: params.label,
709
+ content: params.content
710
+ }),
711
+ timestamp: now,
712
+ stopReason: "stop",
713
+ usage: {
714
+ input: 0,
715
+ output: 0,
716
+ cacheRead: 0,
717
+ cacheWrite: 0,
718
+ totalTokens: 0,
719
+ cost: {
720
+ input: 0,
721
+ output: 0,
722
+ cacheRead: 0,
723
+ cacheWrite: 0,
724
+ total: 0
725
+ }
726
+ },
727
+ api: "openai-responses",
728
+ provider: "genesis",
729
+ model: "gateway-injected",
730
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
731
+ ...params.abortMeta ? { genesisAbort: {
732
+ aborted: true,
733
+ origin: params.abortMeta.origin,
734
+ runId: params.abortMeta.runId
735
+ } } : {}
736
+ };
737
+ try {
738
+ const messageId = SessionManager.open(params.transcriptPath).appendMessage(messageBody);
739
+ emitSessionTranscriptUpdate({
740
+ sessionFile: params.transcriptPath,
741
+ message: messageBody,
742
+ messageId
743
+ });
744
+ return {
745
+ ok: true,
746
+ messageId,
747
+ message: messageBody
748
+ };
749
+ } catch (err) {
750
+ return {
751
+ ok: false,
752
+ error: formatErrorMessage(err)
753
+ };
754
+ }
755
+ }
756
+ //#endregion
757
+ //#region src/gateway/server-methods/chat-webchat-media.ts
758
+ /** Cap embedded audio size to avoid multi‑MB payloads on the chat WebSocket. */
759
+ const MAX_WEBCHAT_AUDIO_BYTES = 15 * 1024 * 1024;
760
+ const MAX_WEBCHAT_IMAGE_DATA_URL_CHARS = 2e6;
761
+ const MAX_WEBCHAT_IMAGE_DATA_BYTES = 15e5;
762
+ const ALLOWED_WEBCHAT_DATA_IMAGE_MEDIA_TYPES = new Set([
763
+ "image/apng",
764
+ "image/avif",
765
+ "image/bmp",
766
+ "image/gif",
767
+ "image/jpeg",
768
+ "image/png",
769
+ "image/webp"
770
+ ]);
771
+ const MIME_BY_EXT = {
772
+ ".aac": "audio/aac",
773
+ ".m4a": "audio/mp4",
774
+ ".mp3": "audio/mpeg",
775
+ ".oga": "audio/ogg",
776
+ ".ogg": "audio/ogg",
777
+ ".opus": "audio/opus",
778
+ ".wav": "audio/wav",
779
+ ".weba": "audio/webm",
780
+ ".webm": "audio/webm",
781
+ ".aif": "audio/aiff",
782
+ ".aiff": "audio/aiff",
783
+ ".caf": "audio/x-caf"
784
+ };
785
+ /** Map `mediaUrl` strings to an absolute filesystem path for local embedding (plain paths or `file:` URLs). */
786
+ function resolveLocalMediaPathForEmbedding(raw) {
787
+ const trimmed = raw.trim();
788
+ if (!trimmed) return null;
789
+ if (/^data:/i.test(trimmed)) return null;
790
+ if (/^https?:/i.test(trimmed)) return null;
791
+ if (trimmed.startsWith("file:")) try {
792
+ const p = safeFileURLToPath(trimmed);
793
+ if (!path.isAbsolute(p)) return null;
794
+ return p;
795
+ } catch {
796
+ return null;
797
+ }
798
+ if (!path.isAbsolute(trimmed)) return null;
799
+ try {
800
+ assertNoWindowsNetworkPath(trimmed, "Local media path");
801
+ } catch {
802
+ return null;
803
+ }
804
+ return trimmed;
805
+ }
806
+ /** Returns a readable local file path when it is a regular file and within the size cap (single stat before read). */
807
+ async function resolveLocalAudioFileForEmbedding(payload, raw, options) {
808
+ if (payload.trustedLocalMedia !== true) return null;
809
+ const resolved = resolveLocalMediaPathForEmbedding(raw);
810
+ if (!resolved) return null;
811
+ if (!isAudioFileName(resolved)) return null;
812
+ try {
813
+ await assertLocalMediaAllowed(resolved, options?.localRoots);
814
+ const st = fs.statSync(resolved);
815
+ if (!st.isFile() || st.size > MAX_WEBCHAT_AUDIO_BYTES) return null;
816
+ return resolved;
817
+ } catch (err) {
818
+ if (err instanceof LocalMediaAccessError) options?.onLocalAudioAccessDenied?.(err);
819
+ return null;
820
+ }
821
+ }
822
+ function mimeTypeForPath(filePath) {
823
+ return MIME_BY_EXT[normalizeLowercaseStringOrEmpty(path.extname(filePath))] ?? "audio/mpeg";
824
+ }
825
+ function estimateBase64DecodedBytes(base64) {
826
+ const sanitized = base64.replace(/\s+/g, "");
827
+ const padding = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
828
+ return Math.floor(sanitized.length * 3 / 4) - padding;
829
+ }
830
+ function resolveEmbeddableImageUrl(url) {
831
+ const trimmed = url.trim();
832
+ if (!trimmed) return null;
833
+ if (trimmed.length > MAX_WEBCHAT_IMAGE_DATA_URL_CHARS) return null;
834
+ const match = /^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=\s]+)$/i.exec(trimmed);
835
+ if (!match) return null;
836
+ const mediaType = normalizeLowercaseStringOrEmpty(match[1]);
837
+ const base64Data = match[2];
838
+ if (!ALLOWED_WEBCHAT_DATA_IMAGE_MEDIA_TYPES.has(mediaType)) return null;
839
+ if (estimateBase64DecodedBytes(base64Data) > MAX_WEBCHAT_IMAGE_DATA_BYTES) return null;
840
+ return trimmed;
841
+ }
842
+ function inferDataUrlMimeType(source) {
843
+ return normalizeMimeType(/^data:([^;,]+)/i.exec(source.trim())?.[1]);
844
+ }
845
+ function inferAssistantAttachmentMimeType(source) {
846
+ if (/^data:/i.test(source)) return inferDataUrlMimeType(source);
847
+ return mimeTypeFromFilePath(source);
848
+ }
849
+ function inferAssistantAttachmentLabel(source, kind) {
850
+ const fallback = kind === "audio" ? "Audio attachment" : kind === "video" ? "Video attachment" : "Attachment";
851
+ const trimmed = source.trim();
852
+ if (/^data:/i.test(trimmed)) return fallback;
853
+ try {
854
+ if (/^https?:\/\//i.test(trimmed)) {
855
+ const parsed = new URL(trimmed);
856
+ return decodeURIComponent(parsed.pathname.split("/").pop() ?? "").trim() || parsed.hostname || fallback;
857
+ }
858
+ } catch {}
859
+ return path.basename(trimmed).trim() || fallback;
860
+ }
861
+ function buildGenericAssistantAttachmentBlock(payload, source) {
862
+ const mimeType = inferAssistantAttachmentMimeType(source);
863
+ const kind = mediaKindFromMime(mimeType);
864
+ if (!kind || kind === "image") return null;
865
+ return {
866
+ type: "attachment",
867
+ attachment: {
868
+ url: source,
869
+ kind,
870
+ label: inferAssistantAttachmentLabel(source, kind),
871
+ ...mimeType ? { mimeType } : {},
872
+ ...kind === "audio" && payload.audioAsVoice === true ? { isVoiceNote: true } : {}
873
+ }
874
+ };
875
+ }
876
+ function resolveReplyDirectivePrefix(payload) {
877
+ const replyToId = sanitizeReplyDirectiveId(payload.replyToId);
878
+ if (replyToId) return `[[reply_to:${replyToId}]]`;
879
+ if (payload.replyToCurrent) return "[[reply_to_current]]";
880
+ return "";
881
+ }
882
+ /**
883
+ * Build Control UI / transcript `content` blocks for local TTS (or other) audio files
884
+ * referenced by slash-command / agent replies when the webchat path only had text aggregation.
885
+ */
886
+ async function buildWebchatAudioContentBlocksFromReplyPayloads(payloads, options) {
887
+ const seen = /* @__PURE__ */ new Set();
888
+ const blocks = [];
889
+ for (const payload of payloads) {
890
+ const parts = resolveSendableOutboundReplyParts(payload);
891
+ for (const raw of parts.mediaUrls) {
892
+ const url = raw.trim();
893
+ if (!url) continue;
894
+ const resolved = await resolveLocalAudioFileForEmbedding(payload, url, options);
895
+ if (!resolved || seen.has(resolved)) continue;
896
+ seen.add(resolved);
897
+ const block = tryReadLocalAudioContentBlock(resolved);
898
+ if (block) blocks.push(block);
899
+ }
900
+ }
901
+ return blocks;
902
+ }
903
+ async function buildWebchatAssistantMessageFromReplyPayloads(payloads, options) {
904
+ const content = [];
905
+ const transcriptTextParts = [];
906
+ const seenAudio = /* @__PURE__ */ new Set();
907
+ const seenImages = /* @__PURE__ */ new Set();
908
+ const seenGenericMedia = /* @__PURE__ */ new Set();
909
+ let hasAudio = false;
910
+ let hasImage = false;
911
+ let hasVideo = false;
912
+ let hasDocument = false;
913
+ for (const payload of payloads) {
914
+ const visibleText = payload.text?.trim();
915
+ const text = visibleText && !isSuppressedControlReplyText(visibleText) ? visibleText : void 0;
916
+ const replyDirectivePrefix = resolveReplyDirectivePrefix(payload);
917
+ let payloadHasAudio = false;
918
+ let payloadHasImage = false;
919
+ let payloadHasVideo = false;
920
+ let payloadHasDocument = false;
921
+ const payloadMediaBlocks = [];
922
+ const parts = resolveSendableOutboundReplyParts(payload);
923
+ for (const raw of parts.mediaUrls) {
924
+ const url = raw.trim();
925
+ if (!url) continue;
926
+ const resolvedAudioPath = await resolveLocalAudioFileForEmbedding(payload, url, options);
927
+ if (resolvedAudioPath) {
928
+ if (seenAudio.has(resolvedAudioPath)) continue;
929
+ seenAudio.add(resolvedAudioPath);
930
+ const block = tryReadLocalAudioContentBlock(resolvedAudioPath);
931
+ if (block) {
932
+ payloadMediaBlocks.push(block);
933
+ hasAudio = true;
934
+ payloadHasAudio = true;
935
+ }
936
+ continue;
937
+ }
938
+ const imageUrl = resolveEmbeddableImageUrl(url);
939
+ if (imageUrl) {
940
+ if (seenImages.has(imageUrl)) continue;
941
+ seenImages.add(imageUrl);
942
+ payloadMediaBlocks.push({
943
+ type: "input_image",
944
+ image_url: imageUrl
945
+ });
946
+ hasImage = true;
947
+ payloadHasImage = true;
948
+ continue;
949
+ }
950
+ if (seenGenericMedia.has(url)) continue;
951
+ const attachmentBlock = buildGenericAssistantAttachmentBlock(payload, url);
952
+ if (!attachmentBlock) continue;
953
+ seenGenericMedia.add(url);
954
+ payloadMediaBlocks.push(attachmentBlock);
955
+ const attachment = attachmentBlock.attachment;
956
+ if (attachment.kind === "audio") {
957
+ hasAudio = true;
958
+ payloadHasAudio = true;
959
+ } else if (attachment.kind === "video") {
960
+ hasVideo = true;
961
+ payloadHasVideo = true;
962
+ } else if (attachment.kind === "document") {
963
+ hasDocument = true;
964
+ payloadHasDocument = true;
965
+ }
966
+ }
967
+ const syntheticText = payloadMediaBlocks.length > 0 && (!text || replyDirectivePrefix) && transcriptTextParts.length === 0 ? [
968
+ payloadHasAudio,
969
+ payloadHasImage,
970
+ payloadHasVideo,
971
+ payloadHasDocument
972
+ ].filter(Boolean).length > 1 ? "Media reply" : payloadHasAudio ? "Audio reply" : payloadHasImage ? "Image reply" : payloadHasVideo ? "Video reply" : "File reply" : void 0;
973
+ const blockText = text ?? syntheticText;
974
+ if (blockText) {
975
+ const fullText = replyDirectivePrefix ? `${replyDirectivePrefix}${blockText}` : blockText;
976
+ transcriptTextParts.push(fullText);
977
+ content.push({
978
+ type: "text",
979
+ text: fullText
980
+ });
981
+ } else if (replyDirectivePrefix) {
982
+ transcriptTextParts.push(replyDirectivePrefix);
983
+ content.push({
984
+ type: "text",
985
+ text: replyDirectivePrefix
986
+ });
987
+ }
988
+ content.push(...payloadMediaBlocks);
989
+ }
990
+ if (!hasAudio && !hasImage && !hasVideo && !hasDocument) return null;
991
+ const transcriptText = transcriptTextParts.join("\n\n").trim() || ([
992
+ hasAudio,
993
+ hasImage,
994
+ hasVideo,
995
+ hasDocument
996
+ ].filter(Boolean).length > 1 ? "Media reply" : hasAudio ? "Audio reply" : hasImage ? "Image reply" : hasVideo ? "Video reply" : "File reply");
997
+ if (transcriptTextParts.length === 0) content.unshift({
998
+ type: "text",
999
+ text: transcriptText
1000
+ });
1001
+ return {
1002
+ content,
1003
+ transcriptText
1004
+ };
1005
+ }
1006
+ function tryReadLocalAudioContentBlock(filePath) {
1007
+ try {
1008
+ const buf = fs.readFileSync(filePath);
1009
+ if (buf.length > MAX_WEBCHAT_AUDIO_BYTES) return null;
1010
+ return {
1011
+ type: "audio",
1012
+ source: {
1013
+ type: "base64",
1014
+ media_type: mimeTypeForPath(filePath),
1015
+ data: buf.toString("base64")
1016
+ }
1017
+ };
1018
+ } catch {
1019
+ return null;
1020
+ }
1021
+ }
1022
+ //#endregion
1023
+ //#region src/gateway/server-methods/chat.ts
1024
+ /** True when a reply payload carries at least one media reference (mediaUrl or mediaUrls). */
1025
+ function isMediaBearingPayload(payload) {
1026
+ if (payload.mediaUrl?.trim()) return true;
1027
+ if (payload.mediaUrls?.some((url) => url.trim())) return true;
1028
+ return false;
1029
+ }
1030
+ async function buildWebchatAssistantMediaMessage(payloads, options) {
1031
+ return buildWebchatAssistantMessageFromReplyPayloads(payloads, {
1032
+ localRoots: options?.localRoots,
1033
+ onLocalAudioAccessDenied: (err) => {
1034
+ options?.onLocalAudioAccessDenied?.(formatForLog(err));
1035
+ }
1036
+ });
1037
+ }
1038
+ const DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS = 8e3;
1039
+ const CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES = 128 * 1024;
1040
+ const CHAT_HISTORY_OVERSIZED_PLACEHOLDER = "[chat.history omitted: message too large]";
1041
+ const MANAGED_OUTGOING_IMAGE_PATH_PREFIX = "/api/chat/media/outgoing/";
1042
+ let chatHistoryPlaceholderEmitCount = 0;
1043
+ const chatHistoryManagedImageCleanupState = /* @__PURE__ */ new Map();
1044
+ const CHANNEL_AGNOSTIC_SESSION_SCOPES = new Set([
1045
+ "main",
1046
+ "direct",
1047
+ "dm",
1048
+ "group",
1049
+ "channel",
1050
+ "cron",
1051
+ "run",
1052
+ "subagent",
1053
+ "acp",
1054
+ "thread",
1055
+ "topic"
1056
+ ]);
1057
+ const CHANNEL_SCOPED_SESSION_SHAPES = new Set([
1058
+ "direct",
1059
+ "dm",
1060
+ "group",
1061
+ "channel"
1062
+ ]);
1063
+ function resolveEffectiveChatHistoryMaxChars(cfg, maxChars) {
1064
+ if (typeof maxChars === "number") return maxChars;
1065
+ if (typeof cfg.gateway?.webchat?.chatHistoryMaxChars === "number") return cfg.gateway.webchat.chatHistoryMaxChars;
1066
+ return DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS;
1067
+ }
1068
+ function buildTranscriptReplyText(payloads) {
1069
+ return payloads.map((payload) => {
1070
+ const parts = resolveSendableOutboundReplyParts(payload);
1071
+ const lines = [];
1072
+ const replyToId = sanitizeReplyDirectiveId(payload.replyToId);
1073
+ if (replyToId) lines.push(`[[reply_to:${replyToId}]]`);
1074
+ else if (payload.replyToCurrent) lines.push("[[reply_to_current]]");
1075
+ const text = payload.text?.trim();
1076
+ if (text && !isSuppressedControlReplyText(text)) lines.push(text);
1077
+ for (const mediaUrl of parts.mediaUrls) {
1078
+ if (payload.sensitiveMedia === true) continue;
1079
+ const trimmed = mediaUrl.trim();
1080
+ if (trimmed) lines.push(`MEDIA:${trimmed}`);
1081
+ }
1082
+ if (payload.audioAsVoice && parts.mediaUrls.some((mediaUrl) => isAudioFileName(mediaUrl))) lines.push("[[audio_as_voice]]");
1083
+ return lines.join("\n").trim();
1084
+ }).filter(Boolean).join("\n\n").trim();
1085
+ }
1086
+ function hasSensitiveMediaPayload(payloads) {
1087
+ return payloads.some((payload) => payload.sensitiveMedia === true && isMediaBearingPayload(payload));
1088
+ }
1089
+ function sanitizeAssistantDisplayText(value) {
1090
+ if (!value) return;
1091
+ const withoutEnvelope = stripEnvelopeFromMessage(value);
1092
+ return stripInlineDirectiveTagsForDisplay(typeof withoutEnvelope === "string" ? withoutEnvelope : value).text.trim() || void 0;
1093
+ }
1094
+ function extractAssistantDisplayTextFromContent(content) {
1095
+ if (!Array.isArray(content) || content.length === 0) return;
1096
+ const parts = content.map((block) => {
1097
+ if (block?.type !== "text" || typeof block.text !== "string") return "";
1098
+ return block.text.trim();
1099
+ }).filter(Boolean);
1100
+ return parts.length > 0 ? parts.join("\n\n") : void 0;
1101
+ }
1102
+ async function buildAssistantDisplayContentFromReplyPayloads(params) {
1103
+ const rawTextPayloadCount = params.payloads.filter((payload) => typeof payload.text === "string" && payload.text.trim().length > 0).length;
1104
+ const normalized = normalizeReplyPayloadsForDelivery(params.payloads);
1105
+ if (normalized.length === 0) return rawTextPayloadCount > 0 ? [{
1106
+ type: "text",
1107
+ text: ""
1108
+ }] : void 0;
1109
+ const content = [];
1110
+ let strippedTextPayloadCount = 0;
1111
+ for (const payload of normalized) {
1112
+ const text = sanitizeAssistantDisplayText(payload.text);
1113
+ if (text) content.push({
1114
+ type: "text",
1115
+ text
1116
+ });
1117
+ else if (typeof payload.text === "string" && payload.text.trim().length > 0) strippedTextPayloadCount += 1;
1118
+ if (params.includeSensitiveMedia === false && payload.sensitiveMedia === true) continue;
1119
+ const audioBlocks = await buildWebchatAudioContentBlocksFromReplyPayloads([payload], {
1120
+ localRoots: Array.isArray(params.managedImageLocalRoots) ? params.managedImageLocalRoots : void 0,
1121
+ onLocalAudioAccessDenied: (err) => {
1122
+ params.onLocalAudioAccessDenied?.(formatForLog(err));
1123
+ }
1124
+ });
1125
+ content.push(...audioBlocks);
1126
+ const mediaUrls = Array.from(new Set([...Array.isArray(payload.mediaUrls) ? payload.mediaUrls : [], ...typeof payload.mediaUrl === "string" ? [payload.mediaUrl] : []]));
1127
+ const imageBlocks = await createManagedOutgoingImageBlocks({
1128
+ sessionKey: params.sessionKey,
1129
+ mediaUrls,
1130
+ localRoots: params.managedImageLocalRoots,
1131
+ continueOnPrepareError: true,
1132
+ onPrepareError: (error) => {
1133
+ params.onManagedImagePrepareError?.(error.message);
1134
+ }
1135
+ });
1136
+ if (imageBlocks.length > 0) content.push(...imageBlocks);
1137
+ }
1138
+ if (content.length > 0) return content;
1139
+ return strippedTextPayloadCount > 0 ? [{
1140
+ type: "text",
1141
+ text: ""
1142
+ }] : void 0;
1143
+ }
1144
+ function replaceAssistantContentTextBlocks(content, transcriptMediaMessage) {
1145
+ const transcriptTextBlocks = (transcriptMediaMessage?.content ?? []).filter((block) => Boolean(block) && typeof block === "object" && block.type === "text" && typeof block.text === "string");
1146
+ if (transcriptTextBlocks.length === 0) return content ? [...content] : void 0;
1147
+ if (!content || content.length === 0) return [...transcriptTextBlocks];
1148
+ const merged = [];
1149
+ let transcriptTextIndex = 0;
1150
+ for (const block of content) {
1151
+ if (block?.type === "text" && typeof block.text === "string" && transcriptTextIndex < transcriptTextBlocks.length) {
1152
+ merged.push(transcriptTextBlocks[transcriptTextIndex++]);
1153
+ continue;
1154
+ }
1155
+ merged.push(block);
1156
+ }
1157
+ if (transcriptTextIndex < transcriptTextBlocks.length) merged.unshift(...transcriptTextBlocks.slice(transcriptTextIndex));
1158
+ return merged;
1159
+ }
1160
+ function isManagedOutgoingImageUrl(value) {
1161
+ if (typeof value !== "string" || !value.trim()) return false;
1162
+ try {
1163
+ return new URL(value, "http://localhost").pathname.startsWith(MANAGED_OUTGOING_IMAGE_PATH_PREFIX);
1164
+ } catch {
1165
+ return false;
1166
+ }
1167
+ }
1168
+ function stripManagedOutgoingAssistantContentBlocks(content) {
1169
+ if (!content || content.length === 0) return;
1170
+ const filtered = content.filter((block) => {
1171
+ if (block?.type !== "image") return true;
1172
+ return !(isManagedOutgoingImageUrl(block.url) || isManagedOutgoingImageUrl(block.openUrl));
1173
+ });
1174
+ return filtered.length > 0 ? filtered : void 0;
1175
+ }
1176
+ function extractAssistantDisplayText(content) {
1177
+ if (!content || content.length === 0) return;
1178
+ return content.map((block) => block?.type === "text" && typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n\n").trim() || void 0;
1179
+ }
1180
+ function hasAssistantDisplayMediaContent(content) {
1181
+ return Boolean(content?.some((block) => block?.type !== "text"));
1182
+ }
1183
+ function scheduleChatHistoryManagedImageCleanup(params) {
1184
+ if (chatHistoryManagedImageCleanupState.has(params.sessionKey)) return;
1185
+ const pending = cleanupManagedOutgoingImageRecords({ sessionKey: params.sessionKey }).then(() => void 0).catch((error) => {
1186
+ params.context.logGateway.debug(`chat.history managed image cleanup skipped sessionKey=${JSON.stringify(params.sessionKey)} error=${formatForLog(error)}`);
1187
+ }).finally(() => {
1188
+ if (chatHistoryManagedImageCleanupState.get(params.sessionKey) === pending) chatHistoryManagedImageCleanupState.delete(params.sessionKey);
1189
+ });
1190
+ chatHistoryManagedImageCleanupState.set(params.sessionKey, pending);
1191
+ }
1192
+ function resolveChatSendOriginatingRoute(params) {
1193
+ if (params.explicitOrigin?.originatingChannel && params.explicitOrigin.originatingTo) return {
1194
+ originatingChannel: params.explicitOrigin.originatingChannel,
1195
+ originatingTo: params.explicitOrigin.originatingTo,
1196
+ ...params.explicitOrigin.accountId ? { accountId: params.explicitOrigin.accountId } : {},
1197
+ ...params.explicitOrigin.messageThreadId ? { messageThreadId: params.explicitOrigin.messageThreadId } : {},
1198
+ explicitDeliverRoute: params.deliver === true
1199
+ };
1200
+ if (!(params.deliver === true)) return {
1201
+ originatingChannel: INTERNAL_MESSAGE_CHANNEL,
1202
+ explicitDeliverRoute: false
1203
+ };
1204
+ const routeChannelCandidate = normalizeMessageChannel(params.entry?.deliveryContext?.channel ?? params.entry?.lastChannel ?? params.entry?.origin?.provider);
1205
+ const routeToCandidate = params.entry?.deliveryContext?.to ?? params.entry?.lastTo;
1206
+ const routeAccountIdCandidate = params.entry?.deliveryContext?.accountId ?? params.entry?.lastAccountId ?? params.entry?.origin?.accountId ?? void 0;
1207
+ const routeThreadIdCandidate = params.entry?.deliveryContext?.threadId ?? params.entry?.lastThreadId ?? params.entry?.origin?.threadId;
1208
+ if (params.sessionKey.length > 512) return {
1209
+ originatingChannel: INTERNAL_MESSAGE_CHANNEL,
1210
+ explicitDeliverRoute: false
1211
+ };
1212
+ const sessionScopeParts = (parseAgentSessionKey(params.sessionKey)?.rest ?? params.sessionKey).split(":", 3).filter(Boolean);
1213
+ const sessionScopeHead = sessionScopeParts[0];
1214
+ const sessionChannelHint = normalizeMessageChannel(sessionScopeHead);
1215
+ const normalizedSessionScopeHead = (sessionScopeHead ?? "").trim().toLowerCase();
1216
+ const sessionPeerShapeCandidates = [sessionScopeParts[1], sessionScopeParts[2]].map((part) => (part ?? "").trim().toLowerCase()).filter(Boolean);
1217
+ const isChannelAgnosticSessionScope = CHANNEL_AGNOSTIC_SESSION_SCOPES.has(normalizedSessionScopeHead);
1218
+ const isChannelScopedSession = sessionPeerShapeCandidates.some((part) => CHANNEL_SCOPED_SESSION_SHAPES.has(part));
1219
+ const hasLegacyChannelPeerShape = !isChannelScopedSession && typeof sessionScopeParts[1] === "string" && sessionChannelHint === routeChannelCandidate;
1220
+ const isFromWebchatClient = isWebchatClient(params.client);
1221
+ const isFromGatewayCliClient = isGatewayCliClient(params.client);
1222
+ const hasClientMetadata = typeof params.client?.mode === "string" && params.client.mode.trim().length > 0 || typeof params.client?.id === "string" && params.client.id.trim().length > 0;
1223
+ const configuredMainKey = (params.mainKey ?? "main").trim().toLowerCase();
1224
+ const canInheritConfiguredMainRoute = normalizedSessionScopeHead.length > 0 && normalizedSessionScopeHead === configuredMainKey && params.hasConnectedClient && (isFromGatewayCliClient || !hasClientMetadata);
1225
+ if (!(Boolean(!isFromWebchatClient && sessionChannelHint && sessionChannelHint !== "webchat" && (!isChannelAgnosticSessionScope && (isChannelScopedSession || hasLegacyChannelPeerShape) || canInheritConfiguredMainRoute)) && routeChannelCandidate && routeChannelCandidate !== "webchat" && typeof routeToCandidate === "string" && routeToCandidate.trim().length > 0)) return {
1226
+ originatingChannel: INTERNAL_MESSAGE_CHANNEL,
1227
+ explicitDeliverRoute: false
1228
+ };
1229
+ return {
1230
+ originatingChannel: routeChannelCandidate,
1231
+ originatingTo: routeToCandidate,
1232
+ accountId: routeAccountIdCandidate,
1233
+ messageThreadId: routeThreadIdCandidate,
1234
+ explicitDeliverRoute: true
1235
+ };
1236
+ }
1237
+ function isAcpSessionKey(sessionKey) {
1238
+ return Boolean(sessionKey?.split(":").includes("acp"));
1239
+ }
1240
+ function explicitOriginTargetsAcpSession(origin) {
1241
+ if (!origin?.originatingChannel || !origin.originatingTo || !origin.accountId) return false;
1242
+ const channel = normalizeMessageChannel(origin.originatingChannel);
1243
+ if (!channel || channel === "webchat") return false;
1244
+ return isAcpSessionKey(getSessionBindingService().resolveByConversation({
1245
+ channel,
1246
+ accountId: origin.accountId,
1247
+ conversationId: origin.originatingTo
1248
+ })?.targetSessionKey);
1249
+ }
1250
+ function explicitOriginTargetsPluginBinding(origin) {
1251
+ if (!origin?.originatingChannel || !origin.originatingTo || !origin.accountId) return false;
1252
+ const channel = normalizeMessageChannel(origin.originatingChannel);
1253
+ if (!channel || channel === "webchat") return false;
1254
+ return isPluginOwnedSessionBindingRecord(getSessionBindingService().resolveByConversation({
1255
+ channel,
1256
+ accountId: origin.accountId,
1257
+ conversationId: origin.originatingTo
1258
+ }));
1259
+ }
1260
+ function stripDisallowedChatControlChars(message) {
1261
+ let output = "";
1262
+ for (const char of message) {
1263
+ const code = char.charCodeAt(0);
1264
+ if (code === 9 || code === 10 || code === 13 || code >= 32 && code !== 127) output += char;
1265
+ }
1266
+ return output;
1267
+ }
1268
+ function sanitizeChatSendMessageInput(message) {
1269
+ const normalized = message.normalize("NFC");
1270
+ if (normalized.includes("\0")) return {
1271
+ ok: false,
1272
+ error: "message must not contain null bytes"
1273
+ };
1274
+ return {
1275
+ ok: true,
1276
+ message: stripDisallowedChatControlChars(normalized)
1277
+ };
1278
+ }
1279
+ function normalizeOptionalChatSystemReceipt(value) {
1280
+ if (value == null) return { ok: true };
1281
+ if (typeof value !== "string") return {
1282
+ ok: false,
1283
+ error: "systemProvenanceReceipt must be a string"
1284
+ };
1285
+ const sanitized = sanitizeChatSendMessageInput(value);
1286
+ if (!sanitized.ok) return sanitized;
1287
+ return {
1288
+ ok: true,
1289
+ receipt: sanitized.message.trim() || void 0
1290
+ };
1291
+ }
1292
+ function isAcpBridgeClient(client) {
1293
+ const info = client?.connect?.client;
1294
+ return info?.id === GATEWAY_CLIENT_NAMES.CLI && info?.mode === GATEWAY_CLIENT_MODES.CLI && info?.displayName === "ACP" && info?.version === "acp";
1295
+ }
1296
+ function canInjectSystemProvenance(client) {
1297
+ return (Array.isArray(client?.connect?.scopes) ? client.connect.scopes : []).includes(ADMIN_SCOPE);
1298
+ }
1299
+ async function persistChatSendImages(params) {
1300
+ if (params.images.length === 0 && params.offloadedRefs.length === 0 || isAcpBridgeClient(params.client)) return [];
1301
+ const inlineSaved = [];
1302
+ for (const img of params.images) try {
1303
+ inlineSaved.push(await saveMediaBuffer(Buffer.from(img.data, "base64"), img.mimeType, "inbound"));
1304
+ } catch (err) {
1305
+ params.logGateway.warn(`chat.send: failed to persist inbound image (${img.mimeType}): ${formatForLog(err)}`);
1306
+ }
1307
+ const offloadedSaved = params.offloadedRefs.map((ref) => ({
1308
+ id: ref.id,
1309
+ path: ref.path,
1310
+ size: 0,
1311
+ contentType: ref.mimeType
1312
+ }));
1313
+ if (params.imageOrder.length === 0) return [...inlineSaved, ...offloadedSaved];
1314
+ const saved = [];
1315
+ let inlineIndex = 0;
1316
+ let offloadedIndex = 0;
1317
+ for (const entry of params.imageOrder) {
1318
+ if (entry === "inline") {
1319
+ const inline = inlineSaved[inlineIndex++];
1320
+ if (inline) saved.push(inline);
1321
+ continue;
1322
+ }
1323
+ const offloaded = offloadedSaved[offloadedIndex++];
1324
+ if (offloaded) saved.push(offloaded);
1325
+ }
1326
+ for (; inlineIndex < inlineSaved.length; inlineIndex++) {
1327
+ const inline = inlineSaved[inlineIndex];
1328
+ if (inline) saved.push(inline);
1329
+ }
1330
+ for (; offloadedIndex < offloadedSaved.length; offloadedIndex++) {
1331
+ const offloaded = offloadedSaved[offloadedIndex];
1332
+ if (offloaded) saved.push(offloaded);
1333
+ }
1334
+ return saved;
1335
+ }
1336
+ function buildChatSendTranscriptMessage(params) {
1337
+ const mediaFields = resolveChatSendTranscriptMediaFields(params.savedImages);
1338
+ return {
1339
+ role: "user",
1340
+ content: params.message,
1341
+ timestamp: params.timestamp,
1342
+ ...mediaFields
1343
+ };
1344
+ }
1345
+ function resolveChatSendTranscriptMediaFields(savedImages) {
1346
+ const mediaPaths = savedImages.map((entry) => entry.path);
1347
+ if (mediaPaths.length === 0) return {};
1348
+ const mediaTypes = savedImages.map((entry) => entry.contentType ?? "application/octet-stream");
1349
+ return {
1350
+ MediaPath: mediaPaths[0],
1351
+ MediaPaths: mediaPaths,
1352
+ MediaType: mediaTypes[0],
1353
+ MediaTypes: mediaTypes
1354
+ };
1355
+ }
1356
+ function extractTranscriptUserText(content) {
1357
+ if (typeof content === "string") return content;
1358
+ if (!Array.isArray(content)) return;
1359
+ const textBlocks = content.map((block) => block && typeof block === "object" && "text" in block ? block.text : void 0).filter((text) => typeof text === "string");
1360
+ return textBlocks.length > 0 ? textBlocks.join("") : void 0;
1361
+ }
1362
+ async function rewriteChatSendUserTurnMediaPaths(params) {
1363
+ const mediaFields = resolveChatSendTranscriptMediaFields(params.savedImages);
1364
+ if (!("MediaPath" in mediaFields)) return;
1365
+ const target = [...SessionManager.open(params.transcriptPath).getBranch()].toReversed().find((entry) => {
1366
+ if (entry.type !== "message" || entry.message.role !== "user") return false;
1367
+ const existingPaths = Array.isArray(entry.message.MediaPaths) ? entry.message.MediaPaths : void 0;
1368
+ if (typeof entry.message.MediaPath === "string" && entry.message.MediaPath || existingPaths && existingPaths.length > 0) return false;
1369
+ return extractTranscriptUserText(entry.message.content) === params.message;
1370
+ });
1371
+ if (!target || target.type !== "message") return;
1372
+ const rewrittenMessage = {
1373
+ ...target.message,
1374
+ ...mediaFields
1375
+ };
1376
+ await rewriteTranscriptEntriesInSessionFile({
1377
+ sessionFile: params.transcriptPath,
1378
+ sessionKey: params.sessionKey,
1379
+ request: { replacements: [{
1380
+ entryId: target.id,
1381
+ message: rewrittenMessage
1382
+ }] }
1383
+ });
1384
+ }
1385
+ function truncateChatHistoryText(text, maxChars = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS) {
1386
+ if (text.length <= maxChars) return {
1387
+ text,
1388
+ truncated: false
1389
+ };
1390
+ return {
1391
+ text: `${text.slice(0, maxChars)}\n...(truncated)...`,
1392
+ truncated: true
1393
+ };
1394
+ }
1395
+ function isToolHistoryBlockType(type) {
1396
+ if (typeof type !== "string") return false;
1397
+ const normalized = type.trim().toLowerCase();
1398
+ return normalized === "toolcall" || normalized === "tool_call" || normalized === "tooluse" || normalized === "tool_use" || normalized === "toolresult" || normalized === "tool_result";
1399
+ }
1400
+ function extractChatHistoryBlockText(message) {
1401
+ if (!message || typeof message !== "object") return;
1402
+ const entry = message;
1403
+ if (typeof entry.content === "string") return entry.content;
1404
+ if (typeof entry.text === "string") return entry.text;
1405
+ if (!Array.isArray(entry.content)) return;
1406
+ const textParts = entry.content.map((block) => {
1407
+ if (!block || typeof block !== "object") return;
1408
+ const typed = block;
1409
+ return typeof typed.text === "string" ? typed.text : void 0;
1410
+ }).filter((value) => typeof value === "string");
1411
+ return textParts.length > 0 ? textParts.join("\n") : void 0;
1412
+ }
1413
+ function sanitizeChatHistoryContentBlock(block, opts) {
1414
+ if (!block || typeof block !== "object") return {
1415
+ block,
1416
+ changed: false
1417
+ };
1418
+ const entry = { ...block };
1419
+ let changed = false;
1420
+ const preserveExactToolPayload = opts?.preserveExactToolPayload === true || isToolHistoryBlockType(entry.type);
1421
+ const maxChars = opts?.maxChars ?? 8e3;
1422
+ if (typeof entry.text === "string") {
1423
+ const stripped = stripInlineDirectiveTagsForDisplay(entry.text);
1424
+ if (preserveExactToolPayload) {
1425
+ entry.text = stripped.text;
1426
+ changed ||= stripped.changed;
1427
+ } else {
1428
+ const res = truncateChatHistoryText(stripped.text, maxChars);
1429
+ entry.text = res.text;
1430
+ changed ||= stripped.changed || res.truncated;
1431
+ }
1432
+ }
1433
+ if (typeof entry.content === "string") {
1434
+ const stripped = stripInlineDirectiveTagsForDisplay(entry.content);
1435
+ if (preserveExactToolPayload) {
1436
+ entry.content = stripped.text;
1437
+ changed ||= stripped.changed;
1438
+ } else {
1439
+ const res = truncateChatHistoryText(stripped.text, maxChars);
1440
+ entry.content = res.text;
1441
+ changed ||= stripped.changed || res.truncated;
1442
+ }
1443
+ }
1444
+ if (typeof entry.partialJson === "string") {
1445
+ if (!preserveExactToolPayload) {
1446
+ const res = truncateChatHistoryText(entry.partialJson, maxChars);
1447
+ entry.partialJson = res.text;
1448
+ changed ||= res.truncated;
1449
+ }
1450
+ }
1451
+ if (typeof entry.arguments === "string") {
1452
+ if (!preserveExactToolPayload) {
1453
+ const res = truncateChatHistoryText(entry.arguments, maxChars);
1454
+ entry.arguments = res.text;
1455
+ changed ||= res.truncated;
1456
+ }
1457
+ }
1458
+ if (typeof entry.thinking === "string") {
1459
+ const res = truncateChatHistoryText(entry.thinking, maxChars);
1460
+ entry.thinking = res.text;
1461
+ changed ||= res.truncated;
1462
+ }
1463
+ if ("thinkingSignature" in entry) {
1464
+ delete entry.thinkingSignature;
1465
+ changed = true;
1466
+ }
1467
+ const type = typeof entry.type === "string" ? entry.type : "";
1468
+ if (type === "image" && typeof entry.data === "string") {
1469
+ const bytes = Buffer.byteLength(entry.data, "utf8");
1470
+ delete entry.data;
1471
+ entry.omitted = true;
1472
+ entry.bytes = bytes;
1473
+ changed = true;
1474
+ }
1475
+ if (type === "audio" && entry.source && typeof entry.source === "object") {
1476
+ const source = { ...entry.source };
1477
+ if (source.type === "base64" && typeof source.data === "string") {
1478
+ const bytes = Buffer.byteLength(source.data, "utf8");
1479
+ delete source.data;
1480
+ source.omitted = true;
1481
+ source.bytes = bytes;
1482
+ entry.source = source;
1483
+ changed = true;
1484
+ }
1485
+ }
1486
+ return {
1487
+ block: changed ? entry : block,
1488
+ changed
1489
+ };
1490
+ }
1491
+ function sanitizeAssistantPhasedContentBlocks(content) {
1492
+ if (!content.some((block) => {
1493
+ if (!block || typeof block !== "object") return false;
1494
+ const entry = block;
1495
+ return entry.type === "text" && Boolean(parseAssistantTextSignature(entry.textSignature)?.phase);
1496
+ })) return {
1497
+ content,
1498
+ changed: false
1499
+ };
1500
+ const filtered = content.filter((block) => {
1501
+ if (!block || typeof block !== "object") return true;
1502
+ const entry = block;
1503
+ if (entry.type !== "text") return true;
1504
+ return parseAssistantTextSignature(entry.textSignature)?.phase === "final_answer";
1505
+ });
1506
+ return {
1507
+ content: filtered,
1508
+ changed: filtered.length !== content.length
1509
+ };
1510
+ }
1511
+ /**
1512
+ * Validate that a value is a finite number, returning undefined otherwise.
1513
+ */
1514
+ function toFiniteNumber(x) {
1515
+ return typeof x === "number" && Number.isFinite(x) ? x : void 0;
1516
+ }
1517
+ /**
1518
+ * Sanitize usage metadata to ensure only finite numeric fields are included.
1519
+ * Prevents UI crashes from malformed transcript JSON.
1520
+ */
1521
+ function sanitizeUsage(raw) {
1522
+ if (!raw || typeof raw !== "object") return;
1523
+ const u = raw;
1524
+ const out = {};
1525
+ for (const k of [
1526
+ "input",
1527
+ "output",
1528
+ "totalTokens",
1529
+ "inputTokens",
1530
+ "outputTokens",
1531
+ "cacheRead",
1532
+ "cacheWrite",
1533
+ "cache_read_input_tokens",
1534
+ "cache_creation_input_tokens"
1535
+ ]) {
1536
+ const n = toFiniteNumber(u[k]);
1537
+ if (n !== void 0) out[k] = n;
1538
+ }
1539
+ if ("cost" in u && u.cost != null && typeof u.cost === "object") {
1540
+ const sanitizedCost = sanitizeCost(u.cost);
1541
+ if (sanitizedCost) out.cost = sanitizedCost;
1542
+ }
1543
+ return Object.keys(out).length > 0 ? out : void 0;
1544
+ }
1545
+ /**
1546
+ * Sanitize cost metadata to ensure only finite numeric fields are included.
1547
+ * Prevents UI crashes from calling .toFixed() on non-numbers.
1548
+ */
1549
+ function sanitizeCost(raw) {
1550
+ if (!raw || typeof raw !== "object") return;
1551
+ const total = toFiniteNumber(raw.total);
1552
+ return total !== void 0 ? { total } : void 0;
1553
+ }
1554
+ function sanitizeChatHistoryMessage(message, maxChars = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS) {
1555
+ if (!message || typeof message !== "object") return {
1556
+ message,
1557
+ changed: false
1558
+ };
1559
+ const entry = { ...message };
1560
+ let changed = false;
1561
+ const role = typeof entry.role === "string" ? entry.role.toLowerCase() : "";
1562
+ const preserveExactToolPayload = role === "toolresult" || role === "tool_result" || role === "tool" || role === "function" || typeof entry.toolName === "string" || typeof entry.tool_name === "string" || typeof entry.toolCallId === "string" || typeof entry.tool_call_id === "string";
1563
+ if ("details" in entry) {
1564
+ delete entry.details;
1565
+ changed = true;
1566
+ }
1567
+ if (entry.role !== "assistant") {
1568
+ if ("usage" in entry) {
1569
+ delete entry.usage;
1570
+ changed = true;
1571
+ }
1572
+ if ("cost" in entry) {
1573
+ delete entry.cost;
1574
+ changed = true;
1575
+ }
1576
+ } else {
1577
+ if ("usage" in entry) {
1578
+ const sanitized = sanitizeUsage(entry.usage);
1579
+ if (sanitized) entry.usage = sanitized;
1580
+ else delete entry.usage;
1581
+ changed = true;
1582
+ }
1583
+ if ("cost" in entry) {
1584
+ const sanitized = sanitizeCost(entry.cost);
1585
+ if (sanitized) entry.cost = sanitized;
1586
+ else delete entry.cost;
1587
+ changed = true;
1588
+ }
1589
+ }
1590
+ if (typeof entry.content === "string") {
1591
+ const stripped = stripInlineDirectiveTagsForDisplay(entry.content);
1592
+ if (preserveExactToolPayload) {
1593
+ entry.content = stripped.text;
1594
+ changed ||= stripped.changed;
1595
+ } else {
1596
+ const res = truncateChatHistoryText(stripped.text, maxChars);
1597
+ entry.content = res.text;
1598
+ changed ||= stripped.changed || res.truncated;
1599
+ }
1600
+ } else if (Array.isArray(entry.content)) {
1601
+ const updated = entry.content.map((block) => sanitizeChatHistoryContentBlock(block, {
1602
+ preserveExactToolPayload,
1603
+ maxChars
1604
+ }));
1605
+ if (updated.some((item) => item.changed)) {
1606
+ entry.content = updated.map((item) => item.block);
1607
+ changed = true;
1608
+ }
1609
+ if (entry.role === "assistant" && Array.isArray(entry.content)) {
1610
+ const sanitizedPhases = sanitizeAssistantPhasedContentBlocks(entry.content);
1611
+ if (sanitizedPhases.changed) {
1612
+ entry.content = sanitizedPhases.content;
1613
+ changed = true;
1614
+ }
1615
+ }
1616
+ }
1617
+ if (typeof entry.text === "string") {
1618
+ const stripped = stripInlineDirectiveTagsForDisplay(entry.text);
1619
+ if (preserveExactToolPayload) {
1620
+ entry.text = stripped.text;
1621
+ changed ||= stripped.changed;
1622
+ } else {
1623
+ const res = truncateChatHistoryText(stripped.text, maxChars);
1624
+ entry.text = res.text;
1625
+ changed ||= stripped.changed || res.truncated;
1626
+ }
1627
+ }
1628
+ return {
1629
+ message: changed ? entry : message,
1630
+ changed
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Extract the visible text from an assistant history message for silent-token checks.
1635
+ * Returns `undefined` for non-assistant messages or messages with no extractable text.
1636
+ * When `entry.text` is present it takes precedence over `entry.content` to avoid
1637
+ * dropping messages that carry real text alongside a stale `content: "NO_REPLY"`.
1638
+ */
1639
+ function extractAssistantTextForSilentCheck(message) {
1640
+ if (!message || typeof message !== "object") return;
1641
+ const entry = message;
1642
+ if (entry.role !== "assistant") return;
1643
+ if (typeof entry.text === "string") return entry.text;
1644
+ if (typeof entry.content === "string") return entry.content;
1645
+ if (!Array.isArray(entry.content) || entry.content.length === 0) return;
1646
+ const texts = [];
1647
+ for (const block of entry.content) {
1648
+ if (!block || typeof block !== "object") return;
1649
+ const typed = block;
1650
+ if (typed.type !== "text" || typeof typed.text !== "string") return;
1651
+ texts.push(typed.text);
1652
+ }
1653
+ return texts.length > 0 ? texts.join("\n") : void 0;
1654
+ }
1655
+ function hasAssistantNonTextContent(message) {
1656
+ if (!message || typeof message !== "object") return false;
1657
+ const content = message.content;
1658
+ if (!Array.isArray(content)) return false;
1659
+ return content.some((block) => block && typeof block === "object" && block.type !== "text");
1660
+ }
1661
+ function shouldDropAssistantHistoryMessage(message) {
1662
+ if (!message || typeof message !== "object") return false;
1663
+ if (message.role !== "assistant") return false;
1664
+ if (resolveAssistantMessagePhase(message) === "commentary") return true;
1665
+ const text = extractAssistantTextForSilentCheck(message);
1666
+ if (text === void 0 || !isSuppressedControlReplyText(text)) return false;
1667
+ return !hasAssistantNonTextContent(message);
1668
+ }
1669
+ function sanitizeChatHistoryMessages(messages, maxChars = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS) {
1670
+ if (messages.length === 0) return messages;
1671
+ let changed = false;
1672
+ const next = [];
1673
+ for (const message of messages) {
1674
+ if (shouldDropAssistantHistoryMessage(message)) {
1675
+ changed = true;
1676
+ continue;
1677
+ }
1678
+ const res = sanitizeChatHistoryMessage(message, maxChars);
1679
+ changed ||= res.changed;
1680
+ if (shouldDropAssistantHistoryMessage(res.message)) {
1681
+ changed = true;
1682
+ continue;
1683
+ }
1684
+ next.push(res.message);
1685
+ }
1686
+ return changed ? next : messages;
1687
+ }
1688
+ function appendCanvasBlockToAssistantHistoryMessage(params) {
1689
+ const preview = params.preview;
1690
+ if (!preview || !params.message || typeof params.message !== "object") return params.message;
1691
+ const entry = params.message;
1692
+ const baseContent = Array.isArray(entry.content) ? [...entry.content] : typeof entry.content === "string" ? [{
1693
+ type: "text",
1694
+ text: entry.content
1695
+ }] : typeof entry.text === "string" ? [{
1696
+ type: "text",
1697
+ text: entry.text
1698
+ }] : [];
1699
+ if (!baseContent.some((block) => {
1700
+ if (!block || typeof block !== "object") return false;
1701
+ const typed = block;
1702
+ return typed.type === "canvas" && typed.preview && typeof typed.preview === "object" && (typed.preview.viewId && typed.preview.viewId === preview.viewId || typed.preview.url && typed.preview.url === preview.url);
1703
+ })) baseContent.push({
1704
+ type: "canvas",
1705
+ preview,
1706
+ rawText: params.rawText
1707
+ });
1708
+ return {
1709
+ ...entry,
1710
+ content: baseContent
1711
+ };
1712
+ }
1713
+ function messageContainsToolHistoryContent(message) {
1714
+ if (!message || typeof message !== "object") return false;
1715
+ const entry = message;
1716
+ if (typeof entry.toolCallId === "string" || typeof entry.tool_call_id === "string" || typeof entry.toolName === "string" || typeof entry.tool_name === "string") return true;
1717
+ if (!Array.isArray(entry.content)) return false;
1718
+ return entry.content.some((block) => {
1719
+ if (!block || typeof block !== "object") return false;
1720
+ return isToolHistoryBlockType(block.type);
1721
+ });
1722
+ }
1723
+ function augmentChatHistoryWithCanvasBlocks(messages) {
1724
+ if (messages.length === 0) return messages;
1725
+ const next = [...messages];
1726
+ let changed = false;
1727
+ let lastAssistantIndex = -1;
1728
+ let lastRenderableAssistantIndex = -1;
1729
+ const pending = [];
1730
+ for (let index = 0; index < next.length; index++) {
1731
+ const message = next[index];
1732
+ if (!message || typeof message !== "object") continue;
1733
+ const entry = message;
1734
+ if ((typeof entry.role === "string" ? entry.role.toLowerCase() : "") === "assistant") {
1735
+ lastAssistantIndex = index;
1736
+ if (!messageContainsToolHistoryContent(entry)) {
1737
+ lastRenderableAssistantIndex = index;
1738
+ if (pending.length > 0) {
1739
+ let target = next[index];
1740
+ for (const item of pending) target = appendCanvasBlockToAssistantHistoryMessage({
1741
+ message: target,
1742
+ preview: item.preview,
1743
+ rawText: item.rawText
1744
+ });
1745
+ next[index] = target;
1746
+ pending.length = 0;
1747
+ changed = true;
1748
+ }
1749
+ }
1750
+ continue;
1751
+ }
1752
+ if (!messageContainsToolHistoryContent(entry)) continue;
1753
+ const toolName = typeof entry.toolName === "string" ? entry.toolName : typeof entry.tool_name === "string" ? entry.tool_name : void 0;
1754
+ const text = extractChatHistoryBlockText(entry);
1755
+ const preview = extractCanvasFromText(text, toolName);
1756
+ if (!preview) continue;
1757
+ pending.push({
1758
+ preview,
1759
+ rawText: text ?? null
1760
+ });
1761
+ }
1762
+ if (pending.length > 0) {
1763
+ const targetIndex = lastRenderableAssistantIndex >= 0 ? lastRenderableAssistantIndex : lastAssistantIndex;
1764
+ if (targetIndex >= 0) {
1765
+ let target = next[targetIndex];
1766
+ for (const item of pending) target = appendCanvasBlockToAssistantHistoryMessage({
1767
+ message: target,
1768
+ preview: item.preview,
1769
+ rawText: item.rawText
1770
+ });
1771
+ next[targetIndex] = target;
1772
+ changed = true;
1773
+ }
1774
+ }
1775
+ return changed ? next : messages;
1776
+ }
1777
+ function buildOversizedHistoryPlaceholder(message) {
1778
+ return {
1779
+ role: message && typeof message === "object" && typeof message.role === "string" ? message.role : "assistant",
1780
+ timestamp: message && typeof message === "object" && typeof message.timestamp === "number" ? message.timestamp : Date.now(),
1781
+ content: [{
1782
+ type: "text",
1783
+ text: CHAT_HISTORY_OVERSIZED_PLACEHOLDER
1784
+ }],
1785
+ __genesis: {
1786
+ truncated: true,
1787
+ reason: "oversized"
1788
+ }
1789
+ };
1790
+ }
1791
+ function replaceOversizedChatHistoryMessages(params) {
1792
+ const { messages, maxSingleMessageBytes } = params;
1793
+ if (messages.length === 0) return {
1794
+ messages,
1795
+ replacedCount: 0
1796
+ };
1797
+ let replacedCount = 0;
1798
+ const next = messages.map((message) => {
1799
+ if (jsonUtf8Bytes(message) <= maxSingleMessageBytes) return message;
1800
+ replacedCount += 1;
1801
+ return buildOversizedHistoryPlaceholder(message);
1802
+ });
1803
+ return {
1804
+ messages: replacedCount > 0 ? next : messages,
1805
+ replacedCount
1806
+ };
1807
+ }
1808
+ function enforceChatHistoryFinalBudget(params) {
1809
+ const { messages, maxBytes } = params;
1810
+ if (messages.length === 0) return {
1811
+ messages,
1812
+ placeholderCount: 0
1813
+ };
1814
+ if (jsonUtf8Bytes(messages) <= maxBytes) return {
1815
+ messages,
1816
+ placeholderCount: 0
1817
+ };
1818
+ const last = messages.at(-1);
1819
+ if (last && jsonUtf8Bytes([last]) <= maxBytes) return {
1820
+ messages: [last],
1821
+ placeholderCount: 0
1822
+ };
1823
+ const placeholder = buildOversizedHistoryPlaceholder(last);
1824
+ if (jsonUtf8Bytes([placeholder]) <= maxBytes) return {
1825
+ messages: [placeholder],
1826
+ placeholderCount: 1
1827
+ };
1828
+ return {
1829
+ messages: [],
1830
+ placeholderCount: 0
1831
+ };
1832
+ }
1833
+ function resolveTranscriptPath(params) {
1834
+ const { sessionId, storePath, sessionFile, agentId } = params;
1835
+ if (!storePath && !sessionFile) return null;
1836
+ try {
1837
+ const sessionsDir = storePath ? path.dirname(storePath) : void 0;
1838
+ return resolveSessionFilePath(sessionId, sessionFile ? { sessionFile } : void 0, sessionsDir || agentId ? {
1839
+ sessionsDir,
1840
+ agentId
1841
+ } : void 0);
1842
+ } catch {
1843
+ return null;
1844
+ }
1845
+ }
1846
+ function ensureTranscriptFile(params) {
1847
+ if (fs.existsSync(params.transcriptPath)) return { ok: true };
1848
+ try {
1849
+ fs.mkdirSync(path.dirname(params.transcriptPath), { recursive: true });
1850
+ const header = {
1851
+ type: "session",
1852
+ version: CURRENT_SESSION_VERSION,
1853
+ id: params.sessionId,
1854
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1855
+ cwd: process.cwd()
1856
+ };
1857
+ fs.writeFileSync(params.transcriptPath, `${JSON.stringify(header)}\n`, {
1858
+ encoding: "utf-8",
1859
+ mode: 384
1860
+ });
1861
+ return { ok: true };
1862
+ } catch (err) {
1863
+ return {
1864
+ ok: false,
1865
+ error: err instanceof Error ? err.message : String(err)
1866
+ };
1867
+ }
1868
+ }
1869
+ function transcriptHasIdempotencyKey(transcriptPath, idempotencyKey) {
1870
+ try {
1871
+ const lines = fs.readFileSync(transcriptPath, "utf-8").split(/\r?\n/);
1872
+ for (const line of lines) {
1873
+ if (!line.trim()) continue;
1874
+ if (JSON.parse(line)?.message?.idempotencyKey === idempotencyKey) return true;
1875
+ }
1876
+ return false;
1877
+ } catch {
1878
+ return false;
1879
+ }
1880
+ }
1881
+ function appendAssistantTranscriptMessage(params) {
1882
+ const transcriptPath = resolveTranscriptPath({
1883
+ sessionId: params.sessionId,
1884
+ storePath: params.storePath,
1885
+ sessionFile: params.sessionFile,
1886
+ agentId: params.agentId
1887
+ });
1888
+ if (!transcriptPath) return {
1889
+ ok: false,
1890
+ error: "transcript path not resolved"
1891
+ };
1892
+ if (!fs.existsSync(transcriptPath)) {
1893
+ if (!params.createIfMissing) return {
1894
+ ok: false,
1895
+ error: "transcript file not found"
1896
+ };
1897
+ const ensured = ensureTranscriptFile({
1898
+ transcriptPath,
1899
+ sessionId: params.sessionId
1900
+ });
1901
+ if (!ensured.ok) return {
1902
+ ok: false,
1903
+ error: ensured.error ?? "failed to create transcript file"
1904
+ };
1905
+ }
1906
+ if (params.idempotencyKey && transcriptHasIdempotencyKey(transcriptPath, params.idempotencyKey)) return { ok: true };
1907
+ return appendInjectedAssistantMessageToTranscript({
1908
+ transcriptPath,
1909
+ message: params.message,
1910
+ label: params.label,
1911
+ content: params.content,
1912
+ idempotencyKey: params.idempotencyKey,
1913
+ abortMeta: params.abortMeta
1914
+ });
1915
+ }
1916
+ function collectSessionAbortPartials(params) {
1917
+ const out = [];
1918
+ for (const [runId, active] of params.chatAbortControllers) {
1919
+ if (!params.runIds.has(runId)) continue;
1920
+ const text = params.chatRunBuffers.get(runId);
1921
+ if (!text || !text.trim()) continue;
1922
+ out.push({
1923
+ runId,
1924
+ sessionId: active.sessionId,
1925
+ text,
1926
+ abortOrigin: params.abortOrigin
1927
+ });
1928
+ }
1929
+ return out;
1930
+ }
1931
+ function persistAbortedPartials(params) {
1932
+ if (params.snapshots.length === 0) return;
1933
+ const { storePath, entry } = loadSessionEntry(params.sessionKey);
1934
+ for (const snapshot of params.snapshots) {
1935
+ const sessionId = entry?.sessionId ?? snapshot.sessionId ?? snapshot.runId;
1936
+ const appended = appendAssistantTranscriptMessage({
1937
+ message: snapshot.text,
1938
+ sessionId,
1939
+ storePath,
1940
+ sessionFile: entry?.sessionFile,
1941
+ createIfMissing: true,
1942
+ idempotencyKey: `${snapshot.runId}:assistant`,
1943
+ abortMeta: {
1944
+ aborted: true,
1945
+ origin: snapshot.abortOrigin,
1946
+ runId: snapshot.runId
1947
+ }
1948
+ });
1949
+ if (!appended.ok) params.context.logGateway.warn(`chat.abort transcript append failed: ${appended.error ?? "unknown error"}`);
1950
+ }
1951
+ }
1952
+ function createChatAbortOps(context) {
1953
+ return {
1954
+ chatAbortControllers: context.chatAbortControllers,
1955
+ chatRunBuffers: context.chatRunBuffers,
1956
+ chatDeltaSentAt: context.chatDeltaSentAt,
1957
+ chatDeltaLastBroadcastLen: context.chatDeltaLastBroadcastLen,
1958
+ chatAbortedRuns: context.chatAbortedRuns,
1959
+ removeChatRun: context.removeChatRun,
1960
+ agentRunSeq: context.agentRunSeq,
1961
+ broadcast: context.broadcast,
1962
+ nodeSendToSession: context.nodeSendToSession
1963
+ };
1964
+ }
1965
+ function normalizeOptionalText(value) {
1966
+ return value?.trim() || void 0;
1967
+ }
1968
+ function normalizeExplicitChatSendOrigin(params) {
1969
+ const originatingChannel = normalizeOptionalText(params.originatingChannel);
1970
+ const originatingTo = normalizeOptionalText(params.originatingTo);
1971
+ const accountId = normalizeOptionalText(params.accountId);
1972
+ const messageThreadId = normalizeOptionalText(params.messageThreadId);
1973
+ if (!Boolean(originatingChannel || originatingTo || accountId || messageThreadId)) return { ok: true };
1974
+ const normalizedChannel = normalizeMessageChannel(originatingChannel);
1975
+ if (!normalizedChannel) return {
1976
+ ok: false,
1977
+ error: "originatingChannel is required when using originating route fields"
1978
+ };
1979
+ if (!originatingTo) return {
1980
+ ok: false,
1981
+ error: "originatingTo is required when using originating route fields"
1982
+ };
1983
+ return {
1984
+ ok: true,
1985
+ value: {
1986
+ originatingChannel: normalizedChannel,
1987
+ originatingTo,
1988
+ ...accountId ? { accountId } : {},
1989
+ ...messageThreadId ? { messageThreadId } : {}
1990
+ }
1991
+ };
1992
+ }
1993
+ function resolveChatAbortRequester(client) {
1994
+ const scopes = Array.isArray(client?.connect?.scopes) ? client.connect.scopes : [];
1995
+ return {
1996
+ connId: normalizeOptionalText(client?.connId),
1997
+ deviceId: normalizeOptionalText(client?.connect?.device?.id),
1998
+ isAdmin: scopes.includes(ADMIN_SCOPE)
1999
+ };
2000
+ }
2001
+ function canRequesterAbortChatRun(entry, requester) {
2002
+ if (requester.isAdmin) return true;
2003
+ const ownerDeviceId = normalizeOptionalText(entry.ownerDeviceId);
2004
+ const ownerConnId = normalizeOptionalText(entry.ownerConnId);
2005
+ if (!ownerDeviceId && !ownerConnId) return true;
2006
+ if (ownerDeviceId && requester.deviceId && ownerDeviceId === requester.deviceId) return true;
2007
+ if (ownerConnId && requester.connId && ownerConnId === requester.connId) return true;
2008
+ return false;
2009
+ }
2010
+ function resolveAuthorizedRunIdsForSession(params) {
2011
+ const authorizedRunIds = [];
2012
+ let matchedSessionRuns = 0;
2013
+ for (const [runId, active] of params.chatAbortControllers) {
2014
+ if (active.sessionKey !== params.sessionKey) continue;
2015
+ matchedSessionRuns += 1;
2016
+ if (canRequesterAbortChatRun(active, params.requester)) authorizedRunIds.push(runId);
2017
+ }
2018
+ return {
2019
+ matchedSessionRuns,
2020
+ authorizedRunIds
2021
+ };
2022
+ }
2023
+ function abortChatRunsForSessionKeyWithPartials(params) {
2024
+ const { matchedSessionRuns, authorizedRunIds } = resolveAuthorizedRunIdsForSession({
2025
+ chatAbortControllers: params.context.chatAbortControllers,
2026
+ sessionKey: params.sessionKey,
2027
+ requester: params.requester
2028
+ });
2029
+ if (authorizedRunIds.length === 0) return {
2030
+ aborted: false,
2031
+ runIds: [],
2032
+ unauthorized: matchedSessionRuns > 0
2033
+ };
2034
+ const authorizedRunIdSet = new Set(authorizedRunIds);
2035
+ const snapshots = collectSessionAbortPartials({
2036
+ chatAbortControllers: params.context.chatAbortControllers,
2037
+ chatRunBuffers: params.context.chatRunBuffers,
2038
+ runIds: authorizedRunIdSet,
2039
+ abortOrigin: params.abortOrigin
2040
+ });
2041
+ const runIds = [];
2042
+ for (const runId of authorizedRunIds) if (abortChatRunById(params.ops, {
2043
+ runId,
2044
+ sessionKey: params.sessionKey,
2045
+ stopReason: params.stopReason
2046
+ }).aborted) runIds.push(runId);
2047
+ const res = {
2048
+ aborted: runIds.length > 0,
2049
+ runIds,
2050
+ unauthorized: false
2051
+ };
2052
+ if (res.aborted) persistAbortedPartials({
2053
+ context: params.context,
2054
+ sessionKey: params.sessionKey,
2055
+ snapshots
2056
+ });
2057
+ return res;
2058
+ }
2059
+ function nextChatSeq(context, runId) {
2060
+ const next = (context.agentRunSeq.get(runId) ?? 0) + 1;
2061
+ context.agentRunSeq.set(runId, next);
2062
+ return next;
2063
+ }
2064
+ function broadcastChatFinal(params) {
2065
+ const seq = nextChatSeq({ agentRunSeq: params.context.agentRunSeq }, params.runId);
2066
+ const strippedEnvelopeMessage = stripEnvelopeFromMessage(params.message);
2067
+ const payload = {
2068
+ runId: params.runId,
2069
+ sessionKey: params.sessionKey,
2070
+ seq,
2071
+ state: "final",
2072
+ message: stripInlineDirectiveTagsFromMessageForDisplay(strippedEnvelopeMessage)
2073
+ };
2074
+ params.context.broadcast("chat", payload);
2075
+ params.context.nodeSendToSession(params.sessionKey, "chat", payload);
2076
+ params.context.agentRunSeq.delete(params.runId);
2077
+ }
2078
+ function isBtwReplyPayload(payload) {
2079
+ return typeof payload?.btw?.question === "string" && payload.btw.question.trim().length > 0 && typeof payload.text === "string" && payload.text.trim().length > 0;
2080
+ }
2081
+ function broadcastSideResult(params) {
2082
+ const seq = nextChatSeq({ agentRunSeq: params.context.agentRunSeq }, params.payload.runId);
2083
+ params.context.broadcast("chat.side_result", {
2084
+ ...params.payload,
2085
+ seq
2086
+ });
2087
+ params.context.nodeSendToSession(params.payload.sessionKey, "chat.side_result", {
2088
+ ...params.payload,
2089
+ seq
2090
+ });
2091
+ }
2092
+ function broadcastChatError(params) {
2093
+ const seq = nextChatSeq({ agentRunSeq: params.context.agentRunSeq }, params.runId);
2094
+ const payload = {
2095
+ runId: params.runId,
2096
+ sessionKey: params.sessionKey,
2097
+ seq,
2098
+ state: "error",
2099
+ errorMessage: params.errorMessage
2100
+ };
2101
+ params.context.broadcast("chat", payload);
2102
+ params.context.nodeSendToSession(params.sessionKey, "chat", payload);
2103
+ params.context.agentRunSeq.delete(params.runId);
2104
+ }
2105
+ const chatHandlers = {
2106
+ "chat.history": async ({ params, respond, context }) => {
2107
+ if (!validateChatHistoryParams(params)) {
2108
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid chat.history params: ${formatValidationErrors(validateChatHistoryParams.errors)}`));
2109
+ return;
2110
+ }
2111
+ const { sessionKey, limit, maxChars } = params;
2112
+ const { cfg, storePath, entry } = loadSessionEntry(sessionKey);
2113
+ const sessionId = entry?.sessionId;
2114
+ const resolvedSessionModel = resolveSessionModelRef(cfg, entry, resolveSessionAgentId({
2115
+ sessionKey,
2116
+ config: cfg
2117
+ }));
2118
+ const localMessages = sessionId && storePath ? readSessionMessages(sessionId, storePath, entry?.sessionFile) : [];
2119
+ const rawMessages = augmentChatHistoryWithCliSessionImports({
2120
+ entry,
2121
+ provider: resolvedSessionModel.provider,
2122
+ localMessages
2123
+ });
2124
+ const max = Math.min(1e3, typeof limit === "number" ? limit : 200);
2125
+ const effectiveMaxChars = resolveEffectiveChatHistoryMaxChars(cfg, maxChars);
2126
+ const normalized = augmentChatHistoryWithCanvasBlocks(sanitizeChatHistoryMessages(stripEnvelopeFromMessages(rawMessages.length > max ? rawMessages.slice(-max) : rawMessages), effectiveMaxChars));
2127
+ const maxHistoryBytes = getMaxChatHistoryMessagesBytes();
2128
+ const replaced = replaceOversizedChatHistoryMessages({
2129
+ messages: normalized,
2130
+ maxSingleMessageBytes: Math.min(CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES, maxHistoryBytes)
2131
+ });
2132
+ scheduleChatHistoryManagedImageCleanup({
2133
+ sessionKey,
2134
+ context
2135
+ });
2136
+ const capped = capArrayByJsonBytes(replaced.messages, maxHistoryBytes).items;
2137
+ const bounded = enforceChatHistoryFinalBudget({
2138
+ messages: capped,
2139
+ maxBytes: maxHistoryBytes
2140
+ });
2141
+ const placeholderCount = replaced.replacedCount + bounded.placeholderCount;
2142
+ if (placeholderCount > 0) {
2143
+ chatHistoryPlaceholderEmitCount += placeholderCount;
2144
+ logLargePayload({
2145
+ surface: "gateway.chat.history",
2146
+ action: "truncated",
2147
+ bytes: jsonUtf8Bytes(normalized),
2148
+ limitBytes: maxHistoryBytes,
2149
+ count: placeholderCount,
2150
+ reason: "chat_history_budget"
2151
+ });
2152
+ context.logGateway.debug(`chat.history omitted oversized payloads placeholders=${placeholderCount} total=${chatHistoryPlaceholderEmitCount}`);
2153
+ }
2154
+ let thinkingLevel = entry?.thinkingLevel;
2155
+ if (!thinkingLevel) {
2156
+ const catalog = await context.loadGatewayModelCatalog();
2157
+ thinkingLevel = resolveThinkingDefault({
2158
+ cfg,
2159
+ provider: resolvedSessionModel.provider,
2160
+ model: resolvedSessionModel.model,
2161
+ catalog
2162
+ });
2163
+ }
2164
+ const verboseLevel = entry?.verboseLevel ?? cfg.agents?.defaults?.verboseDefault;
2165
+ respond(true, {
2166
+ sessionKey,
2167
+ sessionId,
2168
+ messages: bounded.messages,
2169
+ thinkingLevel,
2170
+ fastMode: entry?.fastMode,
2171
+ verboseLevel
2172
+ });
2173
+ },
2174
+ "chat.abort": ({ params, respond, context, client }) => {
2175
+ if (!validateChatAbortParams(params)) {
2176
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid chat.abort params: ${formatValidationErrors(validateChatAbortParams.errors)}`));
2177
+ return;
2178
+ }
2179
+ const { sessionKey: rawSessionKey, runId } = params;
2180
+ const ops = createChatAbortOps(context);
2181
+ const requester = resolveChatAbortRequester(client);
2182
+ if (!runId) {
2183
+ const res = abortChatRunsForSessionKeyWithPartials({
2184
+ context,
2185
+ ops,
2186
+ sessionKey: rawSessionKey,
2187
+ abortOrigin: "rpc",
2188
+ stopReason: "rpc",
2189
+ requester
2190
+ });
2191
+ if (res.unauthorized) {
2192
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
2193
+ return;
2194
+ }
2195
+ respond(true, {
2196
+ ok: true,
2197
+ aborted: res.aborted,
2198
+ runIds: res.runIds
2199
+ });
2200
+ return;
2201
+ }
2202
+ const active = context.chatAbortControllers.get(runId);
2203
+ if (!active) {
2204
+ respond(true, {
2205
+ ok: true,
2206
+ aborted: false,
2207
+ runIds: []
2208
+ });
2209
+ return;
2210
+ }
2211
+ if (active.sessionKey !== rawSessionKey) {
2212
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match sessionKey"));
2213
+ return;
2214
+ }
2215
+ if (!canRequesterAbortChatRun(active, requester)) {
2216
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
2217
+ return;
2218
+ }
2219
+ const partialText = context.chatRunBuffers.get(runId);
2220
+ const res = abortChatRunById(ops, {
2221
+ runId,
2222
+ sessionKey: rawSessionKey,
2223
+ stopReason: "rpc"
2224
+ });
2225
+ if (res.aborted && partialText && partialText.trim()) persistAbortedPartials({
2226
+ context,
2227
+ sessionKey: rawSessionKey,
2228
+ snapshots: [{
2229
+ runId,
2230
+ sessionId: active.sessionId,
2231
+ text: partialText,
2232
+ abortOrigin: "rpc"
2233
+ }]
2234
+ });
2235
+ respond(true, {
2236
+ ok: true,
2237
+ aborted: res.aborted,
2238
+ runIds: res.aborted ? [runId] : []
2239
+ });
2240
+ },
2241
+ "chat.send": async ({ params, respond, context, client }) => {
2242
+ if (!validateChatSendParams(params)) {
2243
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid chat.send params: ${formatValidationErrors(validateChatSendParams.errors)}`));
2244
+ return;
2245
+ }
2246
+ const p = params;
2247
+ const explicitOriginResult = normalizeExplicitChatSendOrigin({
2248
+ originatingChannel: p.originatingChannel,
2249
+ originatingTo: p.originatingTo,
2250
+ accountId: p.originatingAccountId,
2251
+ messageThreadId: p.originatingThreadId
2252
+ });
2253
+ if (!explicitOriginResult.ok) {
2254
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, explicitOriginResult.error));
2255
+ return;
2256
+ }
2257
+ if ((p.systemInputProvenance || p.systemProvenanceReceipt || explicitOriginResult.value) && !canInjectSystemProvenance(client)) {
2258
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, p.systemInputProvenance || p.systemProvenanceReceipt ? "system provenance fields require admin scope" : "originating route fields require admin scope"));
2259
+ return;
2260
+ }
2261
+ const sanitizedMessageResult = sanitizeChatSendMessageInput(p.message);
2262
+ if (!sanitizedMessageResult.ok) {
2263
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, sanitizedMessageResult.error));
2264
+ return;
2265
+ }
2266
+ const systemReceiptResult = normalizeOptionalChatSystemReceipt(p.systemProvenanceReceipt);
2267
+ if (!systemReceiptResult.ok) {
2268
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, systemReceiptResult.error));
2269
+ return;
2270
+ }
2271
+ const inboundMessage = sanitizedMessageResult.message;
2272
+ const systemInputProvenance = normalizeInputProvenance(p.systemInputProvenance);
2273
+ const systemProvenanceReceipt = systemReceiptResult.receipt;
2274
+ const stopCommand = isChatStopCommandText(inboundMessage);
2275
+ const normalizedAttachments = normalizeRpcAttachmentsToChatAttachments(p.attachments);
2276
+ if (!inboundMessage.trim() && normalizedAttachments.length === 0) {
2277
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "message or attachment required"));
2278
+ return;
2279
+ }
2280
+ const rawSessionKey = p.sessionKey;
2281
+ const { cfg, entry, canonicalKey: sessionKey } = loadSessionEntry(rawSessionKey);
2282
+ const deletedAgentId = resolveDeletedAgentIdFromSessionKey(cfg, sessionKey);
2283
+ if (deletedAgentId !== null) {
2284
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `Agent "${deletedAgentId}" no longer exists in configuration`));
2285
+ return;
2286
+ }
2287
+ const agentId = resolveSessionAgentId({
2288
+ sessionKey,
2289
+ config: cfg
2290
+ });
2291
+ let parsedMessage = inboundMessage;
2292
+ let parsedImages = [];
2293
+ let imageOrder = [];
2294
+ let offloadedRefs = [];
2295
+ const timeoutMs = resolveAgentTimeoutMs({
2296
+ cfg,
2297
+ overrideMs: p.timeoutMs
2298
+ });
2299
+ const now = Date.now();
2300
+ const clientRunId = p.idempotencyKey;
2301
+ if (resolveSendPolicy({
2302
+ cfg,
2303
+ entry,
2304
+ sessionKey,
2305
+ channel: entry?.channel,
2306
+ chatType: entry?.chatType
2307
+ }) === "deny") {
2308
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "send blocked by session policy"));
2309
+ return;
2310
+ }
2311
+ if (stopCommand) {
2312
+ const res = abortChatRunsForSessionKeyWithPartials({
2313
+ context,
2314
+ ops: createChatAbortOps(context),
2315
+ sessionKey: rawSessionKey,
2316
+ abortOrigin: "stop-command",
2317
+ stopReason: "stop",
2318
+ requester: resolveChatAbortRequester(client)
2319
+ });
2320
+ if (res.unauthorized) {
2321
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized"));
2322
+ return;
2323
+ }
2324
+ respond(true, {
2325
+ ok: true,
2326
+ aborted: res.aborted,
2327
+ runIds: res.runIds
2328
+ });
2329
+ return;
2330
+ }
2331
+ const cached = context.dedupe.get(`chat:${clientRunId}`);
2332
+ if (cached) {
2333
+ respond(cached.ok, cached.payload, cached.error, { cached: true });
2334
+ return;
2335
+ }
2336
+ if (context.chatAbortControllers.get(clientRunId)) {
2337
+ respond(true, {
2338
+ runId: clientRunId,
2339
+ status: "in_flight"
2340
+ }, void 0, {
2341
+ cached: true,
2342
+ runId: clientRunId
2343
+ });
2344
+ return;
2345
+ }
2346
+ const explicitOriginTargetsPlugin = explicitOriginTargetsPluginBinding(explicitOriginResult.value);
2347
+ if (normalizedAttachments.length > 0) {
2348
+ const modelRef = resolveSessionModelRef(cfg, entry, agentId);
2349
+ const supportsImages = await resolveGatewayModelSupportsImages({
2350
+ loadGatewayModelCatalog: context.loadGatewayModelCatalog,
2351
+ provider: modelRef.provider,
2352
+ model: modelRef.model
2353
+ }) || explicitOriginTargetsAcpSession(explicitOriginResult.value) || explicitOriginTargetsPlugin;
2354
+ try {
2355
+ const parsed = await parseMessageWithAttachments(inboundMessage, normalizedAttachments, {
2356
+ maxBytes: 5e6,
2357
+ log: context.logGateway,
2358
+ supportsImages
2359
+ });
2360
+ parsedMessage = parsed.message;
2361
+ parsedImages = parsed.images;
2362
+ imageOrder = parsed.imageOrder;
2363
+ offloadedRefs = parsed.offloadedRefs;
2364
+ } catch (err) {
2365
+ respond(false, void 0, errorShape(err instanceof MediaOffloadError ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST, String(err)));
2366
+ return;
2367
+ }
2368
+ }
2369
+ try {
2370
+ const activeRunAbort = registerChatAbortController({
2371
+ chatAbortControllers: context.chatAbortControllers,
2372
+ runId: clientRunId,
2373
+ sessionId: entry?.sessionId ?? clientRunId,
2374
+ sessionKey: rawSessionKey,
2375
+ timeoutMs,
2376
+ now,
2377
+ ownerConnId: normalizeOptionalText(client?.connId),
2378
+ ownerDeviceId: normalizeOptionalText(client?.connect?.device?.id),
2379
+ kind: "chat-send"
2380
+ });
2381
+ context.addChatRun(clientRunId, {
2382
+ sessionKey,
2383
+ clientRunId
2384
+ });
2385
+ respond(true, {
2386
+ runId: clientRunId,
2387
+ status: "started"
2388
+ }, void 0, { runId: clientRunId });
2389
+ const persistedImagesPromise = persistChatSendImages({
2390
+ images: parsedImages,
2391
+ imageOrder,
2392
+ offloadedRefs,
2393
+ client,
2394
+ logGateway: context.logGateway
2395
+ });
2396
+ const pluginBoundMediaFields = explicitOriginTargetsPlugin && parsedImages.length > 0 ? resolveChatSendTranscriptMediaFields(await persistedImagesPromise) : {};
2397
+ const trimmedMessage = parsedMessage.trim();
2398
+ const commandBody = Boolean(p.thinking && trimmedMessage && !trimmedMessage.startsWith("/")) ? `/think ${p.thinking} ${parsedMessage}` : parsedMessage;
2399
+ const messageForAgent = systemProvenanceReceipt ? [systemProvenanceReceipt, parsedMessage].filter(Boolean).join("\n\n") : parsedMessage;
2400
+ const clientInfo = client?.connect?.client;
2401
+ const { originatingChannel, originatingTo, accountId, messageThreadId, explicitDeliverRoute } = resolveChatSendOriginatingRoute({
2402
+ client: clientInfo,
2403
+ deliver: p.deliver,
2404
+ entry,
2405
+ explicitOrigin: explicitOriginResult.value,
2406
+ hasConnectedClient: client?.connect !== void 0,
2407
+ mainKey: cfg.session?.mainKey,
2408
+ sessionKey
2409
+ });
2410
+ const ctx = {
2411
+ Body: messageForAgent,
2412
+ BodyForAgent: injectTimestamp(messageForAgent, timestampOptsFromConfig(cfg)),
2413
+ BodyForCommands: commandBody,
2414
+ RawBody: parsedMessage,
2415
+ CommandBody: commandBody,
2416
+ InputProvenance: systemInputProvenance,
2417
+ SessionKey: sessionKey,
2418
+ Provider: INTERNAL_MESSAGE_CHANNEL,
2419
+ Surface: INTERNAL_MESSAGE_CHANNEL,
2420
+ OriginatingChannel: originatingChannel,
2421
+ OriginatingTo: originatingTo,
2422
+ ExplicitDeliverRoute: explicitDeliverRoute,
2423
+ AccountId: accountId,
2424
+ MessageThreadId: messageThreadId,
2425
+ ChatType: "direct",
2426
+ CommandAuthorized: true,
2427
+ MessageSid: clientRunId,
2428
+ SenderId: clientInfo?.id,
2429
+ SenderName: clientInfo?.displayName,
2430
+ SenderUsername: clientInfo?.displayName,
2431
+ GatewayClientScopes: client?.connect?.scopes ?? [],
2432
+ ...pluginBoundMediaFields
2433
+ };
2434
+ const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({
2435
+ cfg,
2436
+ agentId,
2437
+ channel: INTERNAL_MESSAGE_CHANNEL
2438
+ });
2439
+ const deliveredReplies = [];
2440
+ let appendedWebchatAgentMedia = false;
2441
+ let userTranscriptUpdatePromise = null;
2442
+ const emitUserTranscriptUpdate = async () => {
2443
+ if (userTranscriptUpdatePromise) {
2444
+ await userTranscriptUpdatePromise;
2445
+ return;
2446
+ }
2447
+ userTranscriptUpdatePromise = (async () => {
2448
+ const { storePath: latestStorePath, entry: latestEntry } = loadSessionEntry(sessionKey);
2449
+ const resolvedSessionId = latestEntry?.sessionId ?? entry?.sessionId;
2450
+ if (!resolvedSessionId) return;
2451
+ const transcriptPath = resolveTranscriptPath({
2452
+ sessionId: resolvedSessionId,
2453
+ storePath: latestStorePath,
2454
+ sessionFile: latestEntry?.sessionFile ?? entry?.sessionFile,
2455
+ agentId
2456
+ });
2457
+ if (!transcriptPath) return;
2458
+ const persistedImages = await persistedImagesPromise;
2459
+ emitSessionTranscriptUpdate({
2460
+ sessionFile: transcriptPath,
2461
+ sessionKey,
2462
+ message: buildChatSendTranscriptMessage({
2463
+ message: parsedMessage,
2464
+ savedImages: persistedImages,
2465
+ timestamp: now
2466
+ })
2467
+ });
2468
+ })();
2469
+ await userTranscriptUpdatePromise;
2470
+ };
2471
+ let transcriptMediaRewriteDone = false;
2472
+ const rewriteUserTranscriptMedia = async () => {
2473
+ if (transcriptMediaRewriteDone) return;
2474
+ const { storePath: latestStorePath, entry: latestEntry } = loadSessionEntry(sessionKey);
2475
+ const resolvedSessionId = latestEntry?.sessionId ?? entry?.sessionId;
2476
+ if (!resolvedSessionId) return;
2477
+ const transcriptPath = resolveTranscriptPath({
2478
+ sessionId: resolvedSessionId,
2479
+ storePath: latestStorePath,
2480
+ sessionFile: latestEntry?.sessionFile ?? entry?.sessionFile,
2481
+ agentId
2482
+ });
2483
+ if (!transcriptPath) return;
2484
+ transcriptMediaRewriteDone = true;
2485
+ await rewriteChatSendUserTurnMediaPaths({
2486
+ transcriptPath,
2487
+ sessionKey,
2488
+ message: parsedMessage,
2489
+ savedImages: await persistedImagesPromise
2490
+ });
2491
+ };
2492
+ const appendWebchatAgentMediaTranscriptIfNeeded = async (payload) => {
2493
+ if (!agentRunStarted || appendedWebchatAgentMedia || !isMediaBearingPayload(payload)) return;
2494
+ const { storePath: latestStorePath, entry: latestEntry } = loadSessionEntry(sessionKey);
2495
+ const sessionId = latestEntry?.sessionId ?? entry?.sessionId ?? clientRunId;
2496
+ const resolvedTranscriptPath = resolveTranscriptPath({
2497
+ sessionId,
2498
+ storePath: latestStorePath,
2499
+ sessionFile: latestEntry?.sessionFile ?? entry?.sessionFile,
2500
+ agentId
2501
+ });
2502
+ const mediaLocalRoots = appendLocalMediaParentRoots(getAgentScopedMediaLocalRoots(cfg, agentId), resolvedTranscriptPath ? [resolvedTranscriptPath] : void 0);
2503
+ const assistantContent = await buildAssistantDisplayContentFromReplyPayloads({
2504
+ sessionKey,
2505
+ payloads: [payload],
2506
+ managedImageLocalRoots: mediaLocalRoots,
2507
+ includeSensitiveMedia: payload.sensitiveMedia !== true,
2508
+ onLocalAudioAccessDenied: (message) => {
2509
+ context.logGateway.warn(`webchat audio embedding denied local path: ${message}`);
2510
+ },
2511
+ onManagedImagePrepareError: (message) => {
2512
+ context.logGateway.warn(`webchat image embedding skipped attachment: ${message}`);
2513
+ }
2514
+ });
2515
+ const mediaMessage = await buildWebchatAssistantMediaMessage([payload], {
2516
+ localRoots: mediaLocalRoots,
2517
+ onLocalAudioAccessDenied: (message) => {
2518
+ context.logGateway.warn(`webchat audio embedding denied local path: ${message}`);
2519
+ }
2520
+ });
2521
+ const persistedAssistantContent = replaceAssistantContentTextBlocks(assistantContent, mediaMessage);
2522
+ const persistedContentForAppend = hasAssistantDisplayMediaContent(persistedAssistantContent) ? persistedAssistantContent : void 0;
2523
+ const transcriptReply = mediaMessage?.transcriptText ?? extractAssistantDisplayTextFromContent(assistantContent) ?? buildTranscriptReplyText([payload]);
2524
+ if (!transcriptReply && !persistedAssistantContent?.length && !assistantContent?.length) return;
2525
+ const appended = appendAssistantTranscriptMessage({
2526
+ message: transcriptReply,
2527
+ ...persistedContentForAppend?.length ? { content: persistedContentForAppend } : {},
2528
+ sessionId,
2529
+ storePath: latestStorePath,
2530
+ sessionFile: latestEntry?.sessionFile,
2531
+ agentId,
2532
+ createIfMissing: true,
2533
+ idempotencyKey: `${clientRunId}:assistant-media`
2534
+ });
2535
+ if (appended.ok) {
2536
+ if (appended.messageId && assistantContent?.length) await attachManagedOutgoingImagesToMessage({
2537
+ messageId: appended.messageId,
2538
+ blocks: assistantContent
2539
+ });
2540
+ appendedWebchatAgentMedia = true;
2541
+ return;
2542
+ }
2543
+ context.logGateway.warn(`webchat transcript append failed for media reply: ${appended.error ?? "unknown error"}`);
2544
+ };
2545
+ const dispatcher = createReplyDispatcher({
2546
+ ...replyPipeline,
2547
+ onError: (err) => {
2548
+ context.logGateway.warn(`webchat dispatch failed: ${formatForLog(err)}`);
2549
+ },
2550
+ deliver: async (payload, info) => {
2551
+ switch (info.kind) {
2552
+ case "block":
2553
+ case "final":
2554
+ deliveredReplies.push({
2555
+ payload,
2556
+ kind: info.kind
2557
+ });
2558
+ await appendWebchatAgentMediaTranscriptIfNeeded(payload);
2559
+ break;
2560
+ case "tool":
2561
+ if (isMediaBearingPayload(payload)) deliveredReplies.push({
2562
+ payload: {
2563
+ ...payload,
2564
+ text: void 0
2565
+ },
2566
+ kind: "final"
2567
+ });
2568
+ break;
2569
+ }
2570
+ }
2571
+ });
2572
+ emitUserTranscriptUpdate().catch((transcriptErr) => {
2573
+ context.logGateway.warn(`webchat eager user transcript update failed: ${formatForLog(transcriptErr)}`);
2574
+ });
2575
+ let agentRunStarted = false;
2576
+ dispatchInboundMessage({
2577
+ ctx,
2578
+ cfg,
2579
+ dispatcher,
2580
+ replyOptions: {
2581
+ runId: clientRunId,
2582
+ abortSignal: activeRunAbort.controller.signal,
2583
+ images: parsedImages.length > 0 ? parsedImages : void 0,
2584
+ imageOrder: imageOrder.length > 0 ? imageOrder : void 0,
2585
+ onAgentRunStart: (runId) => {
2586
+ agentRunStarted = true;
2587
+ emitUserTranscriptUpdate();
2588
+ const connId = typeof client?.connId === "string" ? client.connId : void 0;
2589
+ const wantsToolEvents = hasGatewayClientCap(client?.connect?.caps, GATEWAY_CLIENT_CAPS.TOOL_EVENTS);
2590
+ if (connId && wantsToolEvents) {
2591
+ context.registerToolEventRecipient(runId, connId);
2592
+ for (const [activeRunId, active] of context.chatAbortControllers) if (activeRunId !== runId && active.sessionKey === p.sessionKey) context.registerToolEventRecipient(activeRunId, connId);
2593
+ }
2594
+ },
2595
+ onModelSelected
2596
+ }
2597
+ }).then(async () => {
2598
+ await rewriteUserTranscriptMedia();
2599
+ if (!agentRunStarted) {
2600
+ await emitUserTranscriptUpdate();
2601
+ const btwReplies = deliveredReplies.map((entry) => entry.payload).filter(isBtwReplyPayload);
2602
+ const btwText = btwReplies.map((payload) => payload.text.trim()).filter(Boolean).join("\n\n").trim();
2603
+ if (btwReplies.length > 0 && btwText) {
2604
+ broadcastSideResult({
2605
+ context,
2606
+ payload: {
2607
+ kind: "btw",
2608
+ runId: clientRunId,
2609
+ sessionKey,
2610
+ question: btwReplies[0].btw.question.trim(),
2611
+ text: btwText,
2612
+ isError: btwReplies.some((payload) => payload.isError),
2613
+ ts: Date.now()
2614
+ }
2615
+ });
2616
+ broadcastChatFinal({
2617
+ context,
2618
+ runId: clientRunId,
2619
+ sessionKey
2620
+ });
2621
+ } else {
2622
+ const finalPayloads = deliveredReplies.filter((entry) => entry.kind === "final").map((entry) => entry.payload);
2623
+ const { storePath: latestStorePath, entry: latestEntry } = loadSessionEntry(sessionKey);
2624
+ const sessionId = latestEntry?.sessionId ?? entry?.sessionId ?? clientRunId;
2625
+ const resolvedTranscriptPath = resolveTranscriptPath({
2626
+ sessionId,
2627
+ storePath: latestStorePath,
2628
+ sessionFile: latestEntry?.sessionFile ?? entry?.sessionFile,
2629
+ agentId
2630
+ });
2631
+ const mediaLocalRoots = appendLocalMediaParentRoots(getAgentScopedMediaLocalRoots(cfg, agentId), resolvedTranscriptPath ? [resolvedTranscriptPath] : void 0);
2632
+ const assistantContent = await buildAssistantDisplayContentFromReplyPayloads({
2633
+ sessionKey,
2634
+ payloads: finalPayloads,
2635
+ managedImageLocalRoots: mediaLocalRoots,
2636
+ includeSensitiveMedia: false,
2637
+ onLocalAudioAccessDenied: (message) => {
2638
+ context.logGateway.warn(`webchat audio embedding denied local path: ${message}`);
2639
+ },
2640
+ onManagedImagePrepareError: (message) => {
2641
+ context.logGateway.warn(`webchat image embedding skipped attachment: ${message}`);
2642
+ }
2643
+ });
2644
+ const mediaMessage = await buildWebchatAssistantMediaMessage(finalPayloads, {
2645
+ localRoots: mediaLocalRoots,
2646
+ onLocalAudioAccessDenied: (message) => {
2647
+ context.logGateway.warn(`webchat audio embedding denied local path: ${message}`);
2648
+ }
2649
+ });
2650
+ const persistedAssistantContent = replaceAssistantContentTextBlocks(hasSensitiveMediaPayload(finalPayloads) ? await buildAssistantDisplayContentFromReplyPayloads({
2651
+ sessionKey,
2652
+ payloads: finalPayloads,
2653
+ managedImageLocalRoots: mediaLocalRoots,
2654
+ includeSensitiveMedia: false,
2655
+ onLocalAudioAccessDenied: (message) => {
2656
+ context.logGateway.warn(`webchat audio embedding denied local path: ${message}`);
2657
+ },
2658
+ onManagedImagePrepareError: (message) => {
2659
+ context.logGateway.warn(`webchat image embedding skipped attachment: ${message}`);
2660
+ }
2661
+ }) : assistantContent, mediaMessage);
2662
+ const persistedContentForAppend = hasAssistantDisplayMediaContent(persistedAssistantContent) ? persistedAssistantContent : void 0;
2663
+ const broadcastAssistantContent = hasAssistantDisplayMediaContent(assistantContent) ? assistantContent : hasAssistantDisplayMediaContent(mediaMessage?.content) ? mediaMessage?.content : assistantContent;
2664
+ const displayReply = extractAssistantDisplayTextFromContent(assistantContent) ?? buildTranscriptReplyText(finalPayloads);
2665
+ const transcriptReply = mediaMessage?.transcriptText || buildTranscriptReplyText(finalPayloads) || displayReply;
2666
+ let message;
2667
+ if (transcriptReply || persistedContentForAppend?.length || assistantContent?.length) {
2668
+ const appended = appendAssistantTranscriptMessage({
2669
+ message: transcriptReply,
2670
+ ...persistedContentForAppend?.length ? { content: persistedContentForAppend } : {},
2671
+ sessionId,
2672
+ storePath: latestStorePath,
2673
+ sessionFile: latestEntry?.sessionFile,
2674
+ agentId,
2675
+ createIfMissing: true
2676
+ });
2677
+ if (appended.ok) {
2678
+ if (appended.messageId && assistantContent?.length) await attachManagedOutgoingImagesToMessage({
2679
+ messageId: appended.messageId,
2680
+ blocks: assistantContent
2681
+ });
2682
+ message = broadcastAssistantContent?.length ? {
2683
+ ...appended.message,
2684
+ content: broadcastAssistantContent
2685
+ } : appended.message;
2686
+ } else {
2687
+ context.logGateway.warn(`webchat transcript append failed: ${appended.error ?? "unknown error"}`);
2688
+ const fallbackAssistantContent = stripManagedOutgoingAssistantContentBlocks(persistedAssistantContent) ?? stripManagedOutgoingAssistantContentBlocks(assistantContent);
2689
+ const fallbackText = extractAssistantDisplayText(fallbackAssistantContent) ?? displayReply;
2690
+ const now = Date.now();
2691
+ message = {
2692
+ role: "assistant",
2693
+ ...fallbackAssistantContent?.length ? { content: fallbackAssistantContent } : fallbackText ? { content: [{
2694
+ type: "text",
2695
+ text: fallbackText
2696
+ }] } : {},
2697
+ ...fallbackText ? { text: fallbackText } : {},
2698
+ timestamp: now,
2699
+ stopReason: "stop",
2700
+ usage: {
2701
+ input: 0,
2702
+ output: 0,
2703
+ totalTokens: 0
2704
+ }
2705
+ };
2706
+ }
2707
+ }
2708
+ broadcastChatFinal({
2709
+ context,
2710
+ runId: clientRunId,
2711
+ sessionKey,
2712
+ message
2713
+ });
2714
+ }
2715
+ } else emitUserTranscriptUpdate();
2716
+ setGatewayDedupeEntry({
2717
+ dedupe: context.dedupe,
2718
+ key: `chat:${clientRunId}`,
2719
+ entry: {
2720
+ ts: Date.now(),
2721
+ ok: true,
2722
+ payload: {
2723
+ runId: clientRunId,
2724
+ status: "ok"
2725
+ }
2726
+ }
2727
+ });
2728
+ }).catch((err) => {
2729
+ rewriteUserTranscriptMedia().catch((rewriteErr) => {
2730
+ context.logGateway.warn(`webchat transcript media rewrite failed after error: ${formatForLog(rewriteErr)}`);
2731
+ });
2732
+ emitUserTranscriptUpdate().catch((transcriptErr) => {
2733
+ context.logGateway.warn(`webchat user transcript update failed after error: ${formatForLog(transcriptErr)}`);
2734
+ });
2735
+ const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
2736
+ setGatewayDedupeEntry({
2737
+ dedupe: context.dedupe,
2738
+ key: `chat:${clientRunId}`,
2739
+ entry: {
2740
+ ts: Date.now(),
2741
+ ok: false,
2742
+ payload: {
2743
+ runId: clientRunId,
2744
+ status: "error",
2745
+ summary: String(err)
2746
+ },
2747
+ error
2748
+ }
2749
+ });
2750
+ broadcastChatError({
2751
+ context,
2752
+ runId: clientRunId,
2753
+ sessionKey,
2754
+ errorMessage: String(err)
2755
+ });
2756
+ }).finally(() => {
2757
+ activeRunAbort.cleanup();
2758
+ context.removeChatRun(clientRunId, clientRunId, sessionKey);
2759
+ });
2760
+ } catch (err) {
2761
+ context.chatAbortControllers.delete(clientRunId);
2762
+ context.removeChatRun(clientRunId, clientRunId, sessionKey);
2763
+ const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
2764
+ const payload = {
2765
+ runId: clientRunId,
2766
+ status: "error",
2767
+ summary: String(err)
2768
+ };
2769
+ setGatewayDedupeEntry({
2770
+ dedupe: context.dedupe,
2771
+ key: `chat:${clientRunId}`,
2772
+ entry: {
2773
+ ts: Date.now(),
2774
+ ok: false,
2775
+ payload,
2776
+ error
2777
+ }
2778
+ });
2779
+ respond(false, payload, error, {
2780
+ runId: clientRunId,
2781
+ error: formatForLog(err)
2782
+ });
2783
+ }
2784
+ },
2785
+ "chat.inject": async ({ params, respond, context }) => {
2786
+ if (!validateChatInjectParams(params)) {
2787
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid chat.inject params: ${formatValidationErrors(validateChatInjectParams.errors)}`));
2788
+ return;
2789
+ }
2790
+ const p = params;
2791
+ const rawSessionKey = p.sessionKey;
2792
+ const { cfg, storePath, entry, canonicalKey: sessionKey } = loadSessionEntry(rawSessionKey);
2793
+ const sessionId = entry?.sessionId;
2794
+ if (!sessionId || !storePath) {
2795
+ respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "session not found"));
2796
+ return;
2797
+ }
2798
+ const appended = appendAssistantTranscriptMessage({
2799
+ message: p.message,
2800
+ label: p.label,
2801
+ sessionId,
2802
+ storePath,
2803
+ sessionFile: entry?.sessionFile,
2804
+ agentId: resolveSessionAgentId({
2805
+ sessionKey,
2806
+ config: cfg
2807
+ }),
2808
+ createIfMissing: true
2809
+ });
2810
+ if (!appended.ok || !appended.messageId || !appended.message) {
2811
+ respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, `failed to write transcript: ${appended.error ?? "unknown error"}`));
2812
+ return;
2813
+ }
2814
+ const chatPayload = {
2815
+ runId: `inject-${appended.messageId}`,
2816
+ sessionKey,
2817
+ seq: 0,
2818
+ state: "final",
2819
+ message: stripInlineDirectiveTagsFromMessageForDisplay(stripEnvelopeFromMessage(appended.message))
2820
+ };
2821
+ context.broadcast("chat", chatPayload);
2822
+ context.nodeSendToSession(sessionKey, "chat", chatPayload);
2823
+ respond(true, {
2824
+ ok: true,
2825
+ messageId: appended.messageId
2826
+ });
2827
+ }
2828
+ };
2829
+ //#endregion
2830
+ export { TICK_INTERVAL_MS as C, MAX_PREAUTH_PAYLOAD_BYTES as S, augmentChatHistoryWithCliSessionImports as T, DEDUPE_MAX as _, enforceChatHistoryFinalBudget as a, MAX_BUFFERED_BYTES as b, sanitizeChatHistoryMessages as c, waitForTerminalGatewayDedupe as d, isSuppressedControlReplyLeadFragment as f, resolveAgentRunExpiresAtMs as g, registerChatAbortController as h, chatHandlers as i, readTerminalSnapshotFromGatewayDedupe as l, abortChatRunById as m, DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS as n, replaceOversizedChatHistoryMessages as o, isSuppressedControlReplyText as p, augmentChatHistoryWithCanvasBlocks as r, resolveEffectiveChatHistoryMaxChars as s, CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES as t, setGatewayDedupeEntry as u, DEDUPE_TTL_MS as v, getMaxChatHistoryMessagesBytes as w, MAX_PAYLOAD_BYTES as x, HEALTH_REFRESH_INTERVAL_MS as y };