@pixelzx/genesis 2026.5.10-2 → 2026.5.10-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1017) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-o_hg2xtq.js +201 -0
  4. package/dist/abort.runtime-C8y_LD66.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-BaxyfsNG.js +107 -0
  7. package/dist/accounts-CBI-56kp.js +104 -0
  8. package/dist/accounts-m2xbhdqn.js +2 -0
  9. package/dist/acp-cli-BOlwnmxd.js +2193 -0
  10. package/dist/acp-spawn-BrI6X9SH.js +2 -0
  11. package/dist/acp-spawn-xahA0x4e.js +1093 -0
  12. package/dist/acp-stateful-target-driver-B0_0BB8d.js +89 -0
  13. package/dist/action-agents-BLXVAHpm.js +67 -0
  14. package/dist/action-focus-Bl80EFqG.js +132 -0
  15. package/dist/action-help-CBbcn9Xo.js +7 -0
  16. package/dist/action-info-DrggqbpC.js +101 -0
  17. package/dist/action-kill-p6a-p_Wl.js +33 -0
  18. package/dist/action-list-4o0eiRPy.js +21 -0
  19. package/dist/action-log-C2VTzCV-.js +30 -0
  20. package/dist/action-send-DQE2YhZv.js +39 -0
  21. package/dist/action-spawn-DeTOlrlr.js +47 -0
  22. package/dist/action-unfocus-CUJ_-To0.js +29 -0
  23. package/dist/actions.runtime-BME76tM1.js +18 -0
  24. package/dist/actions.runtime-DgFQtpdt.js +5 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-DvPQGyLY.js +2 -0
  27. package/dist/agent-command-Dv8Kifbw.js +874 -0
  28. package/dist/agent-harness-runtime-rPtHDzbH.js +144 -0
  29. package/dist/agent-runner-utils-Cwcsq2Vg.js +239 -0
  30. package/dist/agent-runner.runtime-EDmsi-tw.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-BZ7qw7Go.js +18 -0
  33. package/dist/agents-BmdK7DYn.js +954 -0
  34. package/dist/agents-ojp3yzuP.js +5 -0
  35. package/dist/aliases-B-xkGRWv.js +2 -0
  36. package/dist/aliases-CeyLk8gs.js +96 -0
  37. package/dist/api-7RMNrU--.js +139 -0
  38. package/dist/api-DuTxAbzX.js +5 -0
  39. package/dist/api-S68mLw4i.js +3 -0
  40. package/dist/approval-gateway-resolver-D6GUSzWU.js +29 -0
  41. package/dist/approval-gateway-runtime-CLSx2pjl.js +2 -0
  42. package/dist/approval-handler-runtime-D_pDErDf.js +439 -0
  43. package/dist/approval-native-runtime-DMmho8f_.js +729 -0
  44. package/dist/attempt-execution.runtime-BiBQNA9X.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-NLkGfNY6.js +221 -0
  47. package/dist/attempt.tool-run-context-DWlgJ-_O.js +933 -0
  48. package/dist/audit-UgEtgbwZ.js +939 -0
  49. package/dist/audit.runtime--guvdA_A.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-C50R0MRq.js +2 -0
  52. package/dist/auth-D0-jQ58t.js +383 -0
  53. package/dist/auth-order-BFJrCRu5.js +96 -0
  54. package/dist/auth-order-DSgYrJ_p.js +2 -0
  55. package/dist/bash-tools-DHuwAZ58.js +2824 -0
  56. package/dist/bash-tools-D_feNjoF.js +3 -0
  57. package/dist/binding-routing-CY1eMDau.js +85 -0
  58. package/dist/binding-targets-WwNSyphm.js +121 -0
  59. package/dist/bridge-server-D6UfpfpG.js +113 -0
  60. package/dist/browser-control-auth-D68lDX1S.js +2 -0
  61. package/dist/browser-node-runtime-CY1lVQqq.js +12 -0
  62. package/dist/browser-profiles-B49YcSoc.js +2 -0
  63. package/dist/browser-runtime-BDL147Ka.js +387 -0
  64. package/dist/browser-setup-tools-C03RsiTe.js +13 -0
  65. package/dist/build-DLN8Lh14.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-BNALogg6.js +331 -0
  70. package/dist/call-PW7UP-CK.js +3 -0
  71. package/dist/call.runtime-CYfH8MdC.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-B4UpH1T0.js +1401 -0
  74. package/dist/catchup-CXQzIWv3.js +300 -0
  75. package/dist/channel-BiZSvVcj.js +297 -0
  76. package/dist/channel-BkI_5MRp.js +453 -0
  77. package/dist/channel-BnG-E5UX.js +595 -0
  78. package/dist/channel-CNZdJ8HY.js +1174 -0
  79. package/dist/channel-COcBdBbn.js +1100 -0
  80. package/dist/channel-CQI0hLJk.js +350 -0
  81. package/dist/channel-CkoM-a7d.js +226 -0
  82. package/dist/channel-CrHTdcH4.js +840 -0
  83. package/dist/channel-DvgX6dVj.js +1320 -0
  84. package/dist/channel-HtE-iRkv.js +491 -0
  85. package/dist/channel-OequV7Gf.js +1802 -0
  86. package/dist/channel-core-ChdqmAmk.js +5 -0
  87. package/dist/channel-inbound-Q2rVZZUs.js +31 -0
  88. package/dist/channel-plugin-runtime-DaijXHro.js +771 -0
  89. package/dist/channel-runtime-y4XUEoQY.js +425 -0
  90. package/dist/channel.runtime-BrEbVLLQ.js +576 -0
  91. package/dist/channel.runtime-C9UaDpbO.js +2364 -0
  92. package/dist/channel.runtime-Ccnjrmpx.js +109 -0
  93. package/dist/channel.runtime-CerUOlEZ.js +430 -0
  94. package/dist/channel.runtime-Du87a5jR.js +89 -0
  95. package/dist/channel.runtime-FklQos16.js +4 -0
  96. package/dist/channel.runtime-pynPO2Q-.js +34702 -0
  97. package/dist/channel.runtime.js +1 -1
  98. package/dist/channel.setup-D2BshGlh.js +10 -0
  99. package/dist/channels-DXbWBAhP.js +733 -0
  100. package/dist/channels-cli-DowVHylc.js +268 -0
  101. package/dist/chat-BMLW9p0d.js +2830 -0
  102. package/dist/clawbot-cli-DYF742Fr.js +9 -0
  103. package/dist/cli/daemon-cli.js +3 -3
  104. package/dist/cli-BebcHCJY.js +219 -0
  105. package/dist/cli-BnQ5RUbX.js +2 -0
  106. package/dist/cli-CsJTitwJ.js +72 -0
  107. package/dist/cli-D1z_Lra2.js +2 -0
  108. package/dist/cli-runner-DCfEJ3Dl.js +286 -0
  109. package/dist/cli-runner.runtime-1YoJduVc.js +3 -0
  110. package/dist/cli-runner.runtime-DaIWshs8.js +4 -0
  111. package/dist/cli-runner.runtime.js +1 -1
  112. package/dist/cli-startup-metadata.json +2 -2
  113. package/dist/cli.runtime-0QJWPe0Y.js +1261 -0
  114. package/dist/cli.runtime.js +1 -1
  115. package/dist/client-BR4n6hNI.js +713 -0
  116. package/dist/client-hrT_8w_f.js +138 -0
  117. package/dist/command-auth-BI6iswCp.js +76 -0
  118. package/dist/command-config-resolution-BvDykKQ0.js +23 -0
  119. package/dist/command-config-resolution-CJz3dmjF.js +2 -0
  120. package/dist/command-config-resolution.runtime-C1xIzrMA.js +2 -0
  121. package/dist/command-config-resolution.runtime.js +1 -1
  122. package/dist/command-registry-BQh49BOI.js +9 -0
  123. package/dist/command-registry-COW3Dwow.js +4 -0
  124. package/dist/command-registry-core-Bq5tHbQ5.js +106 -0
  125. package/dist/command-secret-gateway-CWH-56qF.js +528 -0
  126. package/dist/command-status.runtime-BUceIW-k.js +87 -0
  127. package/dist/command-status.runtime.js +1 -1
  128. package/dist/commands-acp-CDM0_szW.js +77 -0
  129. package/dist/commands-compact.runtime-BpuJhNyp.js +10 -0
  130. package/dist/commands-compact.runtime.js +1 -1
  131. package/dist/commands-handlers.runtime-DikW0yB0.js +4597 -0
  132. package/dist/commands-handlers.runtime.js +1 -1
  133. package/dist/commands-status-DgbzuFLf.js +16 -0
  134. package/dist/commands-status.runtime-BtoVY07x.js +3 -0
  135. package/dist/commands-status.runtime.js +1 -1
  136. package/dist/commands-subagents-control.runtime-B1MwVPHf.js +2 -0
  137. package/dist/commands-subagents-control.runtime-CPSMKJqB.js +3 -0
  138. package/dist/commands-subagents-control.runtime.js +1 -1
  139. package/dist/commands-system-prompt-DNA0qsTv.js +2 -0
  140. package/dist/commands-system-prompt-DdoBQ8ad.js +158 -0
  141. package/dist/commands.runtime-B8F59wvr.js +166 -0
  142. package/dist/commands.runtime.js +1 -1
  143. package/dist/compact-DevuFvwc.js +1118 -0
  144. package/dist/compact.runtime-DFxdJbZX.js +12 -0
  145. package/dist/compact.runtime.js +1 -1
  146. package/dist/completion-cli-94LY3Cno.js +328 -0
  147. package/dist/config-cli-3wKyVoWG.js +1078 -0
  148. package/dist/config-x0GQmd_p.js +252 -0
  149. package/dist/configure-DXBHXi9E.js +1252 -0
  150. package/dist/configure-iqDkqwpX.js +2 -0
  151. package/dist/connect-options-pZ4TVfhD.js +699 -0
  152. package/dist/control-auth-C0_VWbFV.js +125 -0
  153. package/dist/control-service-DKz9pgNJ.js +156 -0
  154. package/dist/conversation-id-C1ZMSaUv.js +235 -0
  155. package/dist/conversation-id-Cn8LoNiS.js +38 -0
  156. package/dist/conversation-runtime-PeJkl-ts.js +31 -0
  157. package/dist/core-BXR05azh.js +275 -0
  158. package/dist/cron-cli-C9SgQQXV.js +713 -0
  159. package/dist/daemon-cli-CJ8VUS9L.js +12 -0
  160. package/dist/dashboard-B7cbYfiK.js +81 -0
  161. package/dist/dashboard-SJJ1gpY7.js +2 -0
  162. package/dist/delegate-Bb6bHoIc.js +64 -0
  163. package/dist/detached-task-runtime-DUb2_Az9.js +73 -0
  164. package/dist/devices-cli-CZLTVAzc.js +498 -0
  165. package/dist/diagnostics-CElgAkJx.js +154 -0
  166. package/dist/direct-dm-B-q3BnYs.js +64 -0
  167. package/dist/dispatch-D6RvPlwP.js +1131 -0
  168. package/dist/dispatch-acp-Bit9gfDS.js +981 -0
  169. package/dist/dispatch-acp-manager.runtime-BDYoaEzk.js +3 -0
  170. package/dist/dispatch-acp-manager.runtime.js +1 -1
  171. package/dist/dispatch-acp.runtime-9yBydATu.js +19 -0
  172. package/dist/dispatch-acp.runtime.js +1 -1
  173. package/dist/doctor-device-pairing-CALw5gAh.js +307 -0
  174. package/dist/doctor-gateway-daemon-flow-DH90Xuwv.js +250 -0
  175. package/dist/doctor-gateway-health-DLTQr7oR.js +63 -0
  176. package/dist/doctor-health-UickjAEG.js +59 -0
  177. package/dist/doctor-health-contributions-CT2_osp-.js +493 -0
  178. package/dist/doctor-prompter-CmsL_aNs.js +56 -0
  179. package/dist/doctor-workspace-status-DrfJ_CMh.js +75 -0
  180. package/dist/dreaming-BjlelMwS.js +1574 -0
  181. package/dist/dreaming-narrative-Cioh4-iE.js +595 -0
  182. package/dist/embedded-gateway-stub.runtime-D3axE_Gz.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-C61OIas5.js +498 -0
  186. package/dist/execute.runtime-Dh2PQVjB.js +1363 -0
  187. package/dist/execute.runtime.js +1 -1
  188. package/dist/extensionAPI.js +1 -1
  189. package/dist/extensions/active-memory/index.js +1 -1
  190. package/dist/extensions/bluebubbles/api.js +3 -3
  191. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  192. package/dist/extensions/browser/browser-bridge.js +1 -1
  193. package/dist/extensions/browser/browser-config.js +4 -4
  194. package/dist/extensions/browser/browser-control-auth.js +2 -2
  195. package/dist/extensions/browser/browser-doctor.js +2 -2
  196. package/dist/extensions/browser/browser-maintenance.js +2 -2
  197. package/dist/extensions/browser/browser-profiles.js +2 -2
  198. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  199. package/dist/extensions/browser/index.js +1 -1
  200. package/dist/extensions/browser/plugin-registration.js +1 -1
  201. package/dist/extensions/browser/register.runtime.js +3 -3
  202. package/dist/extensions/browser/runtime-api.js +11 -11
  203. package/dist/extensions/browser/test-support.js +1 -1
  204. package/dist/extensions/device-pair/api.js +1 -1
  205. package/dist/extensions/device-pair/index.js +3 -3
  206. package/dist/extensions/device-pair/notify.js +1 -1
  207. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  208. package/dist/extensions/google-meet/index.js +2 -2
  209. package/dist/extensions/imessage/api.js +3 -3
  210. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  211. package/dist/extensions/imessage/runtime-api.js +3 -3
  212. package/dist/extensions/irc/api.js +2 -2
  213. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  214. package/dist/extensions/line/api.js +2 -2
  215. package/dist/extensions/line/channel-plugin-api.js +1 -1
  216. package/dist/extensions/line/contract-api.js +1 -1
  217. package/dist/extensions/line/runtime-api.js +4 -4
  218. package/dist/extensions/line/setup-api.js +1 -1
  219. package/dist/extensions/llm-task/index.js +2 -2
  220. package/dist/extensions/lobster/index.js +3 -3
  221. package/dist/extensions/lobster/runtime-api.js +1 -1
  222. package/dist/extensions/mattermost/api.js +1 -1
  223. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  224. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  225. package/dist/extensions/mattermost/policy-api.js +1 -1
  226. package/dist/extensions/mattermost/runtime-api.js +4 -4
  227. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  228. package/dist/extensions/memory-core/api.js +1 -1
  229. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  230. package/dist/extensions/memory-core/index.js +3 -3
  231. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  232. package/dist/extensions/msteams/api.js +1 -1
  233. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  234. package/dist/extensions/msteams/runtime-api.js +3 -3
  235. package/dist/extensions/msteams/test-api.js +1 -1
  236. package/dist/extensions/nextcloud-talk/api.js +1 -1
  237. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  238. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  239. package/dist/extensions/openshell/index.js +2 -2
  240. package/dist/extensions/signal/api.js +6 -6
  241. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  242. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  243. package/dist/extensions/signal/runtime-api.js +7 -7
  244. package/dist/extensions/skill-workshop/api.js +1 -1
  245. package/dist/extensions/skill-workshop/index.js +1 -1
  246. package/dist/extensions/synology-chat/api.js +1 -1
  247. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  248. package/dist/extensions/tlon/api.js +2 -2
  249. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  250. package/dist/extensions/tlon/runtime-api.js +1 -1
  251. package/dist/extensions/tlon/test-api.js +1 -1
  252. package/dist/extensions/twitch/api.js +1 -1
  253. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  254. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  255. package/dist/extensions/zalo/api.js +3 -3
  256. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  257. package/dist/extensions/zalo/runtime-api.js +2 -2
  258. package/dist/extensions/zalo/setup-api.js +2 -2
  259. package/dist/extensions/zalouser/api.js +3 -3
  260. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  261. package/dist/extensions/zalouser/runtime-api.js +6 -6
  262. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  263. package/dist/extensions/zalouser/test-api.js +1 -1
  264. package/dist/fallbacks-7WaQrL4w.js +2 -0
  265. package/dist/fallbacks-D030WgeJ.js +31 -0
  266. package/dist/fallbacks-shared-D0Irg6Dc.js +111 -0
  267. package/dist/gateway-Drmf7aeu.js +115 -0
  268. package/dist/gateway-cli-DzsJzCar.js +1283 -0
  269. package/dist/gateway-rpc-ByhpcN5x.js +14 -0
  270. package/dist/gateway-rpc.runtime-4zXMZEZA.js +23 -0
  271. package/dist/gateway-rpc.runtime.js +1 -1
  272. package/dist/gateway-runtime-BGIrLVc5.js +15 -0
  273. package/dist/gateway-status-Dcpg0Z1K.js +584 -0
  274. package/dist/genesis-tools-ZNGlG9Ij.js +9144 -0
  275. package/dist/genesis-tools.runtime-CSl_w_fx.js +2 -0
  276. package/dist/genesis-tools.runtime.js +1 -1
  277. package/dist/get-reply-BG-YgQgk.js +3879 -0
  278. package/dist/get-reply-from-config.runtime-CTTbEqgi.js +2 -0
  279. package/dist/get-reply-from-config.runtime.js +1 -1
  280. package/dist/graph-users-DBkBwndc.js +1337 -0
  281. package/dist/health-DP9-SUDF.js +3 -0
  282. package/dist/health-Dn4lrkX0.js +469 -0
  283. package/dist/health-route-BOUp8_1m.js +2 -0
  284. package/dist/health-route-BhuLVeKt.js +41 -0
  285. package/dist/heartbeat-runner-B5ZUS0Zj.js +1292 -0
  286. package/dist/heartbeat-runner-BIlNfweM.js +5 -0
  287. package/dist/heartbeat-runner.runtime-YmoU6ZZ3.js +4 -0
  288. package/dist/heartbeat-runner.runtime.js +1 -1
  289. package/dist/hooks-cli-hN5FtPX4.js +433 -0
  290. package/dist/image-fallbacks-Cq3R8m7Y.js +2 -0
  291. package/dist/image-fallbacks-Dd4BCf1D.js +31 -0
  292. package/dist/inbound-reply-dispatch-Be4j__jx.js +73 -0
  293. package/dist/index.js +2 -2
  294. package/dist/infra-runtime-dEG-SNc-.js +39 -0
  295. package/dist/init-C1wrook_.js +59 -0
  296. package/dist/library-B6SYgaHj.js +45 -0
  297. package/dist/lifecycle-BJuODKPo.js +229 -0
  298. package/dist/lifecycle-Dhj0KywB.js +571 -0
  299. package/dist/lifecycle.runtime-CwSjoTkX.js +2 -0
  300. package/dist/lifecycle.runtime.js +1 -1
  301. package/dist/list-Bj2cpmBs.js +1212 -0
  302. package/dist/list-CBe1cOSo.js +2 -0
  303. package/dist/list-CktR5l_P.js +2 -0
  304. package/dist/list-ydeAMfpS.js +131 -0
  305. package/dist/list.probe-0SQPzjrW.js +419 -0
  306. package/dist/llm-slug-generator-CyQx7U_Q.js +79 -0
  307. package/dist/llm-slug-generator.js +1 -1
  308. package/dist/load-config-BHd00lHp.js +35 -0
  309. package/dist/local-dispatch.runtime-CqTNOXfw.js +8 -0
  310. package/dist/local-dispatch.runtime.js +1 -1
  311. package/dist/logs-cli-BWOEA5qi.js +265 -0
  312. package/dist/logs-cli.runtime-DSIEK1BE.js +2 -0
  313. package/dist/logs-cli.runtime.js +1 -1
  314. package/dist/main-session-restart-recovery-Cfc3B2Uj.js +206 -0
  315. package/dist/managed-image-attachments-BZbPdPC8.js +2 -0
  316. package/dist/managed-image-attachments-CxLohd8A.js +635 -0
  317. package/dist/manager-Cg7vl9NG.js +2057 -0
  318. package/dist/manager-CiI4zE-D.js +2 -0
  319. package/dist/markdown-to-line-B8FYeJdD.js +790 -0
  320. package/dist/mcp/plugin-tools-serve.js +1 -1
  321. package/dist/mcp-cli-BS4_9Zoo.js +725 -0
  322. package/dist/mcp-http-wF9LvDEz.js +529 -0
  323. package/dist/memory-core-host-runtime-cli-06ivr1qR.js +9 -0
  324. package/dist/message-BzaLYgSG.js +232 -0
  325. package/dist/message-action-runner-BazMarN6.js +1407 -0
  326. package/dist/message-action-runner-Bq7rUhnL.js +2 -0
  327. package/dist/message-actions-DcnuU8Sm.js +143 -0
  328. package/dist/message.gateway.runtime-BCFg5opz.js +2 -0
  329. package/dist/message.gateway.runtime.js +1 -1
  330. package/dist/models-auth-status-6d3I6qIv.js +201 -0
  331. package/dist/models-cli-DZPcli0C.js +219 -0
  332. package/dist/monitor-BYFZsGcy.js +2 -0
  333. package/dist/monitor-C2nxTIum.js +1459 -0
  334. package/dist/monitor-CD5DZfT0.js +1237 -0
  335. package/dist/monitor-C_5rnpcO.js +1661 -0
  336. package/dist/monitor-CxPzN2U-.js +671 -0
  337. package/dist/monitor-G_A80TYD.js +788 -0
  338. package/dist/monitor-auth-Bjr6pzE-.js +207 -0
  339. package/dist/monitor-processing-Du6MiEEU.js +1974 -0
  340. package/dist/monitor.runtime-BHjQO73F.js +2 -0
  341. package/dist/monitor.runtime.js +1 -1
  342. package/dist/monitor.webhook-BU61VqG-.js +180 -0
  343. package/dist/msteams-HKEY9u2h.js +35 -0
  344. package/dist/native-hook-relay-DcIfpN38.js +519 -0
  345. package/dist/nextcloud-talk-BAwtzO7T.js +17 -0
  346. package/dist/node-cli-BM5NVTG7.js +2506 -0
  347. package/dist/nodes-cli-BAuBgmem.js +1046 -0
  348. package/dist/nodes-utils-Bs6GofNl.js +84 -0
  349. package/dist/nodes.helpers-9SdaPWam.js +34 -0
  350. package/dist/notify-bMIvLU57.js +315 -0
  351. package/dist/onboard-DZRCsQKI.js +70 -0
  352. package/dist/onboard-WrvK1ncB.js +2 -0
  353. package/dist/onboard-helpers-iMWEmZ9M.js +204 -0
  354. package/dist/onboard-helpers-nf1FCDx1.js +6 -0
  355. package/dist/onboard-interactive-BqvHTpjq.js +24 -0
  356. package/dist/onboard-non-interactive-QqRYgGmh.js +548 -0
  357. package/dist/onboard-remote-Btb7Elo9.js +2 -0
  358. package/dist/onboard-remote-YLLAXD5a.js +193 -0
  359. package/dist/onboard-skills-CbVEWgXS.js +134 -0
  360. package/dist/onboard-skills-Dlrodw-j.js +2 -0
  361. package/dist/openai-http-D9C2CUw5.js +500 -0
  362. package/dist/openresponses-http-Cm1pNnoN.js +1128 -0
  363. package/dist/operator-approvals-client-Crk-kZWE.js +68 -0
  364. package/dist/outbound.runtime-EJrjRipL.js +2 -0
  365. package/dist/outbound.runtime.js +1 -1
  366. package/dist/pair-command-approve-BEGwU4IB.js +44 -0
  367. package/dist/persistent-bindings.lifecycle-DQF-e-Qa.js +85 -0
  368. package/dist/persistent-bindings.lifecycle-lkGrqLnW.js +2 -0
  369. package/dist/pi-embedded-BDlMkZq9.js +2905 -0
  370. package/dist/pi-embedded-Duzz1mtI.js +4 -0
  371. package/dist/pi-embedded.runtime-Ct_Aa3c5.js +4 -0
  372. package/dist/pi-embedded.runtime.js +1 -1
  373. package/dist/pi-tool-definition-adapter-CZw0LtV5.js +229 -0
  374. package/dist/pi-tools-C6B-SOzB.js +1057 -0
  375. package/dist/pi-tools.before-tool-call-9joq1aHl.js +2 -0
  376. package/dist/pi-tools.before-tool-call-DNnie5TY.js +433 -0
  377. package/dist/plugin-BCPNJxM9.js +12195 -0
  378. package/dist/plugin-enabled-BjLKAsAC.js +140 -0
  379. package/dist/plugin-registration-BId8vb01.js +23 -0
  380. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  381. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  382. package/dist/plugin-sdk/acp-runtime.js +2 -2
  383. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  384. package/dist/plugin-sdk/agent-harness.js +6 -6
  385. package/dist/plugin-sdk/agent-runtime.js +2 -2
  386. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  387. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  388. package/dist/plugin-sdk/approval-runtime.js +1 -1
  389. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  390. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  391. package/dist/plugin-sdk/browser-support.js +7 -7
  392. package/dist/plugin-sdk/channel-core.js +2 -2
  393. package/dist/plugin-sdk/channel-inbound.js +2 -2
  394. package/dist/plugin-sdk/command-auth.js +1 -1
  395. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  396. package/dist/plugin-sdk/compat.js +1 -1
  397. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  398. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  399. package/dist/plugin-sdk/core.js +2 -2
  400. package/dist/plugin-sdk/direct-dm.js +1 -1
  401. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  402. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  403. package/dist/plugin-sdk/index.js +1 -1
  404. package/dist/plugin-sdk/infra-runtime.js +2 -2
  405. package/dist/plugin-sdk/irc.js +2 -2
  406. package/dist/plugin-sdk/matrix.js +1 -1
  407. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  408. package/dist/plugin-sdk/memory-core.js +2 -2
  409. package/dist/plugin-sdk/msteams.js +2 -2
  410. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  411. package/dist/plugin-sdk/nostr.js +1 -1
  412. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  413. package/dist/plugin-sdk/reply-runtime.js +4 -4
  414. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  415. package/dist/plugin-sdk/runtime.js +2 -2
  416. package/dist/plugin-sdk/session-visibility.js +1 -1
  417. package/dist/plugin-sdk/testing.js +4 -4
  418. package/dist/plugin-sdk/tlon.js +1 -1
  419. package/dist/plugin-sdk/zalo.js +1 -1
  420. package/dist/plugin-sdk/zalouser.js +1 -1
  421. package/dist/plugin-service-q43trexG.js +2892 -0
  422. package/dist/plugins/runtime/index.js +1 -1
  423. package/dist/policy-B4NUBI6t.js +328 -0
  424. package/dist/postinstall-inventory.json +417 -417
  425. package/dist/prepare.runtime-_zemfjv3.js +815 -0
  426. package/dist/prepare.runtime.js +1 -1
  427. package/dist/probe-BY3B9tTH.js +2205 -0
  428. package/dist/probe-BvnxVXPF.js +2 -0
  429. package/dist/probe-BxfJkCo7.js +1443 -0
  430. package/dist/probe-CVdSkKEj.js +241 -0
  431. package/dist/probe-HJKXZScl.js +74 -0
  432. package/dist/probe-cSkWLlnk.js +45 -0
  433. package/dist/probe-mvSMIO0q.js +2 -0
  434. package/dist/program-B59QlcJQ.js +111 -0
  435. package/dist/prompt-select-styled-4Jq2F-H9.js +20 -0
  436. package/dist/protocol-AGt54mci.js +2335 -0
  437. package/dist/provider-dispatcher-CP48ghhH.js +2 -0
  438. package/dist/provider-dispatcher-DEGzYrP8.js +22 -0
  439. package/dist/qr-cli-l0w87b13.js +349 -0
  440. package/dist/qr-cli-rJZ8om76.js +2 -0
  441. package/dist/reaction-runtime-api-Bkt3VyFC.js +116 -0
  442. package/dist/reactions-m2szYDeb.js +998 -0
  443. package/dist/register-service-commands-BW-5D4CL.js +71 -0
  444. package/dist/register.agent-0oONdLoj.js +248 -0
  445. package/dist/register.configure-DJgbhQEd.js +15 -0
  446. package/dist/register.maintenance-qDzsg7Rx.js +363 -0
  447. package/dist/register.message-D3IcSeh2.js +329 -0
  448. package/dist/register.onboard-712D2YIY.js +88 -0
  449. package/dist/register.runtime-9LgalpKP.js +81 -0
  450. package/dist/register.runtime.js +1 -1
  451. package/dist/register.setup-olmzCf4M.js +150 -0
  452. package/dist/register.status-health-sessions-BcSscPyw.js +1215 -0
  453. package/dist/register.subclis-Cb_7jF2M.js +29 -0
  454. package/dist/register.subclis-DohysWLE.js +3 -0
  455. package/dist/register.subclis-core-Db1skJ4w.js +249 -0
  456. package/dist/register.wallet-WGlu7P0C.js +271 -0
  457. package/dist/reply-dispatch-runtime-C6kPvDIT.js +13 -0
  458. package/dist/reply-runtime-m8R8imuO.js +11 -0
  459. package/dist/reply.runtime-yz20DuV3.js +2 -0
  460. package/dist/reply.runtime.js +1 -1
  461. package/dist/restart-health-B3BG9cWC.js +2 -0
  462. package/dist/restart-health-Blxs74k_.js +202 -0
  463. package/dist/root-help-CtdC-lhj.js +44 -0
  464. package/dist/routes-DlHk_d4H.js +2 -0
  465. package/dist/routes-vuPJqxDc.js +3341 -0
  466. package/dist/rpc-CvdOvi6M.js +61 -0
  467. package/dist/rpc.runtime-BTkO-5N6.js +21 -0
  468. package/dist/rpc.runtime.js +1 -1
  469. package/dist/run-delivery.runtime-Bu0IyFs-.js +530 -0
  470. package/dist/run-delivery.runtime.js +1 -1
  471. package/dist/run-embedded.runtime-Bptomyr6.js +4 -0
  472. package/dist/run-embedded.runtime.js +1 -1
  473. package/dist/run-execution-cli.runtime-DVoDazG0.js +4 -0
  474. package/dist/run-execution-cli.runtime.js +1 -1
  475. package/dist/run-executor.runtime-LRWKlZ-B.js +277 -0
  476. package/dist/run-executor.runtime.js +1 -1
  477. package/dist/run-main-C-5waIfA.js +567 -0
  478. package/dist/run-subagent-registry.runtime-eNmO4Ulf.js +2 -0
  479. package/dist/run-subagent-registry.runtime.js +1 -1
  480. package/dist/run-wait-CYFrtm-o.js +135 -0
  481. package/dist/runtime-BRPRR2hE.js +973 -0
  482. package/dist/runtime-CokulBmy.js +9 -0
  483. package/dist/runtime-api-BJ2r-OR5.js +14 -0
  484. package/dist/runtime-api-BfGhe369.js +9 -0
  485. package/dist/runtime-api-Bfjma1I2.js +9 -0
  486. package/dist/runtime-api-CxY0DKnr.js +4 -0
  487. package/dist/runtime-embedded-pi.runtime-BvnxDutF.js +2 -0
  488. package/dist/runtime-embedded-pi.runtime.js +1 -1
  489. package/dist/runtime-internal-BIVfP__L.js +2 -0
  490. package/dist/runtime-options-BljbnMxi.js +275 -0
  491. package/dist/runtime-schema-Dyv3hS1d.js +27938 -0
  492. package/dist/scan-D9X5Lj0l.js +523 -0
  493. package/dist/scan-M3OixEI7.js +2 -0
  494. package/dist/secrets-cli-fpxI67tT.js +2101 -0
  495. package/dist/security-cli-B9FOJsn-.js +486 -0
  496. package/dist/selection-CFlY2XMr.js +2 -0
  497. package/dist/selection-CdRMYsTR.js +7736 -0
  498. package/dist/send-BHKn9mJM.js +156 -0
  499. package/dist/send-CSAuufSI.js +102 -0
  500. package/dist/send.runtime-Csjbw0LF.js +2 -0
  501. package/dist/send.runtime.js +1 -1
  502. package/dist/server-CtGKkNXK.js +77 -0
  503. package/dist/server-QZSxYkIl.js +13 -0
  504. package/dist/server-context-CCzwJPYE.js +847 -0
  505. package/dist/server-context-SQimgHbw.js +2 -0
  506. package/dist/server-node-events-Bw07_egU.js +481 -0
  507. package/dist/server-plugin-bootstrap-BxVzrft3.js +2 -0
  508. package/dist/server-plugin-bootstrap-Ma9J_GSY.js +11652 -0
  509. package/dist/server-restart-sentinel-n_4jiXSF.js +697 -0
  510. package/dist/server.impl-CY_ZY-Mq.js +12822 -0
  511. package/dist/service-CPRBqblN.js +1446 -0
  512. package/dist/session-kill-http-bilLl8tM.js +110 -0
  513. package/dist/session-reset-service-DHbmMELT.js +471 -0
  514. package/dist/session-route-CHPZxwZH.js +93 -0
  515. package/dist/session-status.runtime-Cco6tPQ0.js +2 -0
  516. package/dist/session-status.runtime.js +1 -1
  517. package/dist/session-subagent-reactivation.runtime-D8SYYjgF.js +2 -0
  518. package/dist/session-subagent-reactivation.runtime.js +1 -1
  519. package/dist/session-tab-registry-9W3qSiwY.js +581 -0
  520. package/dist/session-visibility-Csvz8y2g.js +147 -0
  521. package/dist/sessions-helpers-DJtsPRok.js +304 -0
  522. package/dist/sessions-history-http-BwN8qdVu.js +383 -0
  523. package/dist/sessions-patch-Cn6ICCbl.js +309 -0
  524. package/dist/sessions-resolve-DkokaXLV.js +174 -0
  525. package/dist/sessions.runtime-CUhGDDdQ.js +2 -0
  526. package/dist/sessions.runtime.js +1 -1
  527. package/dist/setup-CXrByuF0.js +505 -0
  528. package/dist/setup-api-CAUnAQYK.js +29 -0
  529. package/dist/setup-core-0kUhQgXj.js +171 -0
  530. package/dist/setup-core-CgIvNnqV.js +176 -0
  531. package/dist/setup-surface-BICUCTSY.js +219 -0
  532. package/dist/setup-surface-CWN6fRnj.js +286 -0
  533. package/dist/setup-surface-DAO84q-l.js +403 -0
  534. package/dist/setup.finalize-Cz-xAyXq.js +547 -0
  535. package/dist/setup.gateway-config-B_6xO6qg.js +250 -0
  536. package/dist/shared-54WHS6Zf.js +198 -0
  537. package/dist/shared-BM7A3tRo.js +121 -0
  538. package/dist/shared-ZX79gVvR.js +76 -0
  539. package/dist/slash-state-D9XJzIhC.js +1911 -0
  540. package/dist/src-CeLenBVS.js +3974 -0
  541. package/dist/startup-context-ExpfHx39.js +312 -0
  542. package/dist/status-B3pfZ-ob.js +2 -0
  543. package/dist/status-BxtYUkFv.js +209 -0
  544. package/dist/status-CBKaYlp2.js +397 -0
  545. package/dist/status-DXMGfco1.js +3 -0
  546. package/dist/status-Dveq2FJA.js +190 -0
  547. package/dist/status-all-C0Rv7_MK.js +498 -0
  548. package/dist/status-json-command-FP5kOrjW.js +84 -0
  549. package/dist/status-json-jAko1YQ3.js +14 -0
  550. package/dist/status-ooCzELGj.js +2 -0
  551. package/dist/status-runtime-shared-t7ZNH_at.js +257 -0
  552. package/dist/status-subagents.runtime-B0-FFd7k.js +18 -0
  553. package/dist/status-subagents.runtime.js +1 -1
  554. package/dist/status-text-D5Wb2Eyv.js +237 -0
  555. package/dist/status.gateway-connection.runtime-DX3GFQOy.js +2 -0
  556. package/dist/status.gateway-connection.runtime.js +1 -1
  557. package/dist/status.gather-BLaJs7JK.js +292 -0
  558. package/dist/status.gather-DXcgE-uZ.js +2 -0
  559. package/dist/status.runtime-BW8lvcAk.js +2 -0
  560. package/dist/status.runtime.js +1 -1
  561. package/dist/status.scan-CqSxwChE.js +65 -0
  562. package/dist/status.scan-overview-C50E8dW7.js +379 -0
  563. package/dist/status.scan.fast-json-DZD93o5C.js +132 -0
  564. package/dist/status.scan.fast-json-aLbUp_Zj.js +2 -0
  565. package/dist/status.summary-CSXp0VuE.js +2 -0
  566. package/dist/status.summary-CZhlDozR.js +214 -0
  567. package/dist/subagent-announce-DQNhTREe.js +351 -0
  568. package/dist/subagent-announce-delivery-DzexQBXL.js +726 -0
  569. package/dist/subagent-announce-output-DHdUIOLb.js +364 -0
  570. package/dist/subagent-control-BIHPVfEC.js +506 -0
  571. package/dist/subagent-followup.runtime-B2vIi_N7.js +68 -0
  572. package/dist/subagent-followup.runtime.js +1 -1
  573. package/dist/subagent-orphan-recovery-acE2Akzk.js +305 -0
  574. package/dist/subagent-registry-DscgS64s.js +1753 -0
  575. package/dist/subagent-registry-VBEsKIg8.js +3 -0
  576. package/dist/subagent-registry.runtime.js +1 -1
  577. package/dist/subagent-spawn-ClpDxVim.js +1005 -0
  578. package/dist/system-cli-Cwoirti-.js +59 -0
  579. package/dist/targets-Du7kf5pU.js +67 -0
  580. package/dist/task-executor-Cex7gyKp.js +360 -0
  581. package/dist/task-owner-access-CfZCzFm8.js +74 -0
  582. package/dist/task-registry-delivery-runtime-7UMu_ADx.js +3 -0
  583. package/dist/task-registry-delivery-runtime-anQhKoeF.js +2 -0
  584. package/dist/task-registry-dsUR7cO8.js +2366 -0
  585. package/dist/task-registry.maintenance-8t06izZG.js +416 -0
  586. package/dist/task-registry.maintenance-BKCkUElL.js +2 -0
  587. package/dist/telegram/token.js +1 -1
  588. package/dist/testing-XS9mU0gy.js +575 -0
  589. package/dist/text-report-CW3trTAs.js +587 -0
  590. package/dist/tool-resolution-CbhdQ1Hc.js +90 -0
  591. package/dist/tools-effective-inventory-C-fhTbL3.js +152 -0
  592. package/dist/tools-invoke-http-DwLDiTC-.js +206 -0
  593. package/dist/trash-BPfwuXw1.js +24 -0
  594. package/dist/tui-cli-CwcpeUI3.js +4575 -0
  595. package/dist/update-cli-C7wZCVxw.js +1759 -0
  596. package/dist/upgrade-I1DlWIOT.js +1226 -0
  597. package/dist/video-generation-task-status-BTNgjS3Y.js +163 -0
  598. package/dist/wait-for-idle-before-flush-jA-mGgw_.js +5986 -0
  599. package/dist/wizard-models-CJ9pSHsX.js +334 -0
  600. package/package.json +1 -1
  601. package/dist/abort-CFK2Nhip.js +0 -201
  602. package/dist/abort.runtime-BuAaxnKL.js +0 -2
  603. package/dist/accounts-CHbim_qS.js +0 -107
  604. package/dist/accounts-DtkNyn-Q.js +0 -2
  605. package/dist/accounts-J3zyVXXx.js +0 -104
  606. package/dist/acp-cli-C3I6FHf2.js +0 -2193
  607. package/dist/acp-spawn-D3xu_-rE.js +0 -1093
  608. package/dist/acp-spawn-vcfww9lP.js +0 -2
  609. package/dist/acp-stateful-target-driver-CiSxPJNY.js +0 -89
  610. package/dist/action-agents-CIlhSgnP.js +0 -67
  611. package/dist/action-focus-Cf5CQqOj.js +0 -132
  612. package/dist/action-help-B0yl4Pe2.js +0 -7
  613. package/dist/action-info-CFUHIn0u.js +0 -101
  614. package/dist/action-kill-C95CsdAp.js +0 -33
  615. package/dist/action-list-BX3RIjsZ.js +0 -21
  616. package/dist/action-log-BOalIOnb.js +0 -30
  617. package/dist/action-send-Bw-K12vK.js +0 -39
  618. package/dist/action-spawn-DSTqN3n1.js +0 -47
  619. package/dist/action-unfocus-BRGuE47t.js +0 -29
  620. package/dist/actions.runtime-5qLo-JvI.js +0 -5
  621. package/dist/actions.runtime-CB7fr1mE.js +0 -18
  622. package/dist/agent-4OUfop4W.js +0 -2
  623. package/dist/agent-command-9KZKjUCs.js +0 -874
  624. package/dist/agent-harness-runtime-Dn6m6FbT.js +0 -144
  625. package/dist/agent-runner-utils-I_WM4CKu.js +0 -239
  626. package/dist/agent-runner.runtime-CXepXPjv.js +0 -3455
  627. package/dist/agent-runtime-DPkZZoYt.js +0 -18
  628. package/dist/agents-3DAP4x-2.js +0 -954
  629. package/dist/agents-DkjDVIbt.js +0 -5
  630. package/dist/aliases-83bfbKwd.js +0 -96
  631. package/dist/aliases-CNWj4VYC.js +0 -2
  632. package/dist/api-BEjdCEtU.js +0 -5
  633. package/dist/api-CkjarVLC.js +0 -139
  634. package/dist/api-Dn4kHUcI.js +0 -3
  635. package/dist/approval-gateway-resolver-CC1SlTbX.js +0 -29
  636. package/dist/approval-gateway-runtime-d2TZtKpe.js +0 -2
  637. package/dist/approval-handler-runtime-COVHjwvD.js +0 -439
  638. package/dist/approval-native-runtime-BVIV224X.js +0 -729
  639. package/dist/attempt-execution.runtime-CszeM4rO.js +0 -509
  640. package/dist/attempt.prompt-helpers-CJwtdWVk.js +0 -221
  641. package/dist/attempt.tool-run-context-D3pOtNpQ.js +0 -933
  642. package/dist/audit-CI0PTe8o.js +0 -939
  643. package/dist/audit.runtime-CVT0pKNw.js +0 -7
  644. package/dist/auth-B6BvjceY.js +0 -383
  645. package/dist/auth-C24A8Bdb.js +0 -2
  646. package/dist/auth-order--2Z2RfgO.js +0 -2
  647. package/dist/auth-order-Cab5pbli.js +0 -96
  648. package/dist/bash-tools-D4Ow1Dnu.js +0 -3
  649. package/dist/bash-tools-N8ycn0zw.js +0 -2824
  650. package/dist/binding-routing-IdC_J5YZ.js +0 -85
  651. package/dist/binding-targets-BD3JnlsK.js +0 -121
  652. package/dist/bridge-server-DReQkRlc.js +0 -113
  653. package/dist/browser-control-auth-BDpXA4Fa.js +0 -2
  654. package/dist/browser-node-runtime-CUEWaMPj.js +0 -12
  655. package/dist/browser-profiles-CKoK0REq.js +0 -2
  656. package/dist/browser-runtime-DctmCqop.js +0 -387
  657. package/dist/browser-setup-tools-D_hWDm_d.js +0 -13
  658. package/dist/build-00dHETnB.js +0 -550
  659. package/dist/call-BEBMfrmf.js +0 -331
  660. package/dist/call-J1xym_da.js +0 -3
  661. package/dist/call.runtime-DpiL_m7V.js +0 -2
  662. package/dist/capability-cli-Dcgy6e0s.js +0 -1401
  663. package/dist/catchup-BIWAuu8n.js +0 -300
  664. package/dist/channel-1CgTIJaH.js +0 -595
  665. package/dist/channel-471U1pny.js +0 -1100
  666. package/dist/channel-B-pPhXQ4.js +0 -453
  667. package/dist/channel-BYutJYNS.js +0 -297
  668. package/dist/channel-C2g916cY.js +0 -491
  669. package/dist/channel-C5JVIEYG.js +0 -226
  670. package/dist/channel-C6PLBfBu.js +0 -1320
  671. package/dist/channel-DFhzKEOr.js +0 -1802
  672. package/dist/channel-DaaKYb-X.js +0 -350
  673. package/dist/channel-LS_UWVN6.js +0 -840
  674. package/dist/channel-UwrUqsgJ.js +0 -1174
  675. package/dist/channel-core-u67ncUuJ.js +0 -5
  676. package/dist/channel-inbound-CZj1nuJ5.js +0 -31
  677. package/dist/channel-plugin-runtime-DbjaJmEm.js +0 -771
  678. package/dist/channel-runtime-o1M6R948.js +0 -425
  679. package/dist/channel.runtime-BBqx6vVj.js +0 -430
  680. package/dist/channel.runtime-ChXnhf2V.js +0 -2364
  681. package/dist/channel.runtime-CiZ5wg5-.js +0 -89
  682. package/dist/channel.runtime-DOIkahiZ.js +0 -109
  683. package/dist/channel.runtime-DUe0Bv9U.js +0 -4
  684. package/dist/channel.runtime-DwICmfFu.js +0 -576
  685. package/dist/channel.runtime-EBX0cQWh.js +0 -34702
  686. package/dist/channel.setup-DtHhxlgN.js +0 -10
  687. package/dist/channels-ChLA3Mda.js +0 -733
  688. package/dist/channels-cli-BqXA071P.js +0 -268
  689. package/dist/chat-B0vA8pOW.js +0 -2830
  690. package/dist/clawbot-cli-BkpkeI6b.js +0 -9
  691. package/dist/cli-DLD4HPRd.js +0 -72
  692. package/dist/cli-ME5Ufp83.js +0 -219
  693. package/dist/cli-ZcCIz0qL.js +0 -2
  694. package/dist/cli-eAgnabrD.js +0 -2
  695. package/dist/cli-runner-BBu8Rh95.js +0 -286
  696. package/dist/cli-runner.runtime-VDLuf97Y.js +0 -4
  697. package/dist/cli-runner.runtime-jK2bwGDS.js +0 -3
  698. package/dist/cli.runtime-BquKQJFI.js +0 -1261
  699. package/dist/client-CDLetywx.js +0 -713
  700. package/dist/client-CvwHGzRM.js +0 -138
  701. package/dist/command-auth-BavEEGzq.js +0 -76
  702. package/dist/command-config-resolution-CgnDlwiW.js +0 -2
  703. package/dist/command-config-resolution-M1sLQtCC.js +0 -23
  704. package/dist/command-config-resolution.runtime-BjVMJcFa.js +0 -2
  705. package/dist/command-registry-BuZbFhmG.js +0 -4
  706. package/dist/command-registry-DugzbSDU.js +0 -9
  707. package/dist/command-registry-core-BF-C6kEk.js +0 -106
  708. package/dist/command-secret-gateway-DJUQmmqr.js +0 -528
  709. package/dist/command-status.runtime-Ws0MIfwY.js +0 -87
  710. package/dist/commands-acp-COM5kx3I.js +0 -77
  711. package/dist/commands-compact.runtime-ZKLATU16.js +0 -10
  712. package/dist/commands-handlers.runtime-BonxJuOb.js +0 -4597
  713. package/dist/commands-status-fYAnTzxd.js +0 -16
  714. package/dist/commands-status.runtime-NM9_L71Y.js +0 -3
  715. package/dist/commands-subagents-control.runtime-C7DNjqgK.js +0 -2
  716. package/dist/commands-subagents-control.runtime-DrvwTszJ.js +0 -3
  717. package/dist/commands-system-prompt-CF7mFq3s.js +0 -158
  718. package/dist/commands-system-prompt-DAynyctS.js +0 -2
  719. package/dist/commands.runtime-CdVSeunO.js +0 -166
  720. package/dist/compact-CQZ7fcfj.js +0 -1118
  721. package/dist/compact.runtime-QhgOP3dH.js +0 -12
  722. package/dist/completion-cli-CkA79Zyd.js +0 -328
  723. package/dist/config-B0nwYGOq.js +0 -252
  724. package/dist/config-cli-DQy3aiyu.js +0 -1078
  725. package/dist/configure-D9182v2z.js +0 -1252
  726. package/dist/configure-DFK_gG4o.js +0 -2
  727. package/dist/connect-options-ClIicH76.js +0 -699
  728. package/dist/control-auth-C9KfGTux.js +0 -125
  729. package/dist/control-service-BNB3JMwD.js +0 -156
  730. package/dist/conversation-id-BfPCu1Wm.js +0 -235
  731. package/dist/conversation-id-Btjce0dU.js +0 -38
  732. package/dist/conversation-runtime-nC5e5AUD.js +0 -31
  733. package/dist/core-cKYNneLh.js +0 -275
  734. package/dist/cron-cli-B61Ct4d1.js +0 -713
  735. package/dist/daemon-cli-BDUJ0J9c.js +0 -12
  736. package/dist/dashboard-BY0SQ1Xk.js +0 -81
  737. package/dist/dashboard-BfFLhcnp.js +0 -2
  738. package/dist/delegate-C5l7xFfl.js +0 -64
  739. package/dist/detached-task-runtime-jUnU2hI1.js +0 -73
  740. package/dist/devices-cli-C2Yk5InD.js +0 -498
  741. package/dist/diagnostics-vLNGss4R.js +0 -154
  742. package/dist/direct-dm-CY7NvWjO.js +0 -64
  743. package/dist/dispatch-acp-D7us-JIr.js +0 -981
  744. package/dist/dispatch-acp-manager.runtime-CvUvPlIu.js +0 -3
  745. package/dist/dispatch-acp.runtime-BD04s8Zg.js +0 -19
  746. package/dist/dispatch-dxndBjvg.js +0 -1131
  747. package/dist/doctor-device-pairing-BWOuDvCO.js +0 -307
  748. package/dist/doctor-gateway-daemon-flow-CfcG9HqL.js +0 -250
  749. package/dist/doctor-gateway-health-CgtIAXiV.js +0 -63
  750. package/dist/doctor-health-Dl8qTbf0.js +0 -59
  751. package/dist/doctor-health-contributions-7VvQGU8Z.js +0 -493
  752. package/dist/doctor-prompter-C1E_9epq.js +0 -56
  753. package/dist/doctor-workspace-status-D_hKwgSB.js +0 -75
  754. package/dist/dreaming-narrative-CGIhjB7J.js +0 -595
  755. package/dist/dreaming-zER_6Edx.js +0 -1574
  756. package/dist/embedded-gateway-stub.runtime-DW85g-TS.js +0 -9
  757. package/dist/exec-approvals-cli-Cw---PEd.js +0 -498
  758. package/dist/execute.runtime-g2ckBHQo.js +0 -1366
  759. package/dist/fallbacks-pV2ELjMN.js +0 -31
  760. package/dist/fallbacks-shared-w3hzF-a3.js +0 -111
  761. package/dist/fallbacks-w-04P5Ca.js +0 -2
  762. package/dist/gateway-D6iHe5yM.js +0 -115
  763. package/dist/gateway-cli-DA66EGkc.js +0 -1283
  764. package/dist/gateway-rpc-C-wnj8-r.js +0 -14
  765. package/dist/gateway-rpc.runtime-UIPl38ru.js +0 -23
  766. package/dist/gateway-runtime-4_MNp5Fb.js +0 -15
  767. package/dist/gateway-status-qhNQ0-uT.js +0 -584
  768. package/dist/genesis-tools-Zt9xVisn.js +0 -9144
  769. package/dist/genesis-tools.runtime-DOqh6dkQ.js +0 -2
  770. package/dist/get-reply-DQ0O9TtJ.js +0 -3879
  771. package/dist/get-reply-from-config.runtime-BuatHlOY.js +0 -2
  772. package/dist/graph-users-wwfIkVlV.js +0 -1337
  773. package/dist/health-Be7drwbn.js +0 -3
  774. package/dist/health-DJnGvMzg.js +0 -469
  775. package/dist/health-route-Du-tYbyy.js +0 -41
  776. package/dist/health-route-yas5DRN8.js +0 -2
  777. package/dist/heartbeat-runner-CgkBGYmZ.js +0 -1292
  778. package/dist/heartbeat-runner-DGh3rGv3.js +0 -5
  779. package/dist/heartbeat-runner.runtime-Cx_T3Yrs.js +0 -4
  780. package/dist/hooks-cli-BMwaAVjB.js +0 -433
  781. package/dist/image-fallbacks-NW-B8h53.js +0 -31
  782. package/dist/image-fallbacks-twUg-Ew1.js +0 -2
  783. package/dist/inbound-reply-dispatch-B3xJheBv.js +0 -73
  784. package/dist/infra-runtime-D0KgiuPR.js +0 -39
  785. package/dist/init-Bw8qk4Lv.js +0 -59
  786. package/dist/library-BNl9tYJG.js +0 -45
  787. package/dist/lifecycle-8ptHb58U.js +0 -571
  788. package/dist/lifecycle-CRrSobXZ.js +0 -229
  789. package/dist/lifecycle.runtime-BDtzaxrU.js +0 -2
  790. package/dist/list-C-ACwyIs.js +0 -131
  791. package/dist/list-CJ6S9iAc.js +0 -1212
  792. package/dist/list-DYwQ_Gfw.js +0 -2
  793. package/dist/list-kHLQDpvt.js +0 -2
  794. package/dist/list.probe-CBJUHqju.js +0 -419
  795. package/dist/llm-slug-generator-DLZt8Bt6.js +0 -79
  796. package/dist/load-config-D_5019M3.js +0 -35
  797. package/dist/local-dispatch.runtime-Dau5kHVW.js +0 -8
  798. package/dist/logs-cli-B1tDn7oN.js +0 -265
  799. package/dist/logs-cli.runtime-Cx4fMzWz.js +0 -2
  800. package/dist/main-session-restart-recovery-CK0sXd7f.js +0 -206
  801. package/dist/managed-image-attachments-97PVDeFD.js +0 -635
  802. package/dist/managed-image-attachments-CC4KLL8v.js +0 -2
  803. package/dist/manager-BQ31y7iX.js +0 -2057
  804. package/dist/manager-CFkV693Y.js +0 -2
  805. package/dist/markdown-to-line-zHVHdZSu.js +0 -790
  806. package/dist/mcp-cli-DJlict1A.js +0 -725
  807. package/dist/mcp-http-BARh68Sy.js +0 -529
  808. package/dist/memory-core-host-runtime-cli-BoZwOAnU.js +0 -9
  809. package/dist/message-BlYpA3Rj.js +0 -232
  810. package/dist/message-action-runner-l7HQgRsA.js +0 -2
  811. package/dist/message-action-runner-xpyTSTjc.js +0 -1407
  812. package/dist/message-actions-BYCdd6QG.js +0 -143
  813. package/dist/message.gateway.runtime-Cb8XMFan.js +0 -2
  814. package/dist/models-auth-status-D3gt082v.js +0 -201
  815. package/dist/models-cli-9FhzxcFw.js +0 -219
  816. package/dist/monitor-B0WA83w1.js +0 -788
  817. package/dist/monitor-B6-pdSFR.js +0 -671
  818. package/dist/monitor-BX1yfW2U.js +0 -2
  819. package/dist/monitor-DKv9iSX7.js +0 -1459
  820. package/dist/monitor-DNDx4gOO.js +0 -1237
  821. package/dist/monitor-DpAuHTne.js +0 -1661
  822. package/dist/monitor-auth-B42F9dgo.js +0 -207
  823. package/dist/monitor-processing-DyP1l7Er.js +0 -1974
  824. package/dist/monitor.runtime-DbcwE5XS.js +0 -2
  825. package/dist/monitor.webhook-Dthw-aQB.js +0 -180
  826. package/dist/msteams-D2mb7FnE.js +0 -35
  827. package/dist/native-hook-relay-CdaoEdNX.js +0 -519
  828. package/dist/nextcloud-talk-B18eVVV7.js +0 -17
  829. package/dist/node-cli-Ck0VwYwV.js +0 -2506
  830. package/dist/nodes-cli-DC-DcHIP.js +0 -1046
  831. package/dist/nodes-utils-BWIRDyv_.js +0 -84
  832. package/dist/nodes.helpers-BEHH7X2_.js +0 -34
  833. package/dist/notify-JkL7xdrB.js +0 -315
  834. package/dist/onboard-C5BIoHo2.js +0 -70
  835. package/dist/onboard-helpers-C2zyBKT7.js +0 -204
  836. package/dist/onboard-helpers-CaQKQFzC.js +0 -6
  837. package/dist/onboard-interactive-Bq6kHQx1.js +0 -24
  838. package/dist/onboard-non-interactive-DQFp1nqn.js +0 -548
  839. package/dist/onboard-qYbyvbbw.js +0 -2
  840. package/dist/onboard-remote-BrlKFoRp.js +0 -193
  841. package/dist/onboard-remote-CGK4Eovr.js +0 -2
  842. package/dist/onboard-skills-BOatQ3qu.js +0 -2
  843. package/dist/onboard-skills-MIp5L4Bg.js +0 -134
  844. package/dist/openai-http-BzR_snW0.js +0 -500
  845. package/dist/openresponses-http-D_qmLKbV.js +0 -1128
  846. package/dist/operator-approvals-client-BMXsikiI.js +0 -68
  847. package/dist/outbound.runtime-sBaP-y4C.js +0 -2
  848. package/dist/pair-command-approve-DJLjxT6x.js +0 -44
  849. package/dist/persistent-bindings.lifecycle-DzeMqt76.js +0 -85
  850. package/dist/persistent-bindings.lifecycle-zRaTKjMh.js +0 -2
  851. package/dist/pi-embedded-CeDhWvgx.js +0 -4
  852. package/dist/pi-embedded-DUpRXfJO.js +0 -2905
  853. package/dist/pi-embedded.runtime-DtYM7NdD.js +0 -4
  854. package/dist/pi-tool-definition-adapter-CB0HS-nc.js +0 -229
  855. package/dist/pi-tools-Bj9D94l1.js +0 -1057
  856. package/dist/pi-tools.before-tool-call-BbQkYemc.js +0 -2
  857. package/dist/pi-tools.before-tool-call-DgbBDh3b.js +0 -433
  858. package/dist/plugin-PC7i4gKf.js +0 -12195
  859. package/dist/plugin-enabled-CfTRDw44.js +0 -140
  860. package/dist/plugin-registration-B-k3D6sT.js +0 -23
  861. package/dist/plugin-service-BK8-VUTt.js +0 -2892
  862. package/dist/policy-BW0acqi4.js +0 -328
  863. package/dist/prepare.runtime-_AbiM89x.js +0 -815
  864. package/dist/probe-BMLDcZ32.js +0 -241
  865. package/dist/probe-Ba3TRP2B.js +0 -45
  866. package/dist/probe-CUiwktQB.js +0 -74
  867. package/dist/probe-DebEe8F0.js +0 -2
  868. package/dist/probe-DezLtnJj.js +0 -2
  869. package/dist/probe-V8OIWFIZ.js +0 -1443
  870. package/dist/probe-dGp0-neY.js +0 -2205
  871. package/dist/program-DW7m0H8i.js +0 -111
  872. package/dist/prompt-select-styled-jplnVzKe.js +0 -20
  873. package/dist/protocol-C83jsm03.js +0 -2335
  874. package/dist/provider-dispatcher-CE-8HFJ3.js +0 -22
  875. package/dist/provider-dispatcher-CvSHrBCK.js +0 -2
  876. package/dist/qr-cli-N0rKzCLa.js +0 -349
  877. package/dist/qr-cli-anaRAjRO.js +0 -2
  878. package/dist/reaction-runtime-api-D0RKf7dw.js +0 -116
  879. package/dist/reactions-D5tTqX43.js +0 -998
  880. package/dist/register-service-commands-DR8PFCDH.js +0 -71
  881. package/dist/register.agent-C0S6Qd9d.js +0 -248
  882. package/dist/register.configure-Syn4zjBT.js +0 -15
  883. package/dist/register.maintenance-DlWVxmgp.js +0 -363
  884. package/dist/register.message-Ca0UvwH3.js +0 -329
  885. package/dist/register.onboard-BrPnofu3.js +0 -88
  886. package/dist/register.runtime-DrxUrGzO.js +0 -81
  887. package/dist/register.setup-DgnkDiBO.js +0 -150
  888. package/dist/register.status-health-sessions-BvccPkCF.js +0 -1215
  889. package/dist/register.subclis-BybdnCZ1.js +0 -29
  890. package/dist/register.subclis-CmiGzm_7.js +0 -3
  891. package/dist/register.subclis-core-CdzVfdg9.js +0 -249
  892. package/dist/register.wallet-CY_R6-2U.js +0 -271
  893. package/dist/reply-dispatch-runtime-C1FpfnAM.js +0 -13
  894. package/dist/reply-runtime-s43-M8Jj.js +0 -11
  895. package/dist/reply.runtime-7wnQxEUw.js +0 -2
  896. package/dist/restart-health-COnZzsKp.js +0 -202
  897. package/dist/restart-health-eI6OqLsK.js +0 -2
  898. package/dist/root-help-DeQ9PX0j.js +0 -44
  899. package/dist/routes-BWEN5YAF.js +0 -2
  900. package/dist/routes-C672_WKa.js +0 -3341
  901. package/dist/rpc-B426srGJ.js +0 -61
  902. package/dist/rpc.runtime-DUM1XyRX.js +0 -21
  903. package/dist/run-delivery.runtime-CXw2jVkt.js +0 -530
  904. package/dist/run-embedded.runtime-xS-1mmyO.js +0 -4
  905. package/dist/run-execution-cli.runtime-aDPMKzJX.js +0 -4
  906. package/dist/run-executor.runtime-C4ZFsj8q.js +0 -277
  907. package/dist/run-main-4Rq8UxLR.js +0 -567
  908. package/dist/run-subagent-registry.runtime-DzAf7j8r.js +0 -2
  909. package/dist/run-wait-T_9raRki.js +0 -135
  910. package/dist/runtime-Bi-FG7ze.js +0 -973
  911. package/dist/runtime-DTEEU-FQ.js +0 -9
  912. package/dist/runtime-api-CD1uwpvJ.js +0 -4
  913. package/dist/runtime-api-CuUMmc6o.js +0 -9
  914. package/dist/runtime-api-D1I8x3ZK.js +0 -9
  915. package/dist/runtime-api-N4ICzHSN.js +0 -14
  916. package/dist/runtime-embedded-pi.runtime-TzUSObio.js +0 -2
  917. package/dist/runtime-internal-BpmmUWVj.js +0 -2
  918. package/dist/runtime-options-lwiANMrp.js +0 -275
  919. package/dist/runtime-schema-DyZs3Hqj.js +0 -27938
  920. package/dist/scan-KAzO-hG8.js +0 -523
  921. package/dist/scan-WYNB2yvG.js +0 -2
  922. package/dist/secrets-cli-V8e9noRa.js +0 -2101
  923. package/dist/security-cli-DQAHIStH.js +0 -486
  924. package/dist/selection-B1sx7E0M.js +0 -2
  925. package/dist/selection-CdYrfYRk.js +0 -7736
  926. package/dist/send-CS2Grx1T.js +0 -102
  927. package/dist/send-DD9fqnsS.js +0 -156
  928. package/dist/send.runtime-UBa9b0KL.js +0 -2
  929. package/dist/server-DTBpPcSJ.js +0 -77
  930. package/dist/server-LnjMkCwG.js +0 -13
  931. package/dist/server-context-CgUkot1S.js +0 -2
  932. package/dist/server-context-e5qiFYb9.js +0 -847
  933. package/dist/server-node-events-DGbm1S0O.js +0 -481
  934. package/dist/server-plugin-bootstrap-BAb2yBlZ.js +0 -11652
  935. package/dist/server-plugin-bootstrap-QC6Ie4eo.js +0 -2
  936. package/dist/server-restart-sentinel-CHIEkMav.js +0 -697
  937. package/dist/server.impl-smIsMGyM.js +0 -12822
  938. package/dist/service-CzJ-5DK_.js +0 -1415
  939. package/dist/session-kill-http-J_6Qu28L.js +0 -110
  940. package/dist/session-reset-service-BpBipveT.js +0 -471
  941. package/dist/session-route-CpYl3T8Y.js +0 -93
  942. package/dist/session-status.runtime-UUa0VU0y.js +0 -2
  943. package/dist/session-subagent-reactivation.runtime-L2O0yOy4.js +0 -2
  944. package/dist/session-tab-registry-DxPANUw6.js +0 -581
  945. package/dist/session-visibility-CPIadgvQ.js +0 -147
  946. package/dist/sessions-helpers-DdEWQ3o2.js +0 -304
  947. package/dist/sessions-history-http-B9AS9VFQ.js +0 -383
  948. package/dist/sessions-patch-DRBy0uu3.js +0 -309
  949. package/dist/sessions-resolve-DM6s9pot.js +0 -174
  950. package/dist/sessions.runtime-ixcVUViJ.js +0 -2
  951. package/dist/setup-BKyIGRRk.js +0 -505
  952. package/dist/setup-api-D3Djxtka.js +0 -29
  953. package/dist/setup-core-C5ITyKzA.js +0 -171
  954. package/dist/setup-core-Nm6km7jp.js +0 -176
  955. package/dist/setup-surface-BEpfVHSH.js +0 -403
  956. package/dist/setup-surface-D4gEPCHR.js +0 -219
  957. package/dist/setup-surface-DdkjjhYB.js +0 -286
  958. package/dist/setup.finalize-BOnrhqzV.js +0 -547
  959. package/dist/setup.gateway-config-CmRGTkaE.js +0 -250
  960. package/dist/shared-Bb4YCXx6.js +0 -198
  961. package/dist/shared-CZCh0WCN.js +0 -121
  962. package/dist/shared-Df0CbtUw.js +0 -76
  963. package/dist/slash-state-BQJu5tOn.js +0 -1911
  964. package/dist/src-C4ImkbSW.js +0 -3974
  965. package/dist/startup-context-nffy5sQU.js +0 -312
  966. package/dist/status-0QDxMlFq.js +0 -2
  967. package/dist/status-5OjwhqkA.js +0 -209
  968. package/dist/status-C306d1iE.js +0 -2
  969. package/dist/status-Crg2u6MB.js +0 -397
  970. package/dist/status-DMLvl7RU.js +0 -190
  971. package/dist/status-N59cRl1N.js +0 -3
  972. package/dist/status-all-WKQtyBf9.js +0 -498
  973. package/dist/status-json-C2DgeCRG.js +0 -14
  974. package/dist/status-json-command-B2k_1ZuR.js +0 -84
  975. package/dist/status-runtime-shared-ZCbKKj-y.js +0 -257
  976. package/dist/status-subagents.runtime-CmaY9hZm.js +0 -18
  977. package/dist/status-text-NR1x0nMa.js +0 -237
  978. package/dist/status.gateway-connection.runtime-DBlvpSWB.js +0 -2
  979. package/dist/status.gather-BkL7J_y1.js +0 -292
  980. package/dist/status.gather-CWbs5-z2.js +0 -2
  981. package/dist/status.runtime-BOc5e8DI.js +0 -2
  982. package/dist/status.scan-DY4x5vdB.js +0 -65
  983. package/dist/status.scan-overview-CF96KtOa.js +0 -379
  984. package/dist/status.scan.fast-json-CUQQXpr8.js +0 -2
  985. package/dist/status.scan.fast-json-Dd2Q4LW7.js +0 -132
  986. package/dist/status.summary-CfGo54T4.js +0 -214
  987. package/dist/status.summary-CyG5QMo9.js +0 -2
  988. package/dist/subagent-announce-DW816JCC.js +0 -351
  989. package/dist/subagent-announce-delivery-DgKXtDWV.js +0 -726
  990. package/dist/subagent-announce-output-BrJdNBlx.js +0 -364
  991. package/dist/subagent-control-xz3ZcUrb.js +0 -506
  992. package/dist/subagent-followup.runtime-DQS6ipTt.js +0 -68
  993. package/dist/subagent-orphan-recovery-CzwjvW_o.js +0 -305
  994. package/dist/subagent-registry-88vWnDP5.js +0 -1753
  995. package/dist/subagent-registry-B_JB7WyN.js +0 -3
  996. package/dist/subagent-spawn-ChRpfSX6.js +0 -1005
  997. package/dist/system-cli-BiYfWkTS.js +0 -59
  998. package/dist/targets-TpH8-6iR.js +0 -67
  999. package/dist/task-executor-Chx2YFYp.js +0 -360
  1000. package/dist/task-owner-access-CPMM8lVh.js +0 -74
  1001. package/dist/task-registry-Cb_XGvuS.js +0 -2366
  1002. package/dist/task-registry-delivery-runtime-6z8W4up9.js +0 -2
  1003. package/dist/task-registry-delivery-runtime-OqkDQtLj.js +0 -3
  1004. package/dist/task-registry.maintenance-Ci6oLcFg.js +0 -2
  1005. package/dist/task-registry.maintenance-i69b0iH7.js +0 -416
  1006. package/dist/testing-BmGGzr14.js +0 -575
  1007. package/dist/text-report-WpPbFau5.js +0 -587
  1008. package/dist/tool-resolution-DCK5whNz.js +0 -90
  1009. package/dist/tools-effective-inventory-CkymEUkf.js +0 -152
  1010. package/dist/tools-invoke-http-BECDcy94.js +0 -206
  1011. package/dist/trash-Cz555AtH.js +0 -24
  1012. package/dist/tui-cli-BTNsU35D.js +0 -4575
  1013. package/dist/update-cli-CEi34S-K.js +0 -1759
  1014. package/dist/upgrade-CeMGojsg.js +0 -1226
  1015. package/dist/video-generation-task-status-BGbHX8xJ.js +0 -163
  1016. package/dist/wait-for-idle-before-flush-CUNJdPz7.js +0 -5986
  1017. package/dist/wizard-models-DGVbHDnh.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-AGt54mci.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-D-tQxSLz.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-Bi2-6k_Q.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-D6RvPlwP.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-5ozxcRTm.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-CxLohd8A.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 };