remoteclaw 0.1.0-next.da482d8 → 0.1.0-next.db8a792

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 (1020) hide show
  1. package/dist/accounts-BZ2kR_Ij.js +47 -0
  2. package/dist/accounts-Bi4rFQG5.js +272 -0
  3. package/dist/accounts-Bpk-loA6.js +47 -0
  4. package/dist/accounts-D1CBpsaa.js +32 -0
  5. package/dist/accounts-DAdUdbPk.js +36 -0
  6. package/dist/accounts-WYyfAiie.js +270 -0
  7. package/dist/accounts-zQKMwnvt.js +36 -0
  8. package/dist/ack-reactions-B1l-vKPr.js +621 -0
  9. package/dist/ack-reactions-BnG0DLMu.js +621 -0
  10. package/dist/acp-cli-Btx71t69.js +1319 -0
  11. package/dist/acp-cli-DVQMjl0p.js +1324 -0
  12. package/dist/active-listener-BfN4RKlA.js +37 -0
  13. package/dist/active-listener-Bq7ckjOV.js +37 -0
  14. package/dist/agent-D2IwuL6g.js +688 -0
  15. package/dist/agent-WaE2mXI1.js +687 -0
  16. package/dist/agent-helpers-BcaiJFiG.js +400 -0
  17. package/dist/agent-scope-DVvX_nkQ.js +116 -0
  18. package/dist/agents-BwnT7jca.js +760 -0
  19. package/dist/agents.config-Dorm30BQ.js +116 -0
  20. package/dist/audio-B1lTyRqS.js +43 -0
  21. package/dist/audio-e0dFnrn8.js +43 -0
  22. package/dist/audit-DZvqycbG.js +3150 -0
  23. package/dist/audit-Mit73dYD.js +3150 -0
  24. package/dist/auth-C-XX0Tdt.js +314 -0
  25. package/dist/auth-D8--b01l.js +315 -0
  26. package/dist/auth-DJ7XEBDO.js +448 -0
  27. package/dist/auth-otyjXf9l.js +448 -0
  28. package/dist/banner-DSE-i7gH.js +294 -0
  29. package/dist/binaries-BSjilwX-.js +13 -0
  30. package/dist/bindings-DFTxQj8x.js +69 -0
  31. package/dist/bonjour-discovery-BnxTMHRd.js +378 -0
  32. package/dist/bonjour-discovery-CVJYHT3g.js +378 -0
  33. package/dist/boot/handler.js +28 -44
  34. package/dist/browser-cli-BR2pZWTC.js +1694 -0
  35. package/dist/browser-cli-I0kfR7FV.js +1690 -0
  36. package/dist/build-info.json +3 -3
  37. package/dist/call-Ck7ysmEl.js +517 -0
  38. package/dist/call-MN6mCJEB.js +518 -0
  39. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  40. package/dist/catalog-Bt9EM4sK.js +185 -0
  41. package/dist/catalog-BtUvWKd9.js +185 -0
  42. package/dist/channel-account-context-BLQq9NKz.js +133 -0
  43. package/dist/channel-account-context-CaCzVa76.js +133 -0
  44. package/dist/channel-activity-BatlvP_U.js +292 -0
  45. package/dist/channel-activity-DHVMMb2x.js +94 -0
  46. package/dist/channel-activity-DtRx3b0W.js +94 -0
  47. package/dist/channel-options-C6kT3nXB.js +32 -0
  48. package/dist/channel-options-CbgR_vsp.js +33 -0
  49. package/dist/channel-selection-CzbrpDPd.js +51 -0
  50. package/dist/channel-selection-Xv5UFxOx.js +51 -0
  51. package/dist/channel-web-DfDokU69.js +2134 -0
  52. package/dist/channel-web-DtvksSuY.js +2132 -0
  53. package/dist/channels-cli-BmdCVX6O.js +1435 -0
  54. package/dist/channels-cli-CrAZpaiN.js +1439 -0
  55. package/dist/channels-status-issues-B77y-TLr.js +18 -0
  56. package/dist/channels-status-issues-COECL8nx.js +18 -0
  57. package/dist/chrome-Cr5wmMk8.js +1733 -0
  58. package/dist/chrome-YBrnJN-g.js +1732 -0
  59. package/dist/chunk-CrfQ_O--.js +341 -0
  60. package/dist/chunk-DFBUmlXU.js +341 -0
  61. package/dist/clack-prompter-CFNKgQXx.js +122 -0
  62. package/dist/clack-prompter-DDlR2e34.js +121 -0
  63. package/dist/cli/daemon-cli.js +1 -1
  64. package/dist/cli-BbOinSy6.js +130 -0
  65. package/dist/cli-DuvHXQ5h.js +134 -0
  66. package/dist/client-BZeatr3g.js +2316 -0
  67. package/dist/client-Bc9JFAwL.js +2316 -0
  68. package/dist/clipboard-Com-8GBg.js +31 -0
  69. package/dist/clipboard-J_9AABIu.js +31 -0
  70. package/dist/command-format-CMAQa4dB.js +32 -0
  71. package/dist/command-format-KkslAzwV.js +18 -0
  72. package/dist/command-logger/handler.js +1 -1
  73. package/dist/command-registry-BJnVtHo0.js +215 -0
  74. package/dist/commands-ijxtne0J.js +41 -0
  75. package/dist/commands-kZtQfqDl.js +41 -0
  76. package/dist/commands-registry-BrBtH2_B.js +891 -0
  77. package/dist/commands-registry-xZoSouba.js +892 -0
  78. package/dist/common-6D7nhDP-.js +156 -0
  79. package/dist/common-B4cjsvqP.js +156 -0
  80. package/dist/completion-cli-CpUq9QC3.js +452 -0
  81. package/dist/completion-cli-De4umD_N.js +452 -0
  82. package/dist/config-C_WcTz_O.js +4231 -0
  83. package/dist/config-DfcqHTH-.js +4229 -0
  84. package/dist/config-cli-C7rq2n_m.js +243 -0
  85. package/dist/config-cli-VToCKln2.js +247 -0
  86. package/dist/config-guard-BlAcGEao.js +75 -0
  87. package/dist/config-guard-C-h_KIeI.js +99 -0
  88. package/dist/config-validation-C0YXR2dY.js +18 -0
  89. package/dist/config-validation-DDYBTmxT.js +18 -0
  90. package/dist/configure-Bkre1zEB.js +891 -0
  91. package/dist/configure-ifuEamRQ.js +889 -0
  92. package/dist/control-auth-DK6cIBzl.js +397 -0
  93. package/dist/control-auth-DQ8bfDMk.js +397 -0
  94. package/dist/control-ui-assets-DLEWfed6.js +186 -0
  95. package/dist/control-ui-assets-DVhkAyhv.js +186 -0
  96. package/dist/conversation-label-HuHoShPF.js +36 -0
  97. package/dist/conversation-label-L0QTtKji.js +36 -0
  98. package/dist/cron-cli-DnxnTi83.js +498 -0
  99. package/dist/cron-cli-yqcBkqZT.js +494 -0
  100. package/dist/daemon-cli-CmQYq8uO.js +735 -0
  101. package/dist/daemon-cli-_OIRoswC.js +737 -0
  102. package/dist/daemon-cli.js +34 -69
  103. package/dist/daemon-install-BEgffqDj.js +56 -0
  104. package/dist/daemon-install-DAorzotp.js +60 -0
  105. package/dist/daemon-install-helpers-B82uvJjJ.js +504 -0
  106. package/dist/daemon-install-helpers-BhL2Gh4l.js +504 -0
  107. package/dist/deliver-CCvDBk5c.js +481 -0
  108. package/dist/deliver-CqKw0wFi.js +481 -0
  109. package/dist/delivery-queue-CK7VnUJf.js +244 -0
  110. package/dist/delivery-queue-DMeQchpT.js +244 -0
  111. package/dist/devices-cli-C6UAfRV_.js +323 -0
  112. package/dist/devices-cli-Le-isdZB.js +319 -0
  113. package/dist/diagnostics-BhFwk6F3.js +35 -0
  114. package/dist/diagnostics-BtaQtaVR.js +35 -0
  115. package/dist/directory-cli-BqMfX5og.js +220 -0
  116. package/dist/directory-cli-DD72TTD4.js +224 -0
  117. package/dist/dispatcher-BLC2WYZv.js +173 -0
  118. package/dist/dispatcher-Cm2FAG_D.js +174 -0
  119. package/dist/dm-policy-shared-DOzpxMHC.js +22 -0
  120. package/dist/dm-policy-shared-DZY0f1bR.js +22 -0
  121. package/dist/dns-cli-BgsNg-bn.js +203 -0
  122. package/dist/dns-cli-CdMU5yuG.js +199 -0
  123. package/dist/dock-ByrYnLiz.js +929 -0
  124. package/dist/dock-CpNmmysM.js +928 -0
  125. package/dist/doctor-completion-BPeaRbmd.js +92 -0
  126. package/dist/doctor-completion-CfOyGJd3.js +92 -0
  127. package/dist/doctor-config-flow-DMyTycn7.js +1935 -0
  128. package/dist/doctor-config-flow-DoMu-pTm.js +1934 -0
  129. package/dist/enable-D5KetMo7.js +59 -0
  130. package/dist/entry.js +61 -1
  131. package/dist/env-BJ36dSrx.js +60 -0
  132. package/dist/errors-BfONuT95.js +35 -0
  133. package/dist/errors-_DSePI1C.js +35 -0
  134. package/dist/exec-DkFE7lqU.js +164 -0
  135. package/dist/exec-mY96dhIg.js +164 -0
  136. package/dist/extensionAPI.js +112 -76
  137. package/dist/fetch-B3EQXbTa.js +67 -0
  138. package/dist/fetch-BPeSHPvr.js +281 -0
  139. package/dist/fetch-BQ7HvRwe.js +67 -0
  140. package/dist/fetch-CbGTzJ8L.js +281 -0
  141. package/dist/fetch-CfIaWynF.js +67 -0
  142. package/dist/file-lock-BHfqppLm.js +107 -0
  143. package/dist/file-lock-CCBpdPM_.js +107 -0
  144. package/dist/fs-safe-BcEpbVjc.js +88 -0
  145. package/dist/fs-safe-S3Zvbabd.js +98 -0
  146. package/dist/gateway-cli-BXipRcsU.js +24602 -0
  147. package/dist/gateway-cli-Bv2K3rXx.js +24606 -0
  148. package/dist/gateway-rpc-BHnd7P1q.js +28 -0
  149. package/dist/gateway-rpc-COEQDswS.js +28 -0
  150. package/dist/gmail-setup-utils-BpdKFe3P.js +423 -0
  151. package/dist/gmail-setup-utils-CqbWr0Kq.js +422 -0
  152. package/dist/health-1ero5j64.js +1414 -0
  153. package/dist/health-ioP2au7j.js +1417 -0
  154. package/dist/heartbeat-visibility-C88L-_f2.js +125 -0
  155. package/dist/heartbeat-visibility-Dk_Q02qX.js +125 -0
  156. package/dist/hook-runner-global-BztoD8lu.js +527 -0
  157. package/dist/hooks-cli-B8D9DzRR.js +1226 -0
  158. package/dist/hooks-cli-rZ3GOXag.js +1222 -0
  159. package/dist/image-ops-Cx1ym2Hi.js +354 -0
  160. package/dist/image-ops-DWytvdh_.js +354 -0
  161. package/dist/import-CTUBsy7D.js +604 -0
  162. package/dist/import-cBp4f62k.js +606 -0
  163. package/dist/inbound-context-COwswi8z.js +68 -0
  164. package/dist/inbound-context-ChcNR30g.js +68 -0
  165. package/dist/index.js +127 -102
  166. package/dist/inspect-BsS3_z-x.js +286 -0
  167. package/dist/inspect-drfsUSIW.js +286 -0
  168. package/dist/installs-BFmmM5Zd.js +325 -0
  169. package/dist/installs-DA7SG0Tx.js +325 -0
  170. package/dist/ipv4-BZGSwnH4.js +46 -0
  171. package/dist/ipv4-DsOgHE0B.js +46 -0
  172. package/dist/ir-R3Pk8Cv8.js +972 -0
  173. package/dist/lifecycle-core-BZMeOT7u.js +474 -0
  174. package/dist/lifecycle-core-C6-_Gts0.js +476 -0
  175. package/dist/loader-CJ2UHqV7.js +22414 -0
  176. package/dist/loader-dEFvmwXu.js +22411 -0
  177. package/dist/logger-9I2fg5mr.js +49 -0
  178. package/dist/login-D9uJTyEv.js +62 -0
  179. package/dist/login-DTh702_w.js +61 -0
  180. package/dist/login-qr-BKsmW6XI.js +325 -0
  181. package/dist/login-qr-SOXdIR58.js +329 -0
  182. package/dist/logs-cli-BshJBHZQ.js +236 -0
  183. package/dist/logs-cli-Ckh-BBTT.js +240 -0
  184. package/dist/markdown-tables-Cfz7zDXI.js +29 -0
  185. package/dist/markdown-tables-DeFSK6aY.js +29 -0
  186. package/dist/media-BD2cZGXT.js +971 -0
  187. package/dist/media-CjvpnJmQ.js +10388 -0
  188. package/dist/message-action-names-CZHrHMRE.js +2520 -0
  189. package/dist/message-action-names-CiZ-0Smk.js +2520 -0
  190. package/dist/message-channel-EMCYRaxk.js +91 -0
  191. package/dist/mime-1E7nn9IU.js +146 -0
  192. package/dist/mime-mSgQeDnC.js +146 -0
  193. package/dist/net-Cg8AQeke.js +225 -0
  194. package/dist/net-DMh1m8AZ.js +225 -0
  195. package/dist/node-cli-BJ5CCbqx.js +1462 -0
  196. package/dist/node-cli-wYYhAs8x.js +1458 -0
  197. package/dist/node-service-CkwVlcey.js +67 -0
  198. package/dist/node-service-DTVW9YJh.js +67 -0
  199. package/dist/nodes-cli-CMFYLD1o.js +1346 -0
  200. package/dist/nodes-cli-DC2zUx3f.js +1350 -0
  201. package/dist/nodes-screen-6pXv1lYa.js +250 -0
  202. package/dist/nodes-screen-CTIZKksn.js +250 -0
  203. package/dist/note-CMELkPJN.js +92 -0
  204. package/dist/npm-registry-spec-BiJI7Rkr.js +786 -0
  205. package/dist/npm-registry-spec-Dza35Ig4.js +786 -0
  206. package/dist/npm-resolution-CUQGDty4.js +86 -0
  207. package/dist/npm-resolution-CwbZK9AI.js +86 -0
  208. package/dist/onboard-8Qd9lU8x.js +649 -0
  209. package/dist/onboard-Q3cY65m8.js +647 -0
  210. package/dist/onboard-auth-BUzYDEqf.js +211 -0
  211. package/dist/onboard-auth-DcVXyd-Z.js +207 -0
  212. package/dist/onboard-channels-BFHuA-AU.js +2548 -0
  213. package/dist/onboard-channels-DVrPP_ie.js +2547 -0
  214. package/dist/onboard-helpers-B-bBSsyR.js +363 -0
  215. package/dist/onboard-helpers-YsCa-sAt.js +364 -0
  216. package/dist/onboard-remote-BWFcuEOD.js +127 -0
  217. package/dist/onboard-remote-C0THuDTK.js +127 -0
  218. package/dist/onboarding-B31lnOPp.js +586 -0
  219. package/dist/onboarding-DmN_qC8e.js +588 -0
  220. package/dist/onboarding.finalize-DGD0PA-D.js +402 -0
  221. package/dist/onboarding.finalize-DNIb3meE.js +404 -0
  222. package/dist/onboarding.gateway-config-BaeIuA62.js +195 -0
  223. package/dist/onboarding.gateway-config-DMV2Odzr.js +201 -0
  224. package/dist/outbound-BdxBHDax.js +220 -0
  225. package/dist/outbound-D-Y9rMgB.js +221 -0
  226. package/dist/outbound-attachment-CvZ04r5k.js +18 -0
  227. package/dist/outbound-attachment-DYa1asB5.js +18 -0
  228. package/dist/outbound-attachment-DgUpk7Uh.js +18 -0
  229. package/dist/pairing-cli-BxTv78V7.js +125 -0
  230. package/dist/pairing-cli-CxUCzNUc.js +129 -0
  231. package/dist/pairing-labels-DVO6NJr0.js +9 -0
  232. package/dist/pairing-labels-D_pD8Cag.js +9 -0
  233. package/dist/pairing-store-Bu9pVlkO.js +459 -0
  234. package/dist/pairing-store-CWaGbAGi.js +460 -0
  235. package/dist/path-env-RsuO6yO-.js +89 -0
  236. package/dist/path-env-_my-d_iR.js +89 -0
  237. package/dist/path-safety-CfiVyVz7.js +14 -0
  238. package/dist/path-safety-D-wLK4pV.js +14 -0
  239. package/dist/plugin-auto-enable-CW01H36W.js +301 -0
  240. package/dist/plugin-auto-enable-CeHhBLCU.js +302 -0
  241. package/dist/plugin-registry-CWL37HnB.js +33 -0
  242. package/dist/plugin-registry-ELliiumZ.js +33 -0
  243. package/dist/plugin-sdk/auth/provider-auth.d.ts +0 -6
  244. package/dist/plugin-sdk/auto-reply/reply/agent-runner-utils.d.ts +9 -29
  245. package/dist/plugin-sdk/auto-reply/reply/commands-status.d.ts +0 -2
  246. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/shared.d.ts +1 -1
  247. package/dist/plugin-sdk/auto-reply/reply/queue/types.d.ts +0 -2
  248. package/dist/plugin-sdk/auto-reply/status.d.ts +0 -4
  249. package/dist/plugin-sdk/auto-reply/templating.d.ts +0 -4
  250. package/dist/plugin-sdk/config/sessions/types.d.ts +0 -2
  251. package/dist/plugin-sdk/config/types.tools.d.ts +1 -59
  252. package/dist/plugin-sdk/config/types.tts.d.ts +2 -1
  253. package/dist/plugin-sdk/config/zod-schema.agent-runtime.d.ts +0 -177
  254. package/dist/plugin-sdk/config/zod-schema.core.d.ts +2 -230
  255. package/dist/plugin-sdk/config/zod-schema.d.ts +3 -192
  256. package/dist/plugin-sdk/config/zod-schema.providers-core.d.ts +3 -15
  257. package/dist/plugin-sdk/config/zod-schema.providers.d.ts +2 -10
  258. package/dist/plugin-sdk/config/zod-schema.session.d.ts +1 -5
  259. package/dist/plugin-sdk/gateway/protocol/index.d.ts +5 -5
  260. package/dist/plugin-sdk/index.js +72 -142
  261. package/dist/plugin-sdk/middleware/cli-runtime-base.d.ts +6 -0
  262. package/dist/plugin-sdk/middleware/runtimes/claude.d.ts +6 -0
  263. package/dist/plugin-sdk/middleware/runtimes/codex.d.ts +2 -2
  264. package/dist/plugin-sdk/plugin-sdk/index.d.ts +2 -0
  265. package/dist/plugin-sdk/plugins/manifest-registry.d.ts +2 -0
  266. package/dist/plugin-sdk/plugins/manifest.d.ts +2 -0
  267. package/dist/plugin-sdk/plugins/registry.d.ts +18 -0
  268. package/dist/plugin-sdk/plugins/types.d.ts +4 -0
  269. package/dist/plugin-sdk/stt/preflight.d.ts +2 -4
  270. package/dist/plugin-sdk/stt/providers/index.d.ts +1 -1
  271. package/dist/plugin-sdk/stt/providers/shared.d.ts +20 -1
  272. package/dist/plugin-sdk/tts/providers/edge.d.ts +2 -0
  273. package/dist/plugin-sdk/tts/providers/elevenlabs.d.ts +2 -0
  274. package/dist/plugin-sdk/tts/providers/index.d.ts +4 -0
  275. package/dist/plugin-sdk/tts/providers/openai.d.ts +2 -0
  276. package/dist/plugin-sdk/tts/tts.d.ts +13 -5
  277. package/dist/plugin-sdk/tts/types.d.ts +21 -0
  278. package/dist/plugins-DExsdlTp.js +455 -0
  279. package/dist/plugins-DdMgSc_b.js +453 -0
  280. package/dist/plugins-cli-DqBWiT_G.js +806 -0
  281. package/dist/plugins-cli-KQEzhU6P.js +802 -0
  282. package/dist/ports-CL0pXAXO.js +96 -0
  283. package/dist/ports-CRI-HSZx.js +370 -0
  284. package/dist/ports-DiQFcKUB.js +316 -0
  285. package/dist/ports-HRurfPIr.js +96 -0
  286. package/dist/preflight-6QRqxWh7.js +667 -0
  287. package/dist/preflight-DDZjr5KD.js +667 -0
  288. package/dist/program-DmhbOJj3.js +249 -0
  289. package/dist/program-context-PPMzZ6Gu.js +474 -0
  290. package/dist/prompt-select-styled-CmSWunD8.js +1669 -0
  291. package/dist/prompt-select-styled-PfxT9zl9.js +1672 -0
  292. package/dist/provider-auth-CfdnLqh3.js +187 -0
  293. package/dist/provider-auth-gpHOMUBP.js +187 -0
  294. package/dist/provider-dispatcher-D4eY8LZW.js +659 -0
  295. package/dist/provider-dispatcher-D5Q7M15D.js +660 -0
  296. package/dist/push-apns-BNwVMXX9.js +713 -0
  297. package/dist/push-apns-BszVkcZK.js +711 -0
  298. package/dist/pw-ai-Bdb3zrBM.js +1911 -0
  299. package/dist/pw-ai-BvcvEdGs.js +1908 -0
  300. package/dist/qr-cli-BBgk2ci1.js +349 -0
  301. package/dist/qr-cli-BLzVrhia.js +353 -0
  302. package/dist/redact-snapshot-CyBDcb_a.js +1966 -0
  303. package/dist/redact-snapshot-D9oPMqA-.js +1966 -0
  304. package/dist/register.agent-CAhKX3Ft.js +1019 -0
  305. package/dist/register.agent-RKHXtLLm.js +291 -0
  306. package/dist/register.configure-CW6XRGxV.js +129 -0
  307. package/dist/register.configure-dvrKc0j7.js +134 -0
  308. package/dist/register.import-CRLOolHv.js +31 -0
  309. package/dist/register.import-dhDEj7Om.js +29 -0
  310. package/dist/register.maintenance-EAhr1tJ9.js +500 -0
  311. package/dist/register.maintenance-lWz4v90u.js +502 -0
  312. package/dist/register.message-DyWkwUIU.js +690 -0
  313. package/dist/register.message-bl2Khz6c.js +686 -0
  314. package/dist/register.onboard-BAozmeei.js +97 -0
  315. package/dist/register.onboard-Da9hWQR1.js +93 -0
  316. package/dist/register.setup-DVrQWLoF.js +117 -0
  317. package/dist/register.setup-DbiLuuqg.js +113 -0
  318. package/dist/register.status-health-sessions-CA8ApUkH.js +668 -0
  319. package/dist/register.status-health-sessions-lGszs-NJ.js +428 -0
  320. package/dist/register.subclis-C-lqMygb.js +267 -0
  321. package/dist/replies-BTC1z8j0.js +136 -0
  322. package/dist/replies-BhlnuFp0.js +136 -0
  323. package/dist/reply-DZMooMoq.js +12880 -0
  324. package/dist/reply-directives-C0-hYyAt.js +182 -0
  325. package/dist/reply-directives-C_CGXLBJ.js +182 -0
  326. package/dist/reply-payloads-BospFSPI.js +527 -0
  327. package/dist/reply-prefix-DDgh77yy.js +37 -0
  328. package/dist/reply-prefix-DwKZPZyG.js +37 -0
  329. package/dist/reply-yGEQ0UW4.js +12877 -0
  330. package/dist/resolve-route-B73QhBIl.js +249 -0
  331. package/dist/resolve-route-DckdRbW8.js +249 -0
  332. package/dist/response-prefix-template-x5RBQnEy.js +134 -0
  333. package/dist/retry-CDrH81GP.js +77 -0
  334. package/dist/run-main-D869n5qf.js +307 -0
  335. package/dist/secure-random-CxzxAnMS.js +44 -0
  336. package/dist/security-cli-CfqosyUf.js +487 -0
  337. package/dist/security-cli-DMZun6gO.js +482 -0
  338. package/dist/send-3wvngctD.js +547 -0
  339. package/dist/send-AY7Fs5ky.js +374 -0
  340. package/dist/send-BSWD4Kr_.js +2245 -0
  341. package/dist/send-BT4HhTLm.js +349 -0
  342. package/dist/send-BvuxToC8.js +2245 -0
  343. package/dist/send-CaUxFvu0.js +492 -0
  344. package/dist/send-CiBRE4OY.js +1178 -0
  345. package/dist/send-Cidd4lQn.js +11 -0
  346. package/dist/send-Cq_Db9wG.js +1779 -0
  347. package/dist/send-DBFcxDPm.js +1776 -0
  348. package/dist/send-DUha0nIz.js +492 -0
  349. package/dist/send-DgYBI05s.js +332 -0
  350. package/dist/send-Dnf5bISH.js +426 -0
  351. package/dist/send-NcQk6UH1.js +547 -0
  352. package/dist/send-Og0-IMee.js +29 -0
  353. package/dist/send-oCN80Pl2.js +349 -0
  354. package/dist/server-DoGGLeP3.js +202 -0
  355. package/dist/server-V7G9FG2A.js +206 -0
  356. package/dist/server-lifecycle-CSWpSlvn.js +2437 -0
  357. package/dist/server-lifecycle-Cal8hBP1.js +2437 -0
  358. package/dist/server-node-events-DSee6jSG.js +394 -0
  359. package/dist/server-node-events-DbQWkU3M.js +390 -0
  360. package/dist/service-Duw0xMJX.js +670 -0
  361. package/dist/service-SRcnA1Am.js +670 -0
  362. package/dist/session-BLcfWX5_.js +170 -0
  363. package/dist/session-CQwkaAs-.js +170 -0
  364. package/dist/session-cost-usage-C-UcrvL4.js +627 -0
  365. package/dist/session-cost-usage-Dg3dzS0E.js +627 -0
  366. package/dist/session-dirs-D6mFEF90.js +318 -0
  367. package/dist/session-dirs-DVsG6e7L.js +318 -0
  368. package/dist/session-utils-C6522g3D.js +622 -0
  369. package/dist/session-utils-Dq2BJyVy.js +622 -0
  370. package/dist/sessions-CNkj4Eq8.js +247 -0
  371. package/dist/sessions-DDIoP7Rl.js +2569 -0
  372. package/dist/shell-env-D8nXPDbP.js +163 -0
  373. package/dist/ssrf-7I3FUHpm.js +183 -0
  374. package/dist/ssrf-DZi4qw5c.js +183 -0
  375. package/dist/status-CrAe8ZYt.js +1983 -0
  376. package/dist/status-DetRJxvZ.js +1979 -0
  377. package/dist/status.update-DquSK3p7.js +449 -0
  378. package/dist/status.update-iABAY3iW.js +449 -0
  379. package/dist/store-Bnm6zwaq.js +2571 -0
  380. package/dist/store-CVkGKjWm.js +64 -0
  381. package/dist/store-D_gpBpAW.js +64 -0
  382. package/dist/store-mxh63FBa.js +53 -0
  383. package/dist/subagent-registry-DNAz7Heu.js +4856 -0
  384. package/dist/subagent-registry-Dhz6HC4Z.js +4854 -0
  385. package/dist/subsystem-DGSHVL8I.js +1081 -0
  386. package/dist/subsystem-m7RSGQoR.js +1196 -0
  387. package/dist/system-cli-ByVDF6p8.js +77 -0
  388. package/dist/system-cli-CERb89Bl.js +73 -0
  389. package/dist/systemd-CSUtfsJx.js +547 -0
  390. package/dist/systemd-hints-BCxkQemJ.js +278 -0
  391. package/dist/systemd-hints-ef7m-7ZH.js +278 -0
  392. package/dist/systemd-linger-CWLgT0Wr.js +75 -0
  393. package/dist/systemd-linger-DT0E7YET.js +75 -0
  394. package/dist/systemd-tS61V4ao.js +547 -0
  395. package/dist/tables-DED01JNI.js +55 -0
  396. package/dist/tables-K3rOiGaJ.js +55 -0
  397. package/dist/tables-NcsXz3r_.js +55 -0
  398. package/dist/tailnet-CEudzG0i.js +40 -0
  399. package/dist/tailnet-D66Y5zC7.js +40 -0
  400. package/dist/tailscale-DjSRjPA-.js +230 -0
  401. package/dist/tailscale-DngZHD9L.js +230 -0
  402. package/dist/targets-BOpYPsGM.js +2545 -0
  403. package/dist/targets-BVsxzQh1.js +220 -0
  404. package/dist/targets-C99szk_e.js +114 -0
  405. package/dist/targets-CA4zx5G4.js +650 -0
  406. package/dist/targets-CTNm3bJ8.js +2544 -0
  407. package/dist/targets-DpmQjetK.js +53 -0
  408. package/dist/targets-Q-YGeAqu.js +650 -0
  409. package/dist/targets-rdWlC6Y-.js +53 -0
  410. package/dist/tool-display-Br6mwaJc.js +785 -0
  411. package/dist/tool-display-CLBf5cRa.js +785 -0
  412. package/dist/tool-images-DB4f57XK.js +263 -0
  413. package/dist/tool-images-kloBqxqK.js +263 -0
  414. package/dist/trash-B32LfX0l.js +125 -0
  415. package/dist/trash-SlUJxKO7.js +125 -0
  416. package/dist/tui-CHOtFK6k.js +3282 -0
  417. package/dist/tui-D4yiSpop.js +3282 -0
  418. package/dist/tui-cli-CzrjmAMZ.js +66 -0
  419. package/dist/tui-cli-Dpbs2QW_.js +62 -0
  420. package/dist/update-B5nYVxpc.js +349 -0
  421. package/dist/update-Bs3HhSnE.js +349 -0
  422. package/dist/update-cli-D_yz9Kyz.js +1147 -0
  423. package/dist/update-cli-DdfwNAsA.js +1149 -0
  424. package/dist/usage-BVyabt5E.js +5421 -0
  425. package/dist/voice-credentials-CI4VgB6u.js +46 -0
  426. package/dist/voice-credentials-l_d_gZiG.js +46 -0
  427. package/dist/web-B5xSAAH2.js +74 -0
  428. package/dist/web-Cc4tDVO9.js +3067 -0
  429. package/dist/web-Cdp9_IUk.js +79 -0
  430. package/dist/webhooks-cli-BDPcBkZL.js +330 -0
  431. package/dist/webhooks-cli-sRfsNesg.js +334 -0
  432. package/dist/whatsapp-actions-BGZXdWiP.js +125 -0
  433. package/dist/whatsapp-actions-HdmZu8oU.js +130 -0
  434. package/dist/workspace-D5LAl41l.js +449 -0
  435. package/dist/workspace-DRYGbrDM.js +447 -0
  436. package/dist/zod-schema-C8gEV0uz.js +2739 -0
  437. package/dist/zod-schema-CCUbW_Si.js +2739 -0
  438. package/package.json +1 -1
  439. package/dist/accounts-Aqbb2_Fn.js +0 -270
  440. package/dist/accounts-Bo2bX8jP.js +0 -272
  441. package/dist/accounts-D3fAPVzU.js +0 -36
  442. package/dist/accounts-DUEDngp6.js +0 -32
  443. package/dist/accounts-DZmv4bXS.js +0 -47
  444. package/dist/accounts-DmB4SVPK.js +0 -47
  445. package/dist/accounts-DtkyfvwR.js +0 -36
  446. package/dist/ack-reactions-Bvfy17SM.js +0 -446
  447. package/dist/ack-reactions-DYU8uhcz.js +0 -446
  448. package/dist/acp-cli-DVXhDMc6.js +0 -1324
  449. package/dist/acp-cli-QBL4_qcW.js +0 -1319
  450. package/dist/active-listener-CwxZ24bZ.js +0 -37
  451. package/dist/active-listener-v2sItamh.js +0 -37
  452. package/dist/agent-BisC5WZ6.js +0 -704
  453. package/dist/agent-Bqdrc0AK.js +0 -703
  454. package/dist/agent-helpers-BSGqeJr-.js +0 -400
  455. package/dist/agent-scope-_ND_-bJy.js +0 -116
  456. package/dist/agents-khSbraAA.js +0 -760
  457. package/dist/agents.config-D8gLHPWo.js +0 -116
  458. package/dist/audio-BIvUsncf.js +0 -43
  459. package/dist/audio-CQ8TfmVN.js +0 -43
  460. package/dist/audit-C0x7Cm6K.js +0 -3150
  461. package/dist/audit-CAY-uzWP.js +0 -3150
  462. package/dist/auth-DGqCLaQq.js +0 -448
  463. package/dist/auth-DLTRySEi.js +0 -314
  464. package/dist/auth-Drf91ntw.js +0 -315
  465. package/dist/auth-ku2khJyQ.js +0 -448
  466. package/dist/banner-txHC40UW.js +0 -294
  467. package/dist/binaries-BTvHIrCr.js +0 -13
  468. package/dist/bindings-DsWJQVKh.js +0 -69
  469. package/dist/bonjour-discovery-BElR62fH.js +0 -378
  470. package/dist/bonjour-discovery-C8XyVsjb.js +0 -378
  471. package/dist/browser-cli-DxJew43l.js +0 -1694
  472. package/dist/browser-cli-p0nakrjO.js +0 -1690
  473. package/dist/call-BrTmlOx3.js +0 -518
  474. package/dist/call-ChdUdwb4.js +0 -517
  475. package/dist/catalog-DTlcfTT9.js +0 -185
  476. package/dist/catalog-PixZqhZK.js +0 -185
  477. package/dist/channel-account-context-BO245Tcn.js +0 -133
  478. package/dist/channel-account-context-BgK0hm-I.js +0 -133
  479. package/dist/channel-activity-B0qlUR5e.js +0 -292
  480. package/dist/channel-activity-C-L6rDrQ.js +0 -94
  481. package/dist/channel-activity-DdgLBZ7M.js +0 -94
  482. package/dist/channel-options-CjlvAHSH.js +0 -32
  483. package/dist/channel-options-DpjP7qQf.js +0 -33
  484. package/dist/channel-selection-DW21dXB1.js +0 -51
  485. package/dist/channel-selection-wK_6S2Ku.js +0 -51
  486. package/dist/channel-web-COTkzJBt.js +0 -2136
  487. package/dist/channel-web-DUz5bn9h.js +0 -2134
  488. package/dist/channels-cli-D8RS8g2Q.js +0 -1438
  489. package/dist/channels-cli-X_8rENR6.js +0 -1434
  490. package/dist/channels-status-issues-B6I2l7Sm.js +0 -18
  491. package/dist/channels-status-issues-DhDH2fWp.js +0 -18
  492. package/dist/chrome-Dqtq7zCc.js +0 -1733
  493. package/dist/chrome-XeSY99Z_.js +0 -1732
  494. package/dist/chunk-CWD_zrz_.js +0 -341
  495. package/dist/chunk-LUabyS9k.js +0 -341
  496. package/dist/clack-prompter-fAgbvPW4.js +0 -122
  497. package/dist/clack-prompter-kf9qTN5p.js +0 -121
  498. package/dist/cli-BjPLpuZR.js +0 -133
  499. package/dist/cli-fFyOTtkD.js +0 -129
  500. package/dist/client-B9u3JdT_.js +0 -2316
  501. package/dist/client-DEEOhx0w.js +0 -2316
  502. package/dist/clipboard-B2nstLx7.js +0 -31
  503. package/dist/clipboard-C8QI9fes.js +0 -31
  504. package/dist/command-format-D0vKipG9.js +0 -32
  505. package/dist/command-format-LFmgWzKJ.js +0 -18
  506. package/dist/command-registry-BsPaMI53.js +0 -215
  507. package/dist/commands-BAYwlS3d.js +0 -41
  508. package/dist/commands-D842kCjj.js +0 -41
  509. package/dist/commands-registry-Cg2GTT2J.js +0 -892
  510. package/dist/commands-registry-Yz-uV5oG.js +0 -891
  511. package/dist/common-B67cBSew.js +0 -156
  512. package/dist/common-DEoiTqOr.js +0 -156
  513. package/dist/completion-cli-BO5mIPLa.js +0 -452
  514. package/dist/completion-cli-z9a6MVgr.js +0 -452
  515. package/dist/config-CAa0rZSx.js +0 -4225
  516. package/dist/config-W0w-gi2j.js +0 -4223
  517. package/dist/config-cli-DdRue35G.js +0 -243
  518. package/dist/config-cli-uOwxu5AC.js +0 -247
  519. package/dist/config-guard-BI85dxHR.js +0 -99
  520. package/dist/config-guard-DQqnigKh.js +0 -75
  521. package/dist/config-validation-D-h4LHyA.js +0 -18
  522. package/dist/config-validation-Df_kroIQ.js +0 -18
  523. package/dist/configure-B7ChPbXv.js +0 -891
  524. package/dist/configure-QspkIXME.js +0 -889
  525. package/dist/control-auth-BrBr2xb8.js +0 -397
  526. package/dist/control-auth-CehjYKnL.js +0 -397
  527. package/dist/control-ui-assets-D8F383Mo.js +0 -186
  528. package/dist/control-ui-assets-DYKtRIm0.js +0 -186
  529. package/dist/conversation-label-Bn5j3lUT.js +0 -36
  530. package/dist/conversation-label-CDH4rKMG.js +0 -36
  531. package/dist/cron-cli-DVzDHzAX.js +0 -494
  532. package/dist/cron-cli-gkH2qKM4.js +0 -498
  533. package/dist/daemon-cli-BTdNO1vH.js +0 -737
  534. package/dist/daemon-cli-DNNqI2LD.js +0 -735
  535. package/dist/daemon-install-CaEHG92p.js +0 -56
  536. package/dist/daemon-install-DbpDSDfW.js +0 -60
  537. package/dist/daemon-install-helpers-DjE_WnlY.js +0 -504
  538. package/dist/daemon-install-helpers-DocTUxqQ.js +0 -504
  539. package/dist/deliver-CDcL8ok6.js +0 -481
  540. package/dist/deliver-CS8JsevV.js +0 -481
  541. package/dist/delivery-queue-CTaYZQ_8.js +0 -244
  542. package/dist/delivery-queue-DMZ7mH8P.js +0 -244
  543. package/dist/devices-cli-BBJ4His-.js +0 -319
  544. package/dist/devices-cli-DHSJSFW1.js +0 -323
  545. package/dist/diagnostics-BSvCaLNs.js +0 -35
  546. package/dist/diagnostics-mWFAsFeo.js +0 -35
  547. package/dist/directory-cli-C-oHD_XE.js +0 -224
  548. package/dist/directory-cli-Cw99VGvr.js +0 -220
  549. package/dist/dispatcher-C8d1NNLZ.js +0 -174
  550. package/dist/dispatcher-DY6Ga60j.js +0 -173
  551. package/dist/dm-policy-shared-CRQ-Wr5g.js +0 -22
  552. package/dist/dm-policy-shared-CXXf2ltd.js +0 -22
  553. package/dist/dns-cli-BOqx9qo1.js +0 -199
  554. package/dist/dns-cli-WfqSC3JU.js +0 -203
  555. package/dist/dock-Big-J2VN.js +0 -929
  556. package/dist/dock-Cj4PKiUh.js +0 -928
  557. package/dist/doctor-completion-hYqcZ7IE.js +0 -92
  558. package/dist/doctor-completion-nxQQ5bEw.js +0 -92
  559. package/dist/doctor-config-flow-BUuADMDa.js +0 -1935
  560. package/dist/doctor-config-flow-yOUpQC2B.js +0 -1934
  561. package/dist/enable-DC9V0nTO.js +0 -59
  562. package/dist/env-B3zr72vQ.js +0 -60
  563. package/dist/errors-CdmXrBic.js +0 -35
  564. package/dist/errors-Cr_NbOb4.js +0 -35
  565. package/dist/exec-D_s-zAtY.js +0 -164
  566. package/dist/exec-Zz6eJ6YU.js +0 -164
  567. package/dist/fetch-BIZkXB5i.js +0 -67
  568. package/dist/fetch-DRVdxxEj.js +0 -67
  569. package/dist/fetch-DTR2MlOk.js +0 -67
  570. package/dist/file-lock-6NXMPZTT.js +0 -107
  571. package/dist/file-lock-C_KRlR7M.js +0 -107
  572. package/dist/fs-safe-DZHpH7TI.js +0 -98
  573. package/dist/fs-safe-vm3JMUkq.js +0 -88
  574. package/dist/gateway-cli-DEW-Ukmc.js +0 -24351
  575. package/dist/gateway-cli-DQYcZCOV.js +0 -24347
  576. package/dist/gateway-rpc-BCFkQPa2.js +0 -28
  577. package/dist/gateway-rpc-DOgYbsOG.js +0 -28
  578. package/dist/gmail-setup-utils-DMeA1UM1.js +0 -423
  579. package/dist/gmail-setup-utils-FHWSAur3.js +0 -422
  580. package/dist/health-BrLNGkZV.js +0 -1414
  581. package/dist/health-C8p9mnfl.js +0 -1417
  582. package/dist/heartbeat-visibility-CJVdaMZF.js +0 -125
  583. package/dist/heartbeat-visibility-DwK1UL0t.js +0 -125
  584. package/dist/hook-runner-global-C0DFQmQw.js +0 -527
  585. package/dist/hooks-cli-DEKi-tbA.js +0 -1221
  586. package/dist/hooks-cli-FndXPMD3.js +0 -1225
  587. package/dist/image-ops-B9ofmzSq.js +0 -354
  588. package/dist/image-ops-CMuvRsMY.js +0 -354
  589. package/dist/import-BH13F5mT.js +0 -606
  590. package/dist/import-D8HVcDqO.js +0 -604
  591. package/dist/inbound-context-BLy-G2Eq.js +0 -68
  592. package/dist/inbound-context-CmmmT8IP.js +0 -68
  593. package/dist/inbound-path-policy-BdmTOUka.js +0 -90
  594. package/dist/inbound-path-policy-BurOAu44.js +0 -90
  595. package/dist/inspect-nW8LAukU.js +0 -286
  596. package/dist/inspect-xy2EHy8G.js +0 -286
  597. package/dist/installs-CpfHmKY1.js +0 -325
  598. package/dist/installs-DebiMrGj.js +0 -325
  599. package/dist/ipv4-ysiNGssl.js +0 -46
  600. package/dist/ipv4-zc_Hfvbp.js +0 -46
  601. package/dist/ir-CaxTklDC.js +0 -940
  602. package/dist/lifecycle-core-Z5SScMlU.js +0 -476
  603. package/dist/lifecycle-core-pPwYSt7m.js +0 -474
  604. package/dist/loader-BapIdJyx.js +0 -22404
  605. package/dist/loader-BdAToyDH.js +0 -22401
  606. package/dist/local-roots-CrJ_Jv_G.js +0 -314
  607. package/dist/local-roots-n_Y4iYwb.js +0 -313
  608. package/dist/logger-B8yHnzPl.js +0 -49
  609. package/dist/login-C99fsB0N.js +0 -61
  610. package/dist/login-cLvGPjeO.js +0 -62
  611. package/dist/login-qr-CGqRFwgl.js +0 -329
  612. package/dist/login-qr-dnY5DC2C.js +0 -325
  613. package/dist/logs-cli-Bda7xY4N.js +0 -236
  614. package/dist/logs-cli-HzR-vnpD.js +0 -240
  615. package/dist/markdown-tables-58Hq__7K.js +0 -29
  616. package/dist/markdown-tables-GFEX0OR6.js +0 -29
  617. package/dist/media-CFsyXs3H.js +0 -940
  618. package/dist/media-Du5SHtnp.js +0 -10452
  619. package/dist/message-action-names-BfuEvR6j.js +0 -2521
  620. package/dist/message-action-names-CVBkpOLt.js +0 -2521
  621. package/dist/message-channel-FMNRI5Ax.js +0 -91
  622. package/dist/mime-AuIDUZPG.js +0 -149
  623. package/dist/mime-Cqg1jjia.js +0 -149
  624. package/dist/net-BEFkF-nI.js +0 -225
  625. package/dist/net-CNsUGiSw.js +0 -225
  626. package/dist/node-cli-Bu-InsO9.js +0 -1462
  627. package/dist/node-cli-DE7Pm7Fr.js +0 -1458
  628. package/dist/node-service-CumFZc9L.js +0 -67
  629. package/dist/node-service-DY1gG06I.js +0 -67
  630. package/dist/nodes-cli-B5aAExN0.js +0 -1350
  631. package/dist/nodes-cli-eKRqlKuO.js +0 -1346
  632. package/dist/nodes-screen-B3Sij1uT.js +0 -250
  633. package/dist/nodes-screen-DEvpoFmH.js +0 -250
  634. package/dist/note-CPFJCWJJ.js +0 -92
  635. package/dist/npm-registry-spec-BgMtTHvq.js +0 -786
  636. package/dist/npm-registry-spec-Dz3z1Zpd.js +0 -786
  637. package/dist/npm-resolution-Buio63BQ.js +0 -86
  638. package/dist/npm-resolution-gH1zHW2a.js +0 -86
  639. package/dist/onboard-BSf6qJWk.js +0 -647
  640. package/dist/onboard-V-SsZRk-.js +0 -649
  641. package/dist/onboard-auth-C_wHkop1.js +0 -207
  642. package/dist/onboard-auth-CkCBLvTg.js +0 -211
  643. package/dist/onboard-channels-DQTGPC18.js +0 -2548
  644. package/dist/onboard-channels-DSDQfR0u.js +0 -2547
  645. package/dist/onboard-helpers-Q7M6vdzh.js +0 -363
  646. package/dist/onboard-helpers-SCO3k5Y8.js +0 -364
  647. package/dist/onboard-remote-Co2hv1AD.js +0 -127
  648. package/dist/onboard-remote-Dl3BFSg2.js +0 -127
  649. package/dist/onboarding-B0bJfZ20.js +0 -588
  650. package/dist/onboarding-CeBR9OBi.js +0 -586
  651. package/dist/onboarding.finalize-BPgfWPB9.js +0 -404
  652. package/dist/onboarding.finalize-BmfLvNPJ.js +0 -402
  653. package/dist/onboarding.gateway-config-BL0Q7Wpg.js +0 -201
  654. package/dist/onboarding.gateway-config-D2QsXMYO.js +0 -195
  655. package/dist/outbound-CcaPcetn.js +0 -220
  656. package/dist/outbound-CeiW8z3a.js +0 -221
  657. package/dist/outbound-attachment-BIvFb3Is.js +0 -18
  658. package/dist/outbound-attachment-Bfm5-JYe.js +0 -18
  659. package/dist/outbound-attachment-CZ7zoYxB.js +0 -18
  660. package/dist/pairing-cli-CgX79ujL.js +0 -125
  661. package/dist/pairing-cli-DvbbXFgC.js +0 -129
  662. package/dist/pairing-labels-3wDxaApH.js +0 -9
  663. package/dist/pairing-labels-DCbWnbWk.js +0 -9
  664. package/dist/pairing-store-CdY7iRS0.js +0 -459
  665. package/dist/pairing-store-DykkYpQ7.js +0 -460
  666. package/dist/path-env-Cqo5LZmw.js +0 -89
  667. package/dist/path-env-GTM4HXCN.js +0 -89
  668. package/dist/path-safety-CXKAVpMp.js +0 -14
  669. package/dist/path-safety-DGB91qBk.js +0 -14
  670. package/dist/plugin-auto-enable-C6FPGg_-.js +0 -301
  671. package/dist/plugin-auto-enable-L8eOc8iC.js +0 -302
  672. package/dist/plugin-registry-CHlaWZD7.js +0 -33
  673. package/dist/plugin-registry-DQdMze4z.js +0 -33
  674. package/dist/plugin-sdk/auth/session-override.d.ts +0 -17
  675. package/dist/plugin-sdk/auto-reply/reply/directive-handling.auth.d.ts +0 -18
  676. package/dist/plugin-sdk/link-understanding/apply.d.ts +0 -10
  677. package/dist/plugin-sdk/link-understanding/defaults.d.ts +0 -2
  678. package/dist/plugin-sdk/link-understanding/detect.d.ts +0 -3
  679. package/dist/plugin-sdk/link-understanding/format.d.ts +0 -4
  680. package/dist/plugin-sdk/link-understanding/runner.d.ts +0 -11
  681. package/dist/plugin-sdk/media/input-files.d.ts +0 -95
  682. package/dist/plugin-sdk/media-understanding/apply.d.ts +0 -19
  683. package/dist/plugin-sdk/media-understanding/attachments.d.ts +0 -49
  684. package/dist/plugin-sdk/media-understanding/concurrency.d.ts +0 -1
  685. package/dist/plugin-sdk/media-understanding/defaults.d.ts +0 -11
  686. package/dist/plugin-sdk/media-understanding/errors.d.ts +0 -6
  687. package/dist/plugin-sdk/media-understanding/format.d.ts +0 -7
  688. package/dist/plugin-sdk/media-understanding/fs.d.ts +0 -1
  689. package/dist/plugin-sdk/media-understanding/output-extract.d.ts +0 -2
  690. package/dist/plugin-sdk/media-understanding/providers/anthropic/index.d.ts +0 -2
  691. package/dist/plugin-sdk/media-understanding/providers/deepgram/audio.d.ts +0 -1
  692. package/dist/plugin-sdk/media-understanding/providers/deepgram/index.d.ts +0 -2
  693. package/dist/plugin-sdk/media-understanding/providers/google/audio.d.ts +0 -1
  694. package/dist/plugin-sdk/media-understanding/providers/google/index.d.ts +0 -2
  695. package/dist/plugin-sdk/media-understanding/providers/google/video.d.ts +0 -3
  696. package/dist/plugin-sdk/media-understanding/providers/groq/index.d.ts +0 -2
  697. package/dist/plugin-sdk/media-understanding/providers/index.d.ts +0 -4
  698. package/dist/plugin-sdk/media-understanding/providers/minimax/index.d.ts +0 -2
  699. package/dist/plugin-sdk/media-understanding/providers/mistral/index.d.ts +0 -2
  700. package/dist/plugin-sdk/media-understanding/providers/moonshot/index.d.ts +0 -2
  701. package/dist/plugin-sdk/media-understanding/providers/moonshot/video.d.ts +0 -3
  702. package/dist/plugin-sdk/media-understanding/providers/openai/audio.d.ts +0 -1
  703. package/dist/plugin-sdk/media-understanding/providers/openai/index.d.ts +0 -2
  704. package/dist/plugin-sdk/media-understanding/providers/shared.d.ts +0 -20
  705. package/dist/plugin-sdk/media-understanding/providers/zai/index.d.ts +0 -2
  706. package/dist/plugin-sdk/media-understanding/resolve.d.ts +0 -44
  707. package/dist/plugin-sdk/media-understanding/runner.d.ts +0 -34
  708. package/dist/plugin-sdk/media-understanding/runner.entries.d.ts +0 -33
  709. package/dist/plugin-sdk/media-understanding/scope.d.ts +0 -9
  710. package/dist/plugin-sdk/media-understanding/types.d.ts +0 -59
  711. package/dist/plugin-sdk/media-understanding/video.d.ts +0 -2
  712. package/dist/plugin-sdk/utils/mask-api-key.d.ts +0 -1
  713. package/dist/plugin-sdk/utils/run-with-concurrency.d.ts +0 -11
  714. package/dist/plugins-7B167wIj.js +0 -453
  715. package/dist/plugins-BRHOfy1Z.js +0 -455
  716. package/dist/plugins-cli--I43zIaS.js +0 -797
  717. package/dist/plugins-cli-DIxMbY9I.js +0 -801
  718. package/dist/ports-BS8kQkd9.js +0 -96
  719. package/dist/ports-CAqyeQYZ.js +0 -316
  720. package/dist/ports-CTUgXF2d.js +0 -96
  721. package/dist/ports-DqfnVnCw.js +0 -370
  722. package/dist/preflight-CaRJtknt.js +0 -64
  723. package/dist/preflight-DeDRKMx4.js +0 -68
  724. package/dist/program-context-9dv7ClZz.js +0 -474
  725. package/dist/program-wVSvyiD-.js +0 -248
  726. package/dist/prompt-select-styled-BE_4W66Z.js +0 -1672
  727. package/dist/prompt-select-styled-BTPf06Os.js +0 -1669
  728. package/dist/provider-dispatcher-VZWITjmt.js +0 -660
  729. package/dist/provider-dispatcher-zYYGo00g.js +0 -659
  730. package/dist/push-apns-Cj0Ryn18.js +0 -713
  731. package/dist/push-apns-fFfYCqda.js +0 -711
  732. package/dist/pw-ai-CnN2sITD.js +0 -1908
  733. package/dist/pw-ai-fnX3cecw.js +0 -1911
  734. package/dist/qr-cli-CriPg41m.js +0 -349
  735. package/dist/qr-cli-DSURqD0D.js +0 -353
  736. package/dist/redact-snapshot-BecRL_h6.js +0 -2016
  737. package/dist/redact-snapshot-pTdzSrex.js +0 -2016
  738. package/dist/register.agent-B5_1XatO.js +0 -290
  739. package/dist/register.agent-Dba3CYyo.js +0 -1018
  740. package/dist/register.configure-DmwHGsPG.js +0 -128
  741. package/dist/register.configure-DrPlgBqB.js +0 -133
  742. package/dist/register.import-CPQqqdje.js +0 -31
  743. package/dist/register.import-D1UaH1QV.js +0 -29
  744. package/dist/register.maintenance-D76tiF4W.js +0 -501
  745. package/dist/register.maintenance-hUriFBfi.js +0 -499
  746. package/dist/register.message--VzmF3u4.js +0 -685
  747. package/dist/register.message-itNWUdvP.js +0 -689
  748. package/dist/register.onboard-Co8D908b.js +0 -93
  749. package/dist/register.onboard-q8JzWtuv.js +0 -97
  750. package/dist/register.setup-Djc6jZTc.js +0 -113
  751. package/dist/register.setup-hhPii4O7.js +0 -117
  752. package/dist/register.status-health-sessions-C1FhACQB.js +0 -668
  753. package/dist/register.status-health-sessions-DcUegHcH.js +0 -428
  754. package/dist/register.subclis-DAfihpBz.js +0 -267
  755. package/dist/replies-IpiCq1Ht.js +0 -136
  756. package/dist/replies-LSx_XhsP.js +0 -136
  757. package/dist/reply-D0CLqcBY.js +0 -13718
  758. package/dist/reply-Djq8ghfI.js +0 -13715
  759. package/dist/reply-directives-Cz7622Qx.js +0 -182
  760. package/dist/reply-directives-ssnaPNiU.js +0 -182
  761. package/dist/reply-payloads-CQMtrphw.js +0 -527
  762. package/dist/reply-prefix-CWcAZKhE.js +0 -37
  763. package/dist/reply-prefix-Drq7Pf3A.js +0 -37
  764. package/dist/resolve-route-B8uIc2H3.js +0 -249
  765. package/dist/resolve-route-C8ooNlI4.js +0 -249
  766. package/dist/response-prefix-template-DPOggmPO.js +0 -134
  767. package/dist/retry-BdhJlZQI.js +0 -77
  768. package/dist/run-main-B-Cb62fC.js +0 -306
  769. package/dist/runner-DUnmgjJ8.js +0 -2394
  770. package/dist/runner-EobZIrDt.js +0 -2394
  771. package/dist/secure-random-B5qmFc3N.js +0 -44
  772. package/dist/security-cli-05blEYyC.js +0 -482
  773. package/dist/security-cli-DYbt8duB.js +0 -487
  774. package/dist/send-7O3-bRtl.js +0 -547
  775. package/dist/send-9Huf62k3.js +0 -2245
  776. package/dist/send-B9mIJdUo.js +0 -547
  777. package/dist/send-Bj0RXr-a.js +0 -492
  778. package/dist/send-BzkAsn7K.js +0 -29
  779. package/dist/send-CXFhFLP9.js +0 -11
  780. package/dist/send-Ce_BDa8P.js +0 -349
  781. package/dist/send-ChvasRSh.js +0 -1779
  782. package/dist/send-Cl5BhbnF.js +0 -426
  783. package/dist/send-CpebTvM6.js +0 -374
  784. package/dist/send-DWf7BCPe.js +0 -492
  785. package/dist/send-DX8QSuSI.js +0 -1174
  786. package/dist/send-DZRn6PT2.js +0 -332
  787. package/dist/send-Dd2_MykI.js +0 -2245
  788. package/dist/send-IJaUAa8H.js +0 -1776
  789. package/dist/send-vvZXksNU.js +0 -349
  790. package/dist/server-BrzR9JmX.js +0 -206
  791. package/dist/server-_h27-uP_.js +0 -202
  792. package/dist/server-lifecycle-CUdA6Far.js +0 -2437
  793. package/dist/server-lifecycle-DQZWL8iP.js +0 -2437
  794. package/dist/server-node-events-DgB1z2Cx.js +0 -392
  795. package/dist/server-node-events-DtvPfM1I.js +0 -396
  796. package/dist/service-9le8AnC-.js +0 -670
  797. package/dist/service-Drb0kx6I.js +0 -670
  798. package/dist/session-BIAOl5QR.js +0 -170
  799. package/dist/session-Wu00pCn_.js +0 -170
  800. package/dist/session-cost-usage-7plmOKbs.js +0 -627
  801. package/dist/session-cost-usage-CPFxBFUg.js +0 -627
  802. package/dist/session-dirs-CfIrIJxG.js +0 -318
  803. package/dist/session-dirs-DlPpWt5Q.js +0 -318
  804. package/dist/session-utils-Sd9w4vc1.js +0 -622
  805. package/dist/session-utils-iL47hYmZ.js +0 -622
  806. package/dist/sessions-6pKQ3gN3.js +0 -247
  807. package/dist/sessions-ZRmCDdj1.js +0 -2569
  808. package/dist/shell-env-DYZq9PqC.js +0 -163
  809. package/dist/ssrf-B-rF_tZB.js +0 -183
  810. package/dist/ssrf-DJW14Wkh.js +0 -183
  811. package/dist/status-CTRQCXRj.js +0 -1979
  812. package/dist/status-Y67xsH93.js +0 -1983
  813. package/dist/status.update-DlBReI5-.js +0 -449
  814. package/dist/status.update-v7fEQ7R9.js +0 -449
  815. package/dist/store-B5989JkX.js +0 -64
  816. package/dist/store-BgtgYJoX.js +0 -53
  817. package/dist/store-DCrrxHyS.js +0 -2571
  818. package/dist/store-Ql6vAcsg.js +0 -64
  819. package/dist/subagent-registry-BGknZEUI.js +0 -4856
  820. package/dist/subagent-registry-CWeRBjfn.js +0 -4854
  821. package/dist/subsystem-Ct6qOOqZ.js +0 -1079
  822. package/dist/subsystem-PQ64_nsu.js +0 -1136
  823. package/dist/system-cli-CmO-4Rju.js +0 -77
  824. package/dist/system-cli-VBsa18K6.js +0 -73
  825. package/dist/systemd-CqFpK30Y.js +0 -547
  826. package/dist/systemd-fK9AV5bP.js +0 -547
  827. package/dist/systemd-hints-D3rr0j14.js +0 -278
  828. package/dist/systemd-hints-DNOSRaqA.js +0 -278
  829. package/dist/systemd-linger-B907NVVy.js +0 -75
  830. package/dist/systemd-linger-wYksBbM7.js +0 -75
  831. package/dist/tables-Boxa9MJH.js +0 -55
  832. package/dist/tables-CO_kxD0e.js +0 -55
  833. package/dist/tables-WZp8Vt9n.js +0 -55
  834. package/dist/tailnet-CfZhpSnt.js +0 -40
  835. package/dist/tailnet-D0NV0tRJ.js +0 -40
  836. package/dist/tailscale-B__xvMjA.js +0 -230
  837. package/dist/tailscale-q_ZrxUCc.js +0 -230
  838. package/dist/targets-B4rMyQFJ.js +0 -53
  839. package/dist/targets-BHYLCv06.js +0 -2534
  840. package/dist/targets-BjWhDMJM.js +0 -650
  841. package/dist/targets-BnpMZZC_.js +0 -120
  842. package/dist/targets-CHwGDIgO.js +0 -650
  843. package/dist/targets-DIDKlfKI.js +0 -220
  844. package/dist/targets-bqjVeCnF.js +0 -2535
  845. package/dist/targets-mqj9GNg1.js +0 -53
  846. package/dist/tool-display-C0hpLmkw.js +0 -785
  847. package/dist/tool-display-CQTRHo3Z.js +0 -785
  848. package/dist/tool-images-BYY11Gw3.js +0 -263
  849. package/dist/tool-images-CnJ0R8Fo.js +0 -263
  850. package/dist/trash-C0mjnHuW.js +0 -125
  851. package/dist/trash-Cgwc9mLD.js +0 -125
  852. package/dist/tui-9cJnR1dN.js +0 -3282
  853. package/dist/tui-BR3egaFJ.js +0 -3282
  854. package/dist/tui-cli-BYpkhE6J.js +0 -66
  855. package/dist/tui-cli-DndeZyup.js +0 -62
  856. package/dist/update-BJVdkzk7.js +0 -349
  857. package/dist/update-DjI6KTA5.js +0 -349
  858. package/dist/update-cli-B7Rl2Qr2.js +0 -1146
  859. package/dist/update-cli-CFk_jqUm.js +0 -1148
  860. package/dist/usage-CFv4a1Nf.js +0 -5448
  861. package/dist/voice-credentials-D59RcLbl.js +0 -45
  862. package/dist/voice-credentials-fjA7GShF.js +0 -45
  863. package/dist/web-Bs1td8Qw.js +0 -79
  864. package/dist/web-CSiw--Px.js +0 -3070
  865. package/dist/web-jRTtDiNf.js +0 -74
  866. package/dist/webhooks-cli-0yQha2yj.js +0 -334
  867. package/dist/webhooks-cli-ula0bTX-.js +0 -330
  868. package/dist/whatsapp-actions-3NdzsNg1.js +0 -130
  869. package/dist/whatsapp-actions-y_1vjkYY.js +0 -125
  870. package/dist/workspace-BT3X-qCZ.js +0 -449
  871. package/dist/workspace-D5hHXubL.js +0 -447
  872. package/dist/zod-schema-CbqZAIYy.js +0 -2696
  873. package/dist/zod-schema-YGQJEcnj.js +0 -2696
  874. /package/dist/{account-lookup-BOCzCnir.js → account-lookup-CIY_RKhi.js} +0 -0
  875. /package/dist/{account-lookup-C0ndrpt-.js → account-lookup-DGscKBsr.js} +0 -0
  876. /package/dist/{agent-helpers-eEHy5uX2.js → agent-helpers-D83kfcF9.js} +0 -0
  877. /package/dist/{agents.config-BgDBcY4h.js → agents.config-BPe_hkMn.js} +0 -0
  878. /package/dist/{api-Cd_7aESj.js → api-D8QQo5bc.js} +0 -0
  879. /package/dist/{api-DJ_oWYus.js → api-GywrnwRm.js} +0 -0
  880. /package/dist/{argv-BY8EVMTP.js → argv-DW4MYBdJ.js} +0 -0
  881. /package/dist/{bindings-Dr0bGRst.js → bindings-BpL4pISF.js} +0 -0
  882. /package/dist/{brew-CmTYeZk1.js → brew-CBsS-Vq1.js} +0 -0
  883. /package/dist/{brew-V4lMBeE3.js → brew-Clw9vXhE.js} +0 -0
  884. /package/dist/{chat-envelope-CrM0X4sl.js → chat-envelope-CY1yvCc-.js} +0 -0
  885. /package/dist/{chat-envelope-BIujl9Cj.js → chat-envelope-DUMcMMB2.js} +0 -0
  886. /package/dist/{chat-type-CH3W-zKy.js → chat-type-BKe459rw.js} +0 -0
  887. /package/dist/{chat-type-DyovJwCt.js → chat-type-CE6cJOyt.js} +0 -0
  888. /package/dist/{cleanup-utils-CNwlTKyR.js → cleanup-utils-365rf8YN.js} +0 -0
  889. /package/dist/{cleanup-utils-gNzIs9yk.js → cleanup-utils-rqUXvR3Z.js} +0 -0
  890. /package/dist/{cli-name-3MdfbvIR.js → cli-name-7Gb97Vyl.js} +0 -0
  891. /package/dist/{cli-name-CRLBidNP.js → cli-name-Yv30OygA.js} +0 -0
  892. /package/dist/{cli-utils-5ZIfXAfM.js → cli-utils-5W6ugvN5.js} +0 -0
  893. /package/dist/{cli-utils-BUOtyfnU.js → cli-utils-CZJacPS2.js} +0 -0
  894. /package/dist/{client-D5m46AuY.js → client-DQ-Nh-rV.js} +0 -0
  895. /package/dist/{client-DFyI5I0n.js → client-Fi2k2G9Z.js} +0 -0
  896. /package/dist/{command-options-Cn2fc1Of.js → command-options-CXHYeogR.js} +0 -0
  897. /package/dist/{command-options-D2nN4AXX.js → command-options-Cx6evn0x.js} +0 -0
  898. /package/dist/{config-eval-CU2G7a83.js → config-eval-DU_v_3lY.js} +0 -0
  899. /package/dist/{config-eval-BCKpAS_K.js → config-eval-V26Gl6eZ.js} +0 -0
  900. /package/dist/{constants-CRGAZ2ow.js → constants-C7gkSGRE.js} +0 -0
  901. /package/dist/{constants-BAZuhSRm.js → constants-DAiBiWlI.js} +0 -0
  902. /package/dist/{constants-DoYLsBmv.js → constants-DOnQraOP.js} +0 -0
  903. /package/dist/{constants-BBVTjb1j.js → constants-DQxqJVLu.js} +0 -0
  904. /package/dist/{credentials-DMAWNZdV.js → credentials-BHWUBHMd.js} +0 -0
  905. /package/dist/{credentials-Dmc3H-jd.js → credentials-DG0tD6-e.js} +0 -0
  906. /package/dist/{daemon-runtime-CzFI2dPw.js → daemon-runtime-B7Tmba31.js} +0 -0
  907. /package/dist/{daemon-runtime-aQhinwSL.js → daemon-runtime-KyXiP2ib.js} +0 -0
  908. /package/dist/{dangerous-name-matching-BlTBBZns.js → dangerous-name-matching-B4MRPcn-.js} +0 -0
  909. /package/dist/{dangerous-tools-BRmbBvRf.js → dangerous-tools-CIPZZJoN.js} +0 -0
  910. /package/dist/{dangerous-tools-E1i3IoxZ.js → dangerous-tools-D-GNbdpV.js} +0 -0
  911. /package/dist/{fetch-timeout-DBRRPNBi.js → fetch-timeout-CPe2rPLq.js} +0 -0
  912. /package/dist/{fetch-timeout-l_6RdoMw.js → fetch-timeout-DkT3EnRA.js} +0 -0
  913. /package/dist/{file-identity-BnGA6wyc.js → file-identity-C8MIb5lb.js} +0 -0
  914. /package/dist/{format-duration-B-Uv5nOi.js → format-duration-Cd7SCued.js} +0 -0
  915. /package/dist/{format-duration-D1M3Zxu6.js → format-duration-Oj8pTbYL.js} +0 -0
  916. /package/dist/{format-relative-Cywx6ldk.js → format-relative-8dpVUfzZ.js} +0 -0
  917. /package/dist/{format-relative-DcQZUAYl.js → format-relative-BMNeqaxW.js} +0 -0
  918. /package/dist/{health-format-CL2Xq92A.js → health-format-CwLlmYSK.js} +0 -0
  919. /package/dist/{health-format-CVgQD-z9.js → health-format-CycFH5Sj.js} +0 -0
  920. /package/dist/{heartbeat-wake-DLxQm6-U.js → heartbeat-wake-D6Lt5YUk.js} +0 -0
  921. /package/dist/{heartbeat-wake-DjsTDzF3.js → heartbeat-wake-uZkAP-tP.js} +0 -0
  922. /package/dist/{help-format-DM6-OBt-.js → help-format-B0YIbosn.js} +0 -0
  923. /package/dist/{help-format-CJQ7APRn.js → help-format-GeOPYD_A.js} +0 -0
  924. /package/dist/{helpers-BER76F_2.js → helpers-6_MYSJEW.js} +0 -0
  925. /package/dist/{helpers-DSMIGYx2.js → helpers-703bXVlF.js} +0 -0
  926. /package/dist/{helpers-D-r6yhnI.js → helpers-p_u0Gnj_.js} +0 -0
  927. /package/dist/{input-provenance-BgfeDgck.js → input-provenance-C4nlFv5Y.js} +0 -0
  928. /package/dist/{input-provenance-xUsSMOsz.js → input-provenance-duDehu0D.js} +0 -0
  929. /package/dist/{ip-BAhS4rY2.js → ip-BFJnbRh9.js} +0 -0
  930. /package/dist/{ip-BUhsZdJu.js → ip-D0zgNmBV.js} +0 -0
  931. /package/dist/{is-main-BmHYGRhd.js → is-main-BE1Jih91.js} +0 -0
  932. /package/dist/{json-file-B5WEJJye.js → json-file-CsV03dh-.js} +0 -0
  933. /package/dist/{json-file-Dbg7nZg1.js → json-file-CtQKYRLl.js} +0 -0
  934. /package/dist/{json-files-BFGbyEzL.js → json-files-B2yMsppu.js} +0 -0
  935. /package/dist/{json-files-CfhnuGaC.js → json-files-BYH8U7Mx.js} +0 -0
  936. /package/dist/{lanes-4FoQemog.js → lanes-BWL_LwXG.js} +0 -0
  937. /package/dist/{lanes-BhdzrAIa.js → lanes-cHJ5arWg.js} +0 -0
  938. /package/dist/{links-CwTlzaPe.js → links-BFtUmGLH.js} +0 -0
  939. /package/dist/{links-D5vtq30Q.js → links-BNjLUJ9U.js} +0 -0
  940. /package/dist/{location-50gaJF5Z.js → location-BC45kOxc.js} +0 -0
  941. /package/dist/{location-Qo8Ii1zo.js → location-BUhzov-a.js} +0 -0
  942. /package/dist/{logger-IA_Dr_BT.js → logger-1QWMF9Hc.js} +0 -0
  943. /package/dist/{logger-nEdVxm5D.js → logger-BWMPnILd.js} +0 -0
  944. /package/dist/{logger-O6JX52kK.js → logger-Liu31nEU.js} +0 -0
  945. /package/dist/{logging-FctZEleJ.js → logging-CtbzyUjs.js} +0 -0
  946. /package/dist/{logging-BiuZwq5D.js → logging-DJFQvfGD.js} +0 -0
  947. /package/dist/{logging-Bs1VqVFL.js → logging-JiRrQn2_.js} +0 -0
  948. /package/dist/{logging-JZEg5nDp.js → logging-kuFzZMsG.js} +0 -0
  949. /package/dist/{message-channel-tuc9CdEw.js → message-channel-DOyKgFu8.js} +0 -0
  950. /package/dist/{mutable-allowlist-detectors-CtKavajp.js → mutable-allowlist-detectors-4m-Kc8Kn.js} +0 -0
  951. /package/dist/{mutable-allowlist-detectors-TCG6mnbz.js → mutable-allowlist-detectors-BECxOoKX.js} +0 -0
  952. /package/dist/{onboard-config-BxfgUqk6.js → onboard-config-C9so5ggC.js} +0 -0
  953. /package/dist/{onboard-config-DNzlo8Cg.js → onboard-config-oXID97rS.js} +0 -0
  954. /package/dist/{parse-log-line-CT0H1-oQ.js → parse-log-line-BtFI563v.js} +0 -0
  955. /package/dist/{parse-log-line-pij_xhtE.js → parse-log-line-COptqka7.js} +0 -0
  956. /package/dist/{parse-timeout-CvODy9RC.js → parse-timeout-BpphuwYl.js} +0 -0
  957. /package/dist/{path-guards-DOpzcMXz.js → path-guards-DJteVA0d.js} +0 -0
  958. /package/dist/{path-guards-DipYoPVw.js → path-guards-DVRUJZVN.js} +0 -0
  959. /package/dist/plugin-sdk/{media-understanding → stt}/providers/google/inline-data.d.ts +0 -0
  960. /package/dist/{plugins-allowlist-Bcqe9Gd8.js → plugins-allowlist-Clt6dsY6.js} +0 -0
  961. /package/dist/{polls-DQrR-qT3.js → polls-C5xr-8pM.js} +0 -0
  962. /package/dist/{polls-ybwcqkWt.js → polls-DXd67TD8.js} +0 -0
  963. /package/dist/{ports-lsof-CDyv5GJd.js → ports-lsof-xWMTWvMQ.js} +0 -0
  964. /package/dist/{process-scoped-map-BwUkYFQV.js → process-scoped-map-C7KeadUK.js} +0 -0
  965. /package/dist/{process-scoped-map-_zxf_kLz.js → process-scoped-map-CQ1C5MbT.js} +0 -0
  966. /package/dist/{program-context-CG-t6Yp-.js → program-context-LuBAPt4y.js} +0 -0
  967. /package/dist/{progress-DRLmcFiG.js → progress-C-hTn2yV.js} +0 -0
  968. /package/dist/{progress-BOdRbOHD.js → progress-ChmZpgvt.js} +0 -0
  969. /package/dist/{prompt-WEkXwIMT.js → prompt-BXeXEH0o.js} +0 -0
  970. /package/dist/{prompt-BRGfic91.js → prompt-C31r0R5I.js} +0 -0
  971. /package/dist/{prompt-style-B4Cq4PyQ.js → prompt-style-BcM-VSMx.js} +0 -0
  972. /package/dist/{proxy-BMJL0Qog.js → proxy-dRhp8Ykw.js} +0 -0
  973. /package/dist/{pw-ai-state-CwXeO5d0.js → pw-ai-state-CjfcKQoO.js} +0 -0
  974. /package/dist/{pw-ai-state-DaISdsXY.js → pw-ai-state-DfjyEttO.js} +0 -0
  975. /package/dist/{redact-gXuh8MFk.js → redact-D975G-N6.js} +0 -0
  976. /package/dist/{redact-CqWx9rpK.js → redact-Dx1Fue21.js} +0 -0
  977. /package/dist/{redact-identifier-BJOQDEj0.js → redact-identifier-Bqj_YiPd.js} +0 -0
  978. /package/dist/{redact-identifier-DR54qsoT.js → redact-identifier-HyK89Sod.js} +0 -0
  979. /package/dist/{remoteclaw-root-CgNyrbxc.js → remoteclaw-root-B1iQBmbi.js} +0 -0
  980. /package/dist/{remoteclaw-root-u8dAeHID.js → remoteclaw-root-BmYwCzQN.js} +0 -0
  981. /package/dist/{render-CDCvpfhh.js → render-BvFSFJZW.js} +0 -0
  982. /package/dist/{render-CJl4GK1B.js → render-flG67HhW.js} +0 -0
  983. /package/dist/{response-prefix-template-D3ZcJP4E.js → response-prefix-template-DDvbVpx6.js} +0 -0
  984. /package/dist/{retry-cXXk2j6_.js → retry-CByUYDAZ.js} +0 -0
  985. /package/dist/{retry-B19gMxS7.js → retry-oNE3cBeG.js} +0 -0
  986. /package/dist/{runtime-guard-BS55uiSW.js → runtime-guard-CqNug-FG.js} +0 -0
  987. /package/dist/{runtime-guard-CK80eucm.js → runtime-guard-DAHXelsb.js} +0 -0
  988. /package/dist/{runtime-status-BhW7hP_U.js → runtime-status-CM4rzyfO.js} +0 -0
  989. /package/dist/{runtime-status-hFVEC3wO.js → runtime-status-DJYthOLz.js} +0 -0
  990. /package/dist/{secret-equal-CJzes24Z.js → secret-equal-1-dwi8DL.js} +0 -0
  991. /package/dist/{secret-equal-CQAmGfGc.js → secret-equal-CXJEZiWb.js} +0 -0
  992. /package/dist/{secure-random-B3f7Ri2X.js → secure-random-Ba4Y5xG5.js} +0 -0
  993. /package/dist/{secure-random-BkZFG9cd.js → secure-random-C6AVByhV.js} +0 -0
  994. /package/dist/{stagger-B-_Wnofy.js → stagger-CjeisVRF.js} +0 -0
  995. /package/dist/{stagger-B2ORDHsP.js → stagger-vkvpUmOz.js} +0 -0
  996. /package/dist/{status-C6YNwimj.js → status-DNLnVQZ4.js} +0 -0
  997. /package/dist/{status-yrDGXYZM.js → status-DZhl73dM.js} +0 -0
  998. /package/dist/{strip-inbound-meta-0cvL6itU.js → strip-inbound-meta-C3Cwe_ZO.js} +0 -0
  999. /package/dist/{strip-inbound-meta-DjKcSFaW.js → strip-inbound-meta-DuDjnGjC.js} +0 -0
  1000. /package/dist/{table-ByMyHTh_.js → table-B9zSN_7D.js} +0 -0
  1001. /package/dist/{table-C-dba-5-.js → table-j8Ayarot.js} +0 -0
  1002. /package/dist/{target-errors-DJVRKFcU.js → target-errors-ChjvOMuV.js} +0 -0
  1003. /package/dist/{target-errors-GZXDqlUu.js → target-errors-Dn4aykSV.js} +0 -0
  1004. /package/dist/{targets-B_d_1z3N.js → targets-BtGRUQMa.js} +0 -0
  1005. /package/dist/{targets-DOJXjN1U.js → targets-CE4AYRI9.js} +0 -0
  1006. /package/dist/{targets-D01MJGnh.js → targets-DlufWCmy.js} +0 -0
  1007. /package/dist/{targets-WSwPflb6.js → targets-akvAerZF.js} +0 -0
  1008. /package/dist/{text-format-DarxU3JH.js → text-format-VSogn9Yq.js} +0 -0
  1009. /package/dist/{text-format-mr5bZq0f.js → text-format-xeHt9ywT.js} +0 -0
  1010. /package/dist/{thinking-BqJmU6Zp.js → thinking-B171Rc3-.js} +0 -0
  1011. /package/dist/{tokens-C8yGxAcR.js → tokens-B-jmvNR9.js} +0 -0
  1012. /package/dist/{tokens-DAFBx5qr.js → tokens-kTLGxaAF.js} +0 -0
  1013. /package/dist/{usage-BXi79Rq6.js → usage-CRJFqYf8.js} +0 -0
  1014. /package/dist/{usage-C1lHaofV.js → usage-Txvb0Iq2.js} +0 -0
  1015. /package/dist/{usage-format-CD5jsZY1.js → usage-format-70DvrseE.js} +0 -0
  1016. /package/dist/{usage-format-CRVpDVj1.js → usage-format-Bs8DkQtr.js} +0 -0
  1017. /package/dist/{widearea-dns-C-0P7TRi.js → widearea-dns-BOgHvO4O.js} +0 -0
  1018. /package/dist/{widearea-dns-DFZMcfLf.js → widearea-dns-CGhfClCr.js} +0 -0
  1019. /package/dist/{workspace-BJCKO8Ns.js → workspace-DhUqtMK_.js} +0 -0
  1020. /package/dist/{wsl-kFaeW76c.js → wsl-Cs-gowFJ.js} +0 -0
@@ -0,0 +1,2571 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
+ import { v as resolveRequiredHomeDir } from "./paths-BTaH3rLn.js";
3
+ import { f as normalizeE164 } from "./utils-C5daYcFn.js";
4
+ import { t as createSubsystemLogger } from "./subsystem-m7RSGQoR.js";
5
+ import { c as normalizeMainKey, g as normalizeOptionalAccountId, l as resolveAgentIdFromSessionKey, r as buildAgentMainSessionKey, s as normalizeAgentId, t as DEFAULT_AGENT_ID } from "./session-key-CgKWfjoZ.js";
6
+ import { c as normalizeMessageChannel, s as listDeliverableMessageChannels } from "./message-channel-EMCYRaxk.js";
7
+ import { i as loadConfig } from "./config-C_WcTz_O.js";
8
+ import { d as parseByteSize, u as parseDurationMs } from "./zod-schema-CCUbW_Si.js";
9
+ import { a as normalizeHyphenSlug, t as getChannelDock } from "./dock-ByrYnLiz.js";
10
+ import { r as normalizeChannelId } from "./plugins-DExsdlTp.js";
11
+ import { t as normalizeChatType } from "./chat-type-CE6cJOyt.js";
12
+ import { n as isPidAlive, t as resolveProcessScopedMap } from "./process-scoped-map-CQ1C5MbT.js";
13
+ import { a as hasToolCall, c as resolveSessionFilePath, d as resolveSessionTranscriptPathInDir, f as resolveSessionTranscriptsDir, h as validateSessionId, i as extractToolCallNames, l as resolveSessionFilePathOptions, m as resolveStorePath, n as stripMessageIdHints, o as SAFE_SESSION_ID_RE, p as resolveSessionTranscriptsDirForAgent, s as resolveDefaultSessionStorePath, t as stripEnvelope, u as resolveSessionTranscriptPath } from "./chat-envelope-DUMcMMB2.js";
14
+ import { n as resolveConversationLabel } from "./conversation-label-HuHoShPF.js";
15
+ import { n as hasInterSessionUserProvenance } from "./input-provenance-C4nlFv5Y.js";
16
+ import { t as stripInboundMetadata } from "./strip-inbound-meta-C3Cwe_ZO.js";
17
+ import fs from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import fs$1 from "node:fs/promises";
21
+ import crypto from "node:crypto";
22
+
23
+ //#region src/agents/session-write-lock.ts
24
+ const CLEANUP_SIGNALS = [
25
+ "SIGINT",
26
+ "SIGTERM",
27
+ "SIGQUIT",
28
+ "SIGABRT"
29
+ ];
30
+ const CLEANUP_STATE_KEY = Symbol.for("remoteclaw.sessionWriteLockCleanupState");
31
+ const HELD_LOCKS_KEY = Symbol.for("remoteclaw.sessionWriteLockHeldLocks");
32
+ const WATCHDOG_STATE_KEY = Symbol.for("remoteclaw.sessionWriteLockWatchdogState");
33
+ const DEFAULT_STALE_MS = 1800 * 1e3;
34
+ const DEFAULT_MAX_HOLD_MS = 300 * 1e3;
35
+ const DEFAULT_WATCHDOG_INTERVAL_MS = 6e4;
36
+ const DEFAULT_TIMEOUT_GRACE_MS = 120 * 1e3;
37
+ const HELD_LOCKS = resolveProcessScopedMap(HELD_LOCKS_KEY);
38
+ function resolveCleanupState() {
39
+ const proc = process;
40
+ if (!proc[CLEANUP_STATE_KEY]) proc[CLEANUP_STATE_KEY] = {
41
+ registered: false,
42
+ cleanupHandlers: /* @__PURE__ */ new Map()
43
+ };
44
+ return proc[CLEANUP_STATE_KEY];
45
+ }
46
+ function resolveWatchdogState() {
47
+ const proc = process;
48
+ if (!proc[WATCHDOG_STATE_KEY]) proc[WATCHDOG_STATE_KEY] = {
49
+ started: false,
50
+ intervalMs: DEFAULT_WATCHDOG_INTERVAL_MS
51
+ };
52
+ return proc[WATCHDOG_STATE_KEY];
53
+ }
54
+ function resolvePositiveMs(value, fallback, opts = {}) {
55
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) return fallback;
56
+ if (value === Number.POSITIVE_INFINITY) return opts.allowInfinity ? value : fallback;
57
+ if (!Number.isFinite(value)) return fallback;
58
+ return value;
59
+ }
60
+ async function releaseHeldLock(normalizedSessionFile, held, opts = {}) {
61
+ if (HELD_LOCKS.get(normalizedSessionFile) !== held) return false;
62
+ if (opts.force) held.count = 0;
63
+ else {
64
+ held.count -= 1;
65
+ if (held.count > 0) return false;
66
+ }
67
+ if (held.releasePromise) {
68
+ await held.releasePromise.catch(() => void 0);
69
+ return true;
70
+ }
71
+ HELD_LOCKS.delete(normalizedSessionFile);
72
+ held.releasePromise = (async () => {
73
+ try {
74
+ await held.handle.close();
75
+ } catch {}
76
+ try {
77
+ await fs$1.rm(held.lockPath, { force: true });
78
+ } catch {}
79
+ })();
80
+ try {
81
+ await held.releasePromise;
82
+ return true;
83
+ } finally {
84
+ held.releasePromise = void 0;
85
+ }
86
+ }
87
+ /**
88
+ * Synchronously release all held locks.
89
+ * Used during process exit when async operations aren't reliable.
90
+ */
91
+ function releaseAllLocksSync() {
92
+ for (const [sessionFile, held] of HELD_LOCKS) {
93
+ try {
94
+ if (typeof held.handle.close === "function") held.handle.close().catch(() => {});
95
+ } catch {}
96
+ try {
97
+ fs.rmSync(held.lockPath, { force: true });
98
+ } catch {}
99
+ HELD_LOCKS.delete(sessionFile);
100
+ }
101
+ }
102
+ async function runLockWatchdogCheck(nowMs = Date.now()) {
103
+ let released = 0;
104
+ for (const [sessionFile, held] of HELD_LOCKS.entries()) {
105
+ const heldForMs = nowMs - held.acquiredAt;
106
+ if (heldForMs <= held.maxHoldMs) continue;
107
+ console.warn(`[session-write-lock] releasing lock held for ${heldForMs}ms (max=${held.maxHoldMs}ms): ${held.lockPath}`);
108
+ if (await releaseHeldLock(sessionFile, held, { force: true })) released += 1;
109
+ }
110
+ return released;
111
+ }
112
+ function ensureWatchdogStarted(intervalMs) {
113
+ const watchdogState = resolveWatchdogState();
114
+ if (watchdogState.started) return;
115
+ watchdogState.started = true;
116
+ watchdogState.intervalMs = intervalMs;
117
+ watchdogState.timer = setInterval(() => {
118
+ runLockWatchdogCheck().catch(() => {});
119
+ }, intervalMs);
120
+ watchdogState.timer.unref?.();
121
+ }
122
+ function handleTerminationSignal(signal) {
123
+ releaseAllLocksSync();
124
+ const cleanupState = resolveCleanupState();
125
+ if (process.listenerCount(signal) === 1) {
126
+ const handler = cleanupState.cleanupHandlers.get(signal);
127
+ if (handler) {
128
+ process.off(signal, handler);
129
+ cleanupState.cleanupHandlers.delete(signal);
130
+ }
131
+ try {
132
+ process.kill(process.pid, signal);
133
+ } catch {}
134
+ }
135
+ }
136
+ function registerCleanupHandlers() {
137
+ const cleanupState = resolveCleanupState();
138
+ if (!cleanupState.registered) {
139
+ cleanupState.registered = true;
140
+ process.on("exit", () => {
141
+ releaseAllLocksSync();
142
+ });
143
+ }
144
+ ensureWatchdogStarted(DEFAULT_WATCHDOG_INTERVAL_MS);
145
+ for (const signal of CLEANUP_SIGNALS) {
146
+ if (cleanupState.cleanupHandlers.has(signal)) continue;
147
+ try {
148
+ const handler = () => handleTerminationSignal(signal);
149
+ cleanupState.cleanupHandlers.set(signal, handler);
150
+ process.on(signal, handler);
151
+ } catch {}
152
+ }
153
+ }
154
+ async function readLockPayload(lockPath) {
155
+ try {
156
+ const raw = await fs$1.readFile(lockPath, "utf8");
157
+ const parsed = JSON.parse(raw);
158
+ const payload = {};
159
+ if (typeof parsed.pid === "number") payload.pid = parsed.pid;
160
+ if (typeof parsed.createdAt === "string") payload.createdAt = parsed.createdAt;
161
+ return payload;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+ function inspectLockPayload(payload, staleMs, nowMs) {
167
+ const pid = typeof payload?.pid === "number" ? payload.pid : null;
168
+ const pidAlive = pid !== null ? isPidAlive(pid) : false;
169
+ const createdAt = typeof payload?.createdAt === "string" ? payload.createdAt : null;
170
+ const createdAtMs = createdAt ? Date.parse(createdAt) : NaN;
171
+ const ageMs = Number.isFinite(createdAtMs) ? Math.max(0, nowMs - createdAtMs) : null;
172
+ const staleReasons = [];
173
+ if (pid === null) staleReasons.push("missing-pid");
174
+ else if (!pidAlive) staleReasons.push("dead-pid");
175
+ if (ageMs === null) staleReasons.push("invalid-createdAt");
176
+ else if (ageMs > staleMs) staleReasons.push("too-old");
177
+ return {
178
+ pid,
179
+ pidAlive,
180
+ createdAt,
181
+ ageMs,
182
+ stale: staleReasons.length > 0,
183
+ staleReasons
184
+ };
185
+ }
186
+ function lockInspectionNeedsMtimeStaleFallback(details) {
187
+ return details.stale && details.staleReasons.every((reason) => reason === "missing-pid" || reason === "invalid-createdAt");
188
+ }
189
+ async function shouldReclaimContendedLockFile(lockPath, details, staleMs, nowMs) {
190
+ if (!details.stale) return false;
191
+ if (!lockInspectionNeedsMtimeStaleFallback(details)) return true;
192
+ try {
193
+ const stat = await fs$1.stat(lockPath);
194
+ return Math.max(0, nowMs - stat.mtimeMs) > staleMs;
195
+ } catch (error) {
196
+ return error?.code !== "ENOENT";
197
+ }
198
+ }
199
+ async function cleanStaleLockFiles(params) {
200
+ const sessionsDir = path.resolve(params.sessionsDir);
201
+ const staleMs = resolvePositiveMs(params.staleMs, DEFAULT_STALE_MS);
202
+ const removeStale = params.removeStale !== false;
203
+ const nowMs = params.nowMs ?? Date.now();
204
+ let entries = [];
205
+ try {
206
+ entries = await fs$1.readdir(sessionsDir, { withFileTypes: true });
207
+ } catch (err) {
208
+ if (err.code === "ENOENT") return {
209
+ locks: [],
210
+ cleaned: []
211
+ };
212
+ throw err;
213
+ }
214
+ const locks = [];
215
+ const cleaned = [];
216
+ const lockEntries = entries.filter((entry) => entry.name.endsWith(".jsonl.lock")).toSorted((a, b) => a.name.localeCompare(b.name));
217
+ for (const entry of lockEntries) {
218
+ const lockPath = path.join(sessionsDir, entry.name);
219
+ const lockInfo = {
220
+ lockPath,
221
+ ...inspectLockPayload(await readLockPayload(lockPath), staleMs, nowMs),
222
+ removed: false
223
+ };
224
+ if (lockInfo.stale && removeStale) {
225
+ await fs$1.rm(lockPath, { force: true });
226
+ lockInfo.removed = true;
227
+ cleaned.push(lockInfo);
228
+ params.log?.warn?.(`removed stale session lock: ${lockPath} (${lockInfo.staleReasons.join(", ") || "unknown"})`);
229
+ }
230
+ locks.push(lockInfo);
231
+ }
232
+ return {
233
+ locks,
234
+ cleaned
235
+ };
236
+ }
237
+ async function acquireSessionWriteLock(params) {
238
+ registerCleanupHandlers();
239
+ const timeoutMs = resolvePositiveMs(params.timeoutMs, 1e4, { allowInfinity: true });
240
+ const staleMs = resolvePositiveMs(params.staleMs, DEFAULT_STALE_MS);
241
+ const maxHoldMs = resolvePositiveMs(params.maxHoldMs, DEFAULT_MAX_HOLD_MS);
242
+ const sessionFile = path.resolve(params.sessionFile);
243
+ const sessionDir = path.dirname(sessionFile);
244
+ await fs$1.mkdir(sessionDir, { recursive: true });
245
+ let normalizedDir = sessionDir;
246
+ try {
247
+ normalizedDir = await fs$1.realpath(sessionDir);
248
+ } catch {}
249
+ const normalizedSessionFile = path.join(normalizedDir, path.basename(sessionFile));
250
+ const lockPath = `${normalizedSessionFile}.lock`;
251
+ const allowReentrant = params.allowReentrant ?? true;
252
+ const held = HELD_LOCKS.get(normalizedSessionFile);
253
+ if (allowReentrant && held) {
254
+ held.count += 1;
255
+ return { release: async () => {
256
+ await releaseHeldLock(normalizedSessionFile, held);
257
+ } };
258
+ }
259
+ const startedAt = Date.now();
260
+ let attempt = 0;
261
+ while (Date.now() - startedAt < timeoutMs) {
262
+ attempt += 1;
263
+ let handle = null;
264
+ try {
265
+ handle = await fs$1.open(lockPath, "wx");
266
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
267
+ await handle.writeFile(JSON.stringify({
268
+ pid: process.pid,
269
+ createdAt
270
+ }, null, 2), "utf8");
271
+ const createdHeld = {
272
+ count: 1,
273
+ handle,
274
+ lockPath,
275
+ acquiredAt: Date.now(),
276
+ maxHoldMs
277
+ };
278
+ HELD_LOCKS.set(normalizedSessionFile, createdHeld);
279
+ return { release: async () => {
280
+ await releaseHeldLock(normalizedSessionFile, createdHeld);
281
+ } };
282
+ } catch (err) {
283
+ if (handle) {
284
+ try {
285
+ await handle.close();
286
+ } catch {}
287
+ try {
288
+ await fs$1.rm(lockPath, { force: true });
289
+ } catch {}
290
+ }
291
+ if (err.code !== "EEXIST") throw err;
292
+ const payload = await readLockPayload(lockPath);
293
+ const nowMs = Date.now();
294
+ if (await shouldReclaimContendedLockFile(lockPath, inspectLockPayload(payload, staleMs, nowMs), staleMs, nowMs)) {
295
+ await fs$1.rm(lockPath, { force: true });
296
+ continue;
297
+ }
298
+ const delay = Math.min(1e3, 50 * attempt);
299
+ await new Promise((r) => setTimeout(r, delay));
300
+ }
301
+ }
302
+ const payload = await readLockPayload(lockPath);
303
+ const owner = typeof payload?.pid === "number" ? `pid=${payload.pid}` : "unknown";
304
+ throw new Error(`session file locked (timeout ${timeoutMs}ms): ${owner} ${lockPath}`);
305
+ }
306
+ const __testing = {
307
+ cleanupSignals: [...CLEANUP_SIGNALS],
308
+ handleTerminationSignal,
309
+ releaseAllLocksSync,
310
+ runLockWatchdogCheck
311
+ };
312
+
313
+ //#endregion
314
+ //#region src/config/sessions/group.ts
315
+ const getGroupSurfaces = () => new Set([...listDeliverableMessageChannels(), "webchat"]);
316
+ function normalizeGroupLabel(raw) {
317
+ return normalizeHyphenSlug(raw);
318
+ }
319
+ function shortenGroupId(value) {
320
+ const trimmed = value?.trim() ?? "";
321
+ if (!trimmed) return "";
322
+ if (trimmed.length <= 14) return trimmed;
323
+ return `${trimmed.slice(0, 6)}...${trimmed.slice(-4)}`;
324
+ }
325
+ function buildGroupDisplayName(params) {
326
+ const providerKey = (params.provider?.trim().toLowerCase() || "group").trim();
327
+ const groupChannel = params.groupChannel?.trim();
328
+ const space = params.space?.trim();
329
+ const subject = params.subject?.trim();
330
+ const detail = (groupChannel && space ? `${space}${groupChannel.startsWith("#") ? "" : "#"}${groupChannel}` : groupChannel || subject || space || "") || "";
331
+ const fallbackId = params.id?.trim() || params.key;
332
+ const rawLabel = detail || fallbackId;
333
+ let token = normalizeGroupLabel(rawLabel);
334
+ if (!token) token = normalizeGroupLabel(shortenGroupId(rawLabel));
335
+ if (!params.groupChannel && token.startsWith("#")) token = token.replace(/^#+/, "");
336
+ if (token && !/^[@#]/.test(token) && !token.startsWith("g-") && !token.includes("#")) token = `g-${token}`;
337
+ return token ? `${providerKey}:${token}` : providerKey;
338
+ }
339
+ function resolveGroupSessionKey(ctx) {
340
+ const from = typeof ctx.From === "string" ? ctx.From.trim() : "";
341
+ const chatType = ctx.ChatType?.trim().toLowerCase();
342
+ const normalizedChatType = chatType === "channel" ? "channel" : chatType === "group" ? "group" : void 0;
343
+ const isWhatsAppGroupId = from.toLowerCase().endsWith("@g.us");
344
+ if (!(normalizedChatType === "group" || normalizedChatType === "channel" || from.includes(":group:") || from.includes(":channel:") || isWhatsAppGroupId)) return null;
345
+ const providerHint = ctx.Provider?.trim().toLowerCase();
346
+ const parts = from.split(":").filter(Boolean);
347
+ const head = parts[0]?.trim().toLowerCase() ?? "";
348
+ const headIsSurface = head ? getGroupSurfaces().has(head) : false;
349
+ const provider = headIsSurface ? head : providerHint ?? (isWhatsAppGroupId ? "whatsapp" : void 0);
350
+ if (!provider) return null;
351
+ const second = parts[1]?.trim().toLowerCase();
352
+ const secondIsKind = second === "group" || second === "channel";
353
+ const kind = secondIsKind ? second : from.includes(":channel:") || normalizedChatType === "channel" ? "channel" : "group";
354
+ const finalId = (headIsSurface ? secondIsKind ? parts.slice(2).join(":") : parts.slice(1).join(":") : from).trim().toLowerCase();
355
+ if (!finalId) return null;
356
+ return {
357
+ key: `${provider}:${kind}:${finalId}`,
358
+ channel: provider,
359
+ id: finalId,
360
+ chatType: kind === "channel" ? "channel" : "group"
361
+ };
362
+ }
363
+
364
+ //#endregion
365
+ //#region src/config/sessions/artifacts.ts
366
+ const ARCHIVE_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d{3})?Z$/;
367
+ const LEGACY_STORE_BACKUP_RE = /^sessions\.json\.bak\.\d+$/;
368
+ function hasArchiveSuffix(fileName, reason) {
369
+ const marker = `.${reason}.`;
370
+ const index = fileName.lastIndexOf(marker);
371
+ if (index < 0) return false;
372
+ const raw = fileName.slice(index + marker.length);
373
+ return ARCHIVE_TIMESTAMP_RE.test(raw);
374
+ }
375
+ function isSessionArchiveArtifactName(fileName) {
376
+ if (LEGACY_STORE_BACKUP_RE.test(fileName)) return true;
377
+ return hasArchiveSuffix(fileName, "deleted") || hasArchiveSuffix(fileName, "reset") || hasArchiveSuffix(fileName, "bak");
378
+ }
379
+ function isPrimarySessionTranscriptFileName(fileName) {
380
+ if (fileName === "sessions.json") return false;
381
+ if (!fileName.endsWith(".jsonl")) return false;
382
+ return !isSessionArchiveArtifactName(fileName);
383
+ }
384
+ function formatSessionArchiveTimestamp(nowMs = Date.now()) {
385
+ return new Date(nowMs).toISOString().replaceAll(":", "-");
386
+ }
387
+ function restoreSessionArchiveTimestamp(raw) {
388
+ const [datePart, timePart] = raw.split("T");
389
+ if (!datePart || !timePart) return raw;
390
+ return `${datePart}T${timePart.replace(/-/g, ":")}`;
391
+ }
392
+ function parseSessionArchiveTimestamp(fileName, reason) {
393
+ const marker = `.${reason}.`;
394
+ const index = fileName.lastIndexOf(marker);
395
+ if (index < 0) return null;
396
+ const raw = fileName.slice(index + marker.length);
397
+ if (!raw) return null;
398
+ if (!ARCHIVE_TIMESTAMP_RE.test(raw)) return null;
399
+ const timestamp = Date.parse(restoreSessionArchiveTimestamp(raw));
400
+ return Number.isNaN(timestamp) ? null : timestamp;
401
+ }
402
+
403
+ //#endregion
404
+ //#region src/config/sessions/metadata.ts
405
+ const mergeOrigin = (existing, next) => {
406
+ if (!existing && !next) return;
407
+ const merged = existing ? { ...existing } : {};
408
+ if (next?.label) merged.label = next.label;
409
+ if (next?.provider) merged.provider = next.provider;
410
+ if (next?.surface) merged.surface = next.surface;
411
+ if (next?.chatType) merged.chatType = next.chatType;
412
+ if (next?.from) merged.from = next.from;
413
+ if (next?.to) merged.to = next.to;
414
+ if (next?.accountId) merged.accountId = next.accountId;
415
+ if (next?.threadId != null && next.threadId !== "") merged.threadId = next.threadId;
416
+ return Object.keys(merged).length > 0 ? merged : void 0;
417
+ };
418
+ function deriveSessionOrigin(ctx) {
419
+ const label = resolveConversationLabel(ctx)?.trim();
420
+ const provider = normalizeMessageChannel(typeof ctx.OriginatingChannel === "string" && ctx.OriginatingChannel || ctx.Surface || ctx.Provider);
421
+ const surface = ctx.Surface?.trim().toLowerCase();
422
+ const chatType = normalizeChatType(ctx.ChatType) ?? void 0;
423
+ const from = ctx.From?.trim();
424
+ const to = (typeof ctx.OriginatingTo === "string" ? ctx.OriginatingTo : ctx.To)?.trim() ?? void 0;
425
+ const accountId = ctx.AccountId?.trim();
426
+ const threadId = ctx.MessageThreadId ?? void 0;
427
+ const origin = {};
428
+ if (label) origin.label = label;
429
+ if (provider) origin.provider = provider;
430
+ if (surface) origin.surface = surface;
431
+ if (chatType) origin.chatType = chatType;
432
+ if (from) origin.from = from;
433
+ if (to) origin.to = to;
434
+ if (accountId) origin.accountId = accountId;
435
+ if (threadId != null && threadId !== "") origin.threadId = threadId;
436
+ return Object.keys(origin).length > 0 ? origin : void 0;
437
+ }
438
+ function snapshotSessionOrigin(entry) {
439
+ if (!entry?.origin) return;
440
+ return { ...entry.origin };
441
+ }
442
+ function deriveGroupSessionPatch(params) {
443
+ const resolution = params.groupResolution ?? resolveGroupSessionKey(params.ctx);
444
+ if (!resolution?.channel) return null;
445
+ const channel = resolution.channel;
446
+ const subject = params.ctx.GroupSubject?.trim();
447
+ const space = params.ctx.GroupSpace?.trim();
448
+ const explicitChannel = params.ctx.GroupChannel?.trim();
449
+ const normalizedChannel = normalizeChannelId(channel);
450
+ const isChannelProvider = Boolean(normalizedChannel && getChannelDock(normalizedChannel)?.capabilities.chatTypes.includes("channel"));
451
+ const nextGroupChannel = explicitChannel ?? ((resolution.chatType === "channel" || isChannelProvider) && subject && subject.startsWith("#") ? subject : void 0);
452
+ const nextSubject = nextGroupChannel ? void 0 : subject;
453
+ const patch = {
454
+ chatType: resolution.chatType ?? "group",
455
+ channel,
456
+ groupId: resolution.id
457
+ };
458
+ if (nextSubject) patch.subject = nextSubject;
459
+ if (nextGroupChannel) patch.groupChannel = nextGroupChannel;
460
+ if (space) patch.space = space;
461
+ const displayName = buildGroupDisplayName({
462
+ provider: channel,
463
+ subject: nextSubject ?? params.existing?.subject,
464
+ groupChannel: nextGroupChannel ?? params.existing?.groupChannel,
465
+ space: space ?? params.existing?.space,
466
+ id: resolution.id,
467
+ key: params.sessionKey
468
+ });
469
+ if (displayName) patch.displayName = displayName;
470
+ return patch;
471
+ }
472
+ function deriveSessionMetaPatch(params) {
473
+ const groupPatch = deriveGroupSessionPatch(params);
474
+ const origin = deriveSessionOrigin(params.ctx);
475
+ if (!groupPatch && !origin) return null;
476
+ const patch = groupPatch ? { ...groupPatch } : {};
477
+ const mergedOrigin = mergeOrigin(params.existing?.origin, origin);
478
+ if (mergedOrigin) patch.origin = mergedOrigin;
479
+ return Object.keys(patch).length > 0 ? patch : null;
480
+ }
481
+
482
+ //#endregion
483
+ //#region src/config/sessions/main-session.ts
484
+ function resolveMainSessionKey(cfg) {
485
+ if (cfg?.session?.scope === "global") return "global";
486
+ const agents = cfg?.agents?.list ?? [];
487
+ return buildAgentMainSessionKey({
488
+ agentId: normalizeAgentId(agents.find((agent) => agent?.default)?.id ?? agents[0]?.id ?? DEFAULT_AGENT_ID),
489
+ mainKey: normalizeMainKey(cfg?.session?.mainKey)
490
+ });
491
+ }
492
+ function resolveMainSessionKeyFromConfig() {
493
+ return resolveMainSessionKey(loadConfig());
494
+ }
495
+ function resolveAgentMainSessionKey(params) {
496
+ const mainKey = normalizeMainKey(params.cfg?.session?.mainKey);
497
+ return buildAgentMainSessionKey({
498
+ agentId: params.agentId,
499
+ mainKey
500
+ });
501
+ }
502
+ function resolveExplicitAgentSessionKey(params) {
503
+ const agentId = params.agentId?.trim();
504
+ if (!agentId) return;
505
+ return resolveAgentMainSessionKey({
506
+ cfg: params.cfg,
507
+ agentId
508
+ });
509
+ }
510
+ function canonicalizeMainSessionAlias(params) {
511
+ const raw = params.sessionKey.trim();
512
+ if (!raw) return raw;
513
+ const agentId = normalizeAgentId(params.agentId);
514
+ const mainKey = normalizeMainKey(params.cfg?.session?.mainKey);
515
+ const agentMainSessionKey = buildAgentMainSessionKey({
516
+ agentId,
517
+ mainKey
518
+ });
519
+ const agentMainAliasKey = buildAgentMainSessionKey({
520
+ agentId,
521
+ mainKey: "main"
522
+ });
523
+ const isMainAlias = raw === "main" || raw === mainKey || raw === agentMainSessionKey || raw === agentMainAliasKey;
524
+ if (params.cfg?.session?.scope === "global" && isMainAlias) return "global";
525
+ if (isMainAlias) return agentMainSessionKey;
526
+ return raw;
527
+ }
528
+
529
+ //#endregion
530
+ //#region src/config/sessions/types.ts
531
+ function normalizeRuntimeField(value) {
532
+ const trimmed = value?.trim();
533
+ return trimmed ? trimmed : void 0;
534
+ }
535
+ function normalizeSessionRuntimeModelFields(entry) {
536
+ const normalizedModel = normalizeRuntimeField(entry.model);
537
+ const normalizedProvider = normalizeRuntimeField(entry.modelProvider);
538
+ let next = entry;
539
+ if (!normalizedModel) {
540
+ if (entry.model !== void 0 || entry.modelProvider !== void 0) {
541
+ next = { ...next };
542
+ delete next.model;
543
+ delete next.modelProvider;
544
+ }
545
+ return next;
546
+ }
547
+ if (entry.model !== normalizedModel) {
548
+ if (next === entry) next = { ...next };
549
+ next.model = normalizedModel;
550
+ }
551
+ if (!normalizedProvider) {
552
+ if (entry.modelProvider !== void 0) {
553
+ if (next === entry) next = { ...next };
554
+ delete next.modelProvider;
555
+ }
556
+ return next;
557
+ }
558
+ if (entry.modelProvider !== normalizedProvider) {
559
+ if (next === entry) next = { ...next };
560
+ next.modelProvider = normalizedProvider;
561
+ }
562
+ return next;
563
+ }
564
+ function mergeSessionEntry(existing, patch) {
565
+ const sessionId = patch.sessionId ?? existing?.sessionId ?? crypto.randomUUID();
566
+ const updatedAt = Math.max(existing?.updatedAt ?? 0, patch.updatedAt ?? 0, Date.now());
567
+ if (!existing) return normalizeSessionRuntimeModelFields({
568
+ ...patch,
569
+ sessionId,
570
+ updatedAt
571
+ });
572
+ const next = {
573
+ ...existing,
574
+ ...patch,
575
+ sessionId,
576
+ updatedAt
577
+ };
578
+ if (Object.hasOwn(patch, "model") && !Object.hasOwn(patch, "modelProvider")) {
579
+ const patchedModel = normalizeRuntimeField(patch.model);
580
+ const existingModel = normalizeRuntimeField(existing.model);
581
+ if (patchedModel && patchedModel !== existingModel) delete next.modelProvider;
582
+ }
583
+ return normalizeSessionRuntimeModelFields(next);
584
+ }
585
+ function resolveFreshSessionTotalTokens(entry) {
586
+ const total = entry?.totalTokens;
587
+ if (typeof total !== "number" || !Number.isFinite(total) || total < 0) return;
588
+ if (entry?.totalTokensFresh === false) return;
589
+ return total;
590
+ }
591
+ function isSessionTotalTokensFresh(entry) {
592
+ return resolveFreshSessionTotalTokens(entry) !== void 0;
593
+ }
594
+ const DEFAULT_RESET_TRIGGER = "/new";
595
+ const DEFAULT_RESET_TRIGGERS = ["/new", "/reset"];
596
+ const DEFAULT_IDLE_MINUTES = 60;
597
+
598
+ //#endregion
599
+ //#region src/config/sessions/reset.ts
600
+ const DEFAULT_RESET_MODE = "daily";
601
+ const DEFAULT_RESET_AT_HOUR = 4;
602
+ const THREAD_SESSION_MARKERS = [":thread:", ":topic:"];
603
+ const GROUP_SESSION_MARKERS = [":group:", ":channel:"];
604
+ function isThreadSessionKey(sessionKey) {
605
+ const normalized = (sessionKey ?? "").toLowerCase();
606
+ if (!normalized) return false;
607
+ return THREAD_SESSION_MARKERS.some((marker) => normalized.includes(marker));
608
+ }
609
+ function resolveSessionResetType(params) {
610
+ if (params.isThread || isThreadSessionKey(params.sessionKey)) return "thread";
611
+ if (params.isGroup) return "group";
612
+ const normalized = (params.sessionKey ?? "").toLowerCase();
613
+ if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) return "group";
614
+ return "direct";
615
+ }
616
+ function resolveThreadFlag(params) {
617
+ if (params.messageThreadId != null) return true;
618
+ if (params.threadLabel?.trim()) return true;
619
+ if (params.threadStarterBody?.trim()) return true;
620
+ if (params.parentSessionKey?.trim()) return true;
621
+ return isThreadSessionKey(params.sessionKey);
622
+ }
623
+ function resolveDailyResetAtMs(now, atHour) {
624
+ const normalizedAtHour = normalizeResetAtHour(atHour);
625
+ const resetAt = new Date(now);
626
+ resetAt.setHours(normalizedAtHour, 0, 0, 0);
627
+ if (now < resetAt.getTime()) resetAt.setDate(resetAt.getDate() - 1);
628
+ return resetAt.getTime();
629
+ }
630
+ function resolveSessionResetPolicy(params) {
631
+ const sessionCfg = params.sessionCfg;
632
+ const baseReset = params.resetOverride ?? sessionCfg?.reset;
633
+ const typeReset = params.resetOverride ? void 0 : sessionCfg?.resetByType?.[params.resetType] ?? (params.resetType === "direct" ? (sessionCfg?.resetByType)?.dm : void 0);
634
+ const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType);
635
+ const legacyIdleMinutes = params.resetOverride ? void 0 : sessionCfg?.idleMinutes;
636
+ const mode = typeReset?.mode ?? baseReset?.mode ?? (!hasExplicitReset && legacyIdleMinutes != null ? "idle" : DEFAULT_RESET_MODE);
637
+ const atHour = normalizeResetAtHour(typeReset?.atHour ?? baseReset?.atHour ?? DEFAULT_RESET_AT_HOUR);
638
+ const idleMinutesRaw = typeReset?.idleMinutes ?? baseReset?.idleMinutes ?? legacyIdleMinutes;
639
+ let idleMinutes;
640
+ if (idleMinutesRaw != null) {
641
+ const normalized = Math.floor(idleMinutesRaw);
642
+ if (Number.isFinite(normalized)) idleMinutes = Math.max(normalized, 1);
643
+ } else if (mode === "idle") idleMinutes = DEFAULT_IDLE_MINUTES;
644
+ return {
645
+ mode,
646
+ atHour,
647
+ idleMinutes
648
+ };
649
+ }
650
+ function resolveChannelResetConfig(params) {
651
+ const resetByChannel = params.sessionCfg?.resetByChannel;
652
+ if (!resetByChannel) return;
653
+ const normalized = normalizeMessageChannel(params.channel);
654
+ const fallback = params.channel?.trim().toLowerCase();
655
+ const key = normalized ?? fallback;
656
+ if (!key) return;
657
+ return resetByChannel[key] ?? resetByChannel[key.toLowerCase()];
658
+ }
659
+ function evaluateSessionFreshness(params) {
660
+ const dailyResetAt = params.policy.mode === "daily" ? resolveDailyResetAtMs(params.now, params.policy.atHour) : void 0;
661
+ const idleExpiresAt = params.policy.idleMinutes != null ? params.updatedAt + params.policy.idleMinutes * 6e4 : void 0;
662
+ const staleDaily = dailyResetAt != null && params.updatedAt < dailyResetAt;
663
+ const staleIdle = idleExpiresAt != null && params.now > idleExpiresAt;
664
+ return {
665
+ fresh: !(staleDaily || staleIdle),
666
+ dailyResetAt,
667
+ idleExpiresAt
668
+ };
669
+ }
670
+ function normalizeResetAtHour(value) {
671
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_RESET_AT_HOUR;
672
+ const normalized = Math.floor(value);
673
+ if (!Number.isFinite(normalized)) return DEFAULT_RESET_AT_HOUR;
674
+ if (normalized < 0) return 0;
675
+ if (normalized > 23) return 23;
676
+ return normalized;
677
+ }
678
+
679
+ //#endregion
680
+ //#region src/config/sessions/session-key.ts
681
+ function deriveSessionKey(scope, ctx) {
682
+ if (scope === "global") return "global";
683
+ const resolvedGroup = resolveGroupSessionKey(ctx);
684
+ if (resolvedGroup) return resolvedGroup.key;
685
+ return (ctx.From ? normalizeE164(ctx.From) : "") || "unknown";
686
+ }
687
+ /**
688
+ * Resolve the session key with a canonical direct-chat bucket (default: "main").
689
+ * All non-group direct chats collapse to this bucket; groups stay isolated.
690
+ */
691
+ function resolveSessionKey(scope, ctx, mainKey) {
692
+ const explicit = ctx.SessionKey?.trim();
693
+ if (explicit) return explicit.toLowerCase();
694
+ const raw = deriveSessionKey(scope, ctx);
695
+ if (scope === "global") return raw;
696
+ const canonical = buildAgentMainSessionKey({
697
+ agentId: DEFAULT_AGENT_ID,
698
+ mainKey: normalizeMainKey(mainKey)
699
+ });
700
+ if (!(raw.includes(":group:") || raw.includes(":channel:"))) return canonical;
701
+ return `agent:${DEFAULT_AGENT_ID}:${raw}`;
702
+ }
703
+
704
+ //#endregion
705
+ //#region src/sessions/transcript-events.ts
706
+ const SESSION_TRANSCRIPT_LISTENERS = /* @__PURE__ */ new Set();
707
+ function emitSessionTranscriptUpdate(sessionFile) {
708
+ const trimmed = sessionFile.trim();
709
+ if (!trimmed) return;
710
+ const update = { sessionFile: trimmed };
711
+ for (const listener of SESSION_TRANSCRIPT_LISTENERS) listener(update);
712
+ }
713
+
714
+ //#endregion
715
+ //#region src/config/sessions/constants.ts
716
+ /** Session transcript format version (matches pi-coding-agent SessionManager v3 layout). */
717
+ const CURRENT_SESSION_VERSION = 3;
718
+
719
+ //#endregion
720
+ //#region src/config/sessions/session-file.ts
721
+ async function resolveAndPersistSessionFile(params) {
722
+ const { sessionId, sessionKey, sessionStore, storePath } = params;
723
+ const baseEntry = params.sessionEntry ?? sessionStore[sessionKey] ?? {
724
+ sessionId,
725
+ updatedAt: Date.now()
726
+ };
727
+ const fallbackSessionFile = params.fallbackSessionFile?.trim();
728
+ const sessionFile = resolveSessionFilePath(sessionId, !baseEntry.sessionFile && fallbackSessionFile ? {
729
+ ...baseEntry,
730
+ sessionFile: fallbackSessionFile
731
+ } : baseEntry, {
732
+ agentId: params.agentId,
733
+ sessionsDir: params.sessionsDir
734
+ });
735
+ const persistedEntry = {
736
+ ...baseEntry,
737
+ sessionId,
738
+ updatedAt: Date.now(),
739
+ sessionFile
740
+ };
741
+ if (baseEntry.sessionId !== sessionId || baseEntry.sessionFile !== sessionFile) {
742
+ sessionStore[sessionKey] = persistedEntry;
743
+ await updateSessionStore(storePath, (store) => {
744
+ store[sessionKey] = {
745
+ ...store[sessionKey],
746
+ ...persistedEntry
747
+ };
748
+ }, params.activeSessionKey ? { activeSessionKey: params.activeSessionKey } : void 0);
749
+ return {
750
+ sessionFile,
751
+ sessionEntry: persistedEntry
752
+ };
753
+ }
754
+ sessionStore[sessionKey] = persistedEntry;
755
+ return {
756
+ sessionFile,
757
+ sessionEntry: persistedEntry
758
+ };
759
+ }
760
+
761
+ //#endregion
762
+ //#region src/config/sessions/transcript.ts
763
+ function stripQuery(value) {
764
+ const noHash = value.split("#")[0] ?? value;
765
+ return noHash.split("?")[0] ?? noHash;
766
+ }
767
+ function extractFileNameFromMediaUrl(value) {
768
+ const trimmed = value.trim();
769
+ if (!trimmed) return null;
770
+ const cleaned = stripQuery(trimmed);
771
+ try {
772
+ const parsed = new URL(cleaned);
773
+ const base = path.basename(parsed.pathname);
774
+ if (!base) return null;
775
+ try {
776
+ return decodeURIComponent(base);
777
+ } catch {
778
+ return base;
779
+ }
780
+ } catch {
781
+ const base = path.basename(cleaned);
782
+ if (!base || base === "/" || base === ".") return null;
783
+ return base;
784
+ }
785
+ }
786
+ function resolveMirroredTranscriptText(params) {
787
+ const mediaUrls = params.mediaUrls?.filter((url) => url && url.trim()) ?? [];
788
+ if (mediaUrls.length > 0) {
789
+ const names = mediaUrls.map((url) => extractFileNameFromMediaUrl(url)).filter((name) => Boolean(name && name.trim()));
790
+ if (names.length > 0) return names.join(", ");
791
+ return "media";
792
+ }
793
+ const trimmed = (params.text ?? "").trim();
794
+ return trimmed ? trimmed : null;
795
+ }
796
+ async function ensureSessionHeader(params) {
797
+ if (fs.existsSync(params.sessionFile)) return;
798
+ await fs.promises.mkdir(path.dirname(params.sessionFile), { recursive: true });
799
+ const header = {
800
+ type: "session",
801
+ version: CURRENT_SESSION_VERSION,
802
+ id: params.sessionId,
803
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
804
+ cwd: process.cwd()
805
+ };
806
+ await fs.promises.writeFile(params.sessionFile, `${JSON.stringify(header)}\n`, {
807
+ encoding: "utf-8",
808
+ mode: 384
809
+ });
810
+ }
811
+ async function appendAssistantMessageToSessionTranscript(params) {
812
+ const sessionKey = params.sessionKey.trim();
813
+ if (!sessionKey) return {
814
+ ok: false,
815
+ reason: "missing sessionKey"
816
+ };
817
+ const mirrorText = resolveMirroredTranscriptText({
818
+ text: params.text,
819
+ mediaUrls: params.mediaUrls
820
+ });
821
+ if (!mirrorText) return {
822
+ ok: false,
823
+ reason: "empty text"
824
+ };
825
+ const storePath = params.storePath ?? resolveDefaultSessionStorePath(params.agentId);
826
+ const store = loadSessionStore(storePath, { skipCache: true });
827
+ const entry = store[sessionKey];
828
+ if (!entry?.sessionId) return {
829
+ ok: false,
830
+ reason: `unknown sessionKey: ${sessionKey}`
831
+ };
832
+ let sessionFile;
833
+ try {
834
+ sessionFile = (await resolveAndPersistSessionFile({
835
+ sessionId: entry.sessionId,
836
+ sessionKey,
837
+ sessionStore: store,
838
+ storePath,
839
+ sessionEntry: entry,
840
+ agentId: params.agentId,
841
+ sessionsDir: path.dirname(storePath)
842
+ })).sessionFile;
843
+ } catch (err) {
844
+ return {
845
+ ok: false,
846
+ reason: err instanceof Error ? err.message : String(err)
847
+ };
848
+ }
849
+ await ensureSessionHeader({
850
+ sessionFile,
851
+ sessionId: entry.sessionId
852
+ });
853
+ const line = {
854
+ type: "message",
855
+ message: {
856
+ role: "assistant",
857
+ content: [{
858
+ type: "text",
859
+ text: mirrorText
860
+ }],
861
+ api: "openai-responses",
862
+ provider: "remoteclaw",
863
+ model: "delivery-mirror",
864
+ usage: {
865
+ input: 0,
866
+ output: 0,
867
+ cacheRead: 0,
868
+ cacheWrite: 0,
869
+ totalTokens: 0,
870
+ cost: {
871
+ input: 0,
872
+ output: 0,
873
+ cacheRead: 0,
874
+ cacheWrite: 0,
875
+ total: 0
876
+ }
877
+ },
878
+ stopReason: "stop",
879
+ timestamp: Date.now()
880
+ }
881
+ };
882
+ await fs.promises.appendFile(sessionFile, `${JSON.stringify(line)}\n`, "utf-8");
883
+ emitSessionTranscriptUpdate(sessionFile);
884
+ return {
885
+ ok: true,
886
+ sessionFile
887
+ };
888
+ }
889
+
890
+ //#endregion
891
+ //#region src/config/sessions/delivery-info.ts
892
+ /**
893
+ * Extract deliveryContext and threadId from a sessionKey.
894
+ * Supports both :thread: (most channels) and :topic: (Telegram).
895
+ */
896
+ function parseSessionThreadInfo(sessionKey) {
897
+ if (!sessionKey) return {
898
+ baseSessionKey: void 0,
899
+ threadId: void 0
900
+ };
901
+ const topicIndex = sessionKey.lastIndexOf(":topic:");
902
+ const threadIndex = sessionKey.lastIndexOf(":thread:");
903
+ const markerIndex = Math.max(topicIndex, threadIndex);
904
+ const marker = topicIndex > threadIndex ? ":topic:" : ":thread:";
905
+ return {
906
+ baseSessionKey: markerIndex === -1 ? sessionKey : sessionKey.slice(0, markerIndex),
907
+ threadId: (markerIndex === -1 ? void 0 : sessionKey.slice(markerIndex + marker.length))?.trim() || void 0
908
+ };
909
+ }
910
+ function extractDeliveryInfo(sessionKey) {
911
+ const { baseSessionKey, threadId } = parseSessionThreadInfo(sessionKey);
912
+ if (!sessionKey || !baseSessionKey) return {
913
+ deliveryContext: void 0,
914
+ threadId
915
+ };
916
+ let deliveryContext;
917
+ try {
918
+ const store = loadSessionStore(resolveStorePath(loadConfig().session?.store));
919
+ let entry = store[sessionKey];
920
+ if (!entry?.deliveryContext && baseSessionKey !== sessionKey) entry = store[baseSessionKey];
921
+ if (entry?.deliveryContext) deliveryContext = {
922
+ channel: entry.deliveryContext.channel,
923
+ to: entry.deliveryContext.to,
924
+ accountId: entry.deliveryContext.accountId
925
+ };
926
+ } catch {}
927
+ return {
928
+ deliveryContext,
929
+ threadId
930
+ };
931
+ }
932
+
933
+ //#endregion
934
+ //#region src/config/sessions/disk-budget.ts
935
+ const NOOP_LOGGER = {
936
+ warn: () => {},
937
+ info: () => {}
938
+ };
939
+ function canonicalizePathForComparison$1(filePath) {
940
+ const resolved = path.resolve(filePath);
941
+ try {
942
+ return fs.realpathSync(resolved);
943
+ } catch {
944
+ return resolved;
945
+ }
946
+ }
947
+ function measureStoreBytes(store) {
948
+ return Buffer.byteLength(JSON.stringify(store, null, 2), "utf-8");
949
+ }
950
+ function measureStoreEntryChunkBytes(key, entry) {
951
+ const singleEntryStore = JSON.stringify({ [key]: entry }, null, 2);
952
+ if (!singleEntryStore.startsWith("{\n") || !singleEntryStore.endsWith("\n}")) return measureStoreBytes({ [key]: entry }) - 4;
953
+ const chunk = singleEntryStore.slice(2, -2);
954
+ return Buffer.byteLength(chunk, "utf-8");
955
+ }
956
+ function buildStoreEntryChunkSizeMap(store) {
957
+ const out = /* @__PURE__ */ new Map();
958
+ for (const [key, entry] of Object.entries(store)) out.set(key, measureStoreEntryChunkBytes(key, entry));
959
+ return out;
960
+ }
961
+ function getEntryUpdatedAt$1(entry) {
962
+ if (!entry) return 0;
963
+ const updatedAt = entry.updatedAt;
964
+ return Number.isFinite(updatedAt) ? updatedAt : 0;
965
+ }
966
+ function buildSessionIdRefCounts(store) {
967
+ const counts = /* @__PURE__ */ new Map();
968
+ for (const entry of Object.values(store)) {
969
+ const sessionId = entry?.sessionId;
970
+ if (!sessionId) continue;
971
+ counts.set(sessionId, (counts.get(sessionId) ?? 0) + 1);
972
+ }
973
+ return counts;
974
+ }
975
+ function resolveSessionTranscriptPathForEntry(params) {
976
+ if (!params.entry.sessionId) return null;
977
+ try {
978
+ const resolved = resolveSessionFilePath(params.entry.sessionId, params.entry, { sessionsDir: params.sessionsDir });
979
+ const resolvedSessionsDir = canonicalizePathForComparison$1(params.sessionsDir);
980
+ const resolvedPath = canonicalizePathForComparison$1(resolved);
981
+ const relative = path.relative(resolvedSessionsDir, resolvedPath);
982
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return null;
983
+ return resolvedPath;
984
+ } catch {
985
+ return null;
986
+ }
987
+ }
988
+ function resolveReferencedSessionTranscriptPaths(params) {
989
+ const referenced = /* @__PURE__ */ new Set();
990
+ for (const entry of Object.values(params.store)) {
991
+ const resolved = resolveSessionTranscriptPathForEntry({
992
+ sessionsDir: params.sessionsDir,
993
+ entry
994
+ });
995
+ if (resolved) referenced.add(canonicalizePathForComparison$1(resolved));
996
+ }
997
+ return referenced;
998
+ }
999
+ async function readSessionsDirFiles(sessionsDir) {
1000
+ const dirEntries = await fs.promises.readdir(sessionsDir, { withFileTypes: true }).catch(() => []);
1001
+ const files = [];
1002
+ for (const dirent of dirEntries) {
1003
+ if (!dirent.isFile()) continue;
1004
+ const filePath = path.join(sessionsDir, dirent.name);
1005
+ const stat = await fs.promises.stat(filePath).catch(() => null);
1006
+ if (!stat?.isFile()) continue;
1007
+ files.push({
1008
+ path: filePath,
1009
+ canonicalPath: canonicalizePathForComparison$1(filePath),
1010
+ name: dirent.name,
1011
+ size: stat.size,
1012
+ mtimeMs: stat.mtimeMs
1013
+ });
1014
+ }
1015
+ return files;
1016
+ }
1017
+ async function removeFileIfExists(filePath) {
1018
+ const stat = await fs.promises.stat(filePath).catch(() => null);
1019
+ if (!stat?.isFile()) return 0;
1020
+ await fs.promises.rm(filePath, { force: true }).catch(() => void 0);
1021
+ return stat.size;
1022
+ }
1023
+ async function removeFileForBudget(params) {
1024
+ const resolvedPath = path.resolve(params.filePath);
1025
+ const canonicalPath = params.canonicalPath ?? canonicalizePathForComparison$1(resolvedPath);
1026
+ if (params.dryRun) {
1027
+ if (params.simulatedRemovedPaths.has(canonicalPath)) return 0;
1028
+ const size = params.fileSizesByPath.get(canonicalPath) ?? 0;
1029
+ if (size <= 0) return 0;
1030
+ params.simulatedRemovedPaths.add(canonicalPath);
1031
+ return size;
1032
+ }
1033
+ return removeFileIfExists(resolvedPath);
1034
+ }
1035
+ async function enforceSessionDiskBudget(params) {
1036
+ const maxBytes = params.maintenance.maxDiskBytes;
1037
+ const highWaterBytes = params.maintenance.highWaterBytes;
1038
+ if (maxBytes == null || highWaterBytes == null) return null;
1039
+ const log = params.log ?? NOOP_LOGGER;
1040
+ const dryRun = params.dryRun === true;
1041
+ const sessionsDir = path.dirname(params.storePath);
1042
+ const files = await readSessionsDirFiles(sessionsDir);
1043
+ const fileSizesByPath = new Map(files.map((file) => [file.canonicalPath, file.size]));
1044
+ const simulatedRemovedPaths = /* @__PURE__ */ new Set();
1045
+ const resolvedStorePath = canonicalizePathForComparison$1(params.storePath);
1046
+ const storeFile = files.find((file) => file.canonicalPath === resolvedStorePath);
1047
+ let projectedStoreBytes = measureStoreBytes(params.store);
1048
+ let total = files.reduce((sum, file) => sum + file.size, 0) - (storeFile?.size ?? 0) + projectedStoreBytes;
1049
+ const totalBefore = total;
1050
+ if (total <= maxBytes) return {
1051
+ totalBytesBefore: totalBefore,
1052
+ totalBytesAfter: total,
1053
+ removedFiles: 0,
1054
+ removedEntries: 0,
1055
+ freedBytes: 0,
1056
+ maxBytes,
1057
+ highWaterBytes,
1058
+ overBudget: false
1059
+ };
1060
+ if (params.warnOnly) {
1061
+ log.warn("session disk budget exceeded (warn-only mode)", {
1062
+ sessionsDir,
1063
+ totalBytes: total,
1064
+ maxBytes,
1065
+ highWaterBytes
1066
+ });
1067
+ return {
1068
+ totalBytesBefore: totalBefore,
1069
+ totalBytesAfter: total,
1070
+ removedFiles: 0,
1071
+ removedEntries: 0,
1072
+ freedBytes: 0,
1073
+ maxBytes,
1074
+ highWaterBytes,
1075
+ overBudget: true
1076
+ };
1077
+ }
1078
+ let removedFiles = 0;
1079
+ let removedEntries = 0;
1080
+ let freedBytes = 0;
1081
+ const referencedPaths = resolveReferencedSessionTranscriptPaths({
1082
+ sessionsDir,
1083
+ store: params.store
1084
+ });
1085
+ const removableFileQueue = files.filter((file) => isSessionArchiveArtifactName(file.name) || isPrimarySessionTranscriptFileName(file.name) && !referencedPaths.has(file.canonicalPath)).toSorted((a, b) => a.mtimeMs - b.mtimeMs);
1086
+ for (const file of removableFileQueue) {
1087
+ if (total <= highWaterBytes) break;
1088
+ const deletedBytes = await removeFileForBudget({
1089
+ filePath: file.path,
1090
+ canonicalPath: file.canonicalPath,
1091
+ dryRun,
1092
+ fileSizesByPath,
1093
+ simulatedRemovedPaths
1094
+ });
1095
+ if (deletedBytes <= 0) continue;
1096
+ total -= deletedBytes;
1097
+ freedBytes += deletedBytes;
1098
+ removedFiles += 1;
1099
+ }
1100
+ if (total > highWaterBytes) {
1101
+ const activeSessionKey = params.activeSessionKey?.trim().toLowerCase();
1102
+ const sessionIdRefCounts = buildSessionIdRefCounts(params.store);
1103
+ const entryChunkBytesByKey = buildStoreEntryChunkSizeMap(params.store);
1104
+ const keys = Object.keys(params.store).toSorted((a, b) => {
1105
+ return getEntryUpdatedAt$1(params.store[a]) - getEntryUpdatedAt$1(params.store[b]);
1106
+ });
1107
+ for (const key of keys) {
1108
+ if (total <= highWaterBytes) break;
1109
+ if (activeSessionKey && key.trim().toLowerCase() === activeSessionKey) continue;
1110
+ const entry = params.store[key];
1111
+ if (!entry) continue;
1112
+ const previousProjectedBytes = projectedStoreBytes;
1113
+ delete params.store[key];
1114
+ const chunkBytes = entryChunkBytesByKey.get(key);
1115
+ entryChunkBytesByKey.delete(key);
1116
+ if (typeof chunkBytes === "number" && Number.isFinite(chunkBytes) && chunkBytes >= 0) projectedStoreBytes = Math.max(2, projectedStoreBytes - (chunkBytes + 2));
1117
+ else projectedStoreBytes = measureStoreBytes(params.store);
1118
+ total += projectedStoreBytes - previousProjectedBytes;
1119
+ removedEntries += 1;
1120
+ const sessionId = entry.sessionId;
1121
+ if (!sessionId) continue;
1122
+ const nextRefCount = (sessionIdRefCounts.get(sessionId) ?? 1) - 1;
1123
+ if (nextRefCount > 0) {
1124
+ sessionIdRefCounts.set(sessionId, nextRefCount);
1125
+ continue;
1126
+ }
1127
+ sessionIdRefCounts.delete(sessionId);
1128
+ const transcriptPath = resolveSessionTranscriptPathForEntry({
1129
+ sessionsDir,
1130
+ entry
1131
+ });
1132
+ if (!transcriptPath) continue;
1133
+ const deletedBytes = await removeFileForBudget({
1134
+ filePath: transcriptPath,
1135
+ dryRun,
1136
+ fileSizesByPath,
1137
+ simulatedRemovedPaths
1138
+ });
1139
+ if (deletedBytes <= 0) continue;
1140
+ total -= deletedBytes;
1141
+ freedBytes += deletedBytes;
1142
+ removedFiles += 1;
1143
+ }
1144
+ }
1145
+ if (!dryRun) {
1146
+ if (total > highWaterBytes) log.warn("session disk budget still above high-water target after cleanup", {
1147
+ sessionsDir,
1148
+ totalBytes: total,
1149
+ maxBytes,
1150
+ highWaterBytes,
1151
+ removedFiles,
1152
+ removedEntries
1153
+ });
1154
+ else if (removedFiles > 0 || removedEntries > 0) log.info("applied session disk budget cleanup", {
1155
+ sessionsDir,
1156
+ totalBytesBefore: totalBefore,
1157
+ totalBytesAfter: total,
1158
+ maxBytes,
1159
+ highWaterBytes,
1160
+ removedFiles,
1161
+ removedEntries
1162
+ });
1163
+ }
1164
+ return {
1165
+ totalBytesBefore: totalBefore,
1166
+ totalBytesAfter: total,
1167
+ removedFiles,
1168
+ removedEntries,
1169
+ freedBytes,
1170
+ maxBytes,
1171
+ highWaterBytes,
1172
+ overBudget: true
1173
+ };
1174
+ }
1175
+
1176
+ //#endregion
1177
+ //#region src/config/sessions.ts
1178
+ var sessions_exports = /* @__PURE__ */ __exportAll({
1179
+ DEFAULT_IDLE_MINUTES: () => DEFAULT_IDLE_MINUTES,
1180
+ DEFAULT_RESET_AT_HOUR: () => DEFAULT_RESET_AT_HOUR,
1181
+ DEFAULT_RESET_MODE: () => DEFAULT_RESET_MODE,
1182
+ DEFAULT_RESET_TRIGGER: () => DEFAULT_RESET_TRIGGER,
1183
+ DEFAULT_RESET_TRIGGERS: () => DEFAULT_RESET_TRIGGERS,
1184
+ SAFE_SESSION_ID_RE: () => SAFE_SESSION_ID_RE,
1185
+ appendAssistantMessageToSessionTranscript: () => appendAssistantMessageToSessionTranscript,
1186
+ buildGroupDisplayName: () => buildGroupDisplayName,
1187
+ canonicalizeMainSessionAlias: () => canonicalizeMainSessionAlias,
1188
+ capEntryCount: () => capEntryCount,
1189
+ clearSessionStoreCacheForTest: () => clearSessionStoreCacheForTest,
1190
+ deriveGroupSessionPatch: () => deriveGroupSessionPatch,
1191
+ deriveSessionKey: () => deriveSessionKey,
1192
+ deriveSessionMetaPatch: () => deriveSessionMetaPatch,
1193
+ deriveSessionOrigin: () => deriveSessionOrigin,
1194
+ enforceSessionDiskBudget: () => enforceSessionDiskBudget,
1195
+ evaluateSessionFreshness: () => evaluateSessionFreshness,
1196
+ extractDeliveryInfo: () => extractDeliveryInfo,
1197
+ formatSessionArchiveTimestamp: () => formatSessionArchiveTimestamp,
1198
+ getActiveSessionMaintenanceWarning: () => getActiveSessionMaintenanceWarning,
1199
+ getSessionStoreLockQueueSizeForTest: () => getSessionStoreLockQueueSizeForTest,
1200
+ isPrimarySessionTranscriptFileName: () => isPrimarySessionTranscriptFileName,
1201
+ isSessionArchiveArtifactName: () => isSessionArchiveArtifactName,
1202
+ isSessionTotalTokensFresh: () => isSessionTotalTokensFresh,
1203
+ isThreadSessionKey: () => isThreadSessionKey,
1204
+ loadSessionStore: () => loadSessionStore,
1205
+ mergeSessionEntry: () => mergeSessionEntry,
1206
+ normalizeSessionRuntimeModelFields: () => normalizeSessionRuntimeModelFields,
1207
+ parseSessionArchiveTimestamp: () => parseSessionArchiveTimestamp,
1208
+ parseSessionThreadInfo: () => parseSessionThreadInfo,
1209
+ pruneStaleEntries: () => pruneStaleEntries,
1210
+ readSessionUpdatedAt: () => readSessionUpdatedAt,
1211
+ recordSessionMetaFromInbound: () => recordSessionMetaFromInbound,
1212
+ resolveAgentIdFromSessionKey: () => resolveAgentIdFromSessionKey,
1213
+ resolveAgentMainSessionKey: () => resolveAgentMainSessionKey,
1214
+ resolveAndPersistSessionFile: () => resolveAndPersistSessionFile,
1215
+ resolveChannelResetConfig: () => resolveChannelResetConfig,
1216
+ resolveDailyResetAtMs: () => resolveDailyResetAtMs,
1217
+ resolveDefaultSessionStorePath: () => resolveDefaultSessionStorePath,
1218
+ resolveExplicitAgentSessionKey: () => resolveExplicitAgentSessionKey,
1219
+ resolveFreshSessionTotalTokens: () => resolveFreshSessionTotalTokens,
1220
+ resolveGroupSessionKey: () => resolveGroupSessionKey,
1221
+ resolveMainSessionKey: () => resolveMainSessionKey,
1222
+ resolveMainSessionKeyFromConfig: () => resolveMainSessionKeyFromConfig,
1223
+ resolveMaintenanceConfig: () => resolveMaintenanceConfig,
1224
+ resolveMirroredTranscriptText: () => resolveMirroredTranscriptText,
1225
+ resolveSessionFilePath: () => resolveSessionFilePath,
1226
+ resolveSessionFilePathOptions: () => resolveSessionFilePathOptions,
1227
+ resolveSessionKey: () => resolveSessionKey,
1228
+ resolveSessionResetPolicy: () => resolveSessionResetPolicy,
1229
+ resolveSessionResetType: () => resolveSessionResetType,
1230
+ resolveSessionTranscriptPath: () => resolveSessionTranscriptPath,
1231
+ resolveSessionTranscriptPathInDir: () => resolveSessionTranscriptPathInDir,
1232
+ resolveSessionTranscriptsDir: () => resolveSessionTranscriptsDir,
1233
+ resolveSessionTranscriptsDirForAgent: () => resolveSessionTranscriptsDirForAgent,
1234
+ resolveStorePath: () => resolveStorePath,
1235
+ resolveThreadFlag: () => resolveThreadFlag,
1236
+ rotateSessionFile: () => rotateSessionFile,
1237
+ saveSessionStore: () => saveSessionStore,
1238
+ snapshotSessionOrigin: () => snapshotSessionOrigin,
1239
+ updateLastRoute: () => updateLastRoute,
1240
+ updateSessionStore: () => updateSessionStore,
1241
+ updateSessionStoreEntry: () => updateSessionStoreEntry,
1242
+ validateSessionId: () => validateSessionId,
1243
+ withSessionStoreLockForTest: () => withSessionStoreLockForTest
1244
+ });
1245
+
1246
+ //#endregion
1247
+ //#region src/utils/directive-tags.ts
1248
+ const AUDIO_TAG_RE = /\[\[\s*audio_as_voice\s*\]\]/gi;
1249
+ const REPLY_TAG_RE = /\[\[\s*(?:reply_to_current|reply_to\s*:\s*([^\]\n]+))\s*\]\]/gi;
1250
+ function normalizeDirectiveWhitespace(text) {
1251
+ return text.replace(/[ \t]+/g, " ").replace(/[ \t]*\n[ \t]*/g, "\n").trim();
1252
+ }
1253
+ function stripInlineDirectiveTagsForDisplay(text) {
1254
+ if (!text) return {
1255
+ text,
1256
+ changed: false
1257
+ };
1258
+ const stripped = text.replace(AUDIO_TAG_RE, "").replace(REPLY_TAG_RE, "");
1259
+ return {
1260
+ text: stripped,
1261
+ changed: stripped !== text
1262
+ };
1263
+ }
1264
+ function isMessageTextPart(part) {
1265
+ return Boolean(part) && part?.type === "text" && typeof part.text === "string";
1266
+ }
1267
+ /**
1268
+ * Strips inline directive tags from message text blocks while preserving message shape.
1269
+ * Empty post-strip text stays empty-string to preserve caller semantics.
1270
+ */
1271
+ function stripInlineDirectiveTagsFromMessageForDisplay(message) {
1272
+ if (!message) return message;
1273
+ if (!Array.isArray(message.content)) return message;
1274
+ const cleaned = message.content.map((part) => {
1275
+ if (!part || typeof part !== "object") return part;
1276
+ const record = part;
1277
+ if (!isMessageTextPart(record)) return part;
1278
+ return {
1279
+ ...record,
1280
+ text: stripInlineDirectiveTagsForDisplay(record.text).text
1281
+ };
1282
+ });
1283
+ return {
1284
+ ...message,
1285
+ content: cleaned
1286
+ };
1287
+ }
1288
+ function parseInlineDirectives(text, options = {}) {
1289
+ const { currentMessageId, stripAudioTag = true, stripReplyTags = true } = options;
1290
+ if (!text) return {
1291
+ text: "",
1292
+ audioAsVoice: false,
1293
+ replyToCurrent: false,
1294
+ hasAudioTag: false,
1295
+ hasReplyTag: false
1296
+ };
1297
+ let cleaned = text;
1298
+ let audioAsVoice = false;
1299
+ let hasAudioTag = false;
1300
+ let hasReplyTag = false;
1301
+ let sawCurrent = false;
1302
+ let lastExplicitId;
1303
+ cleaned = cleaned.replace(AUDIO_TAG_RE, (match) => {
1304
+ audioAsVoice = true;
1305
+ hasAudioTag = true;
1306
+ return stripAudioTag ? " " : match;
1307
+ });
1308
+ cleaned = cleaned.replace(REPLY_TAG_RE, (match, idRaw) => {
1309
+ hasReplyTag = true;
1310
+ if (idRaw === void 0) sawCurrent = true;
1311
+ else {
1312
+ const id = idRaw.trim();
1313
+ if (id) lastExplicitId = id;
1314
+ }
1315
+ return stripReplyTags ? " " : match;
1316
+ });
1317
+ cleaned = normalizeDirectiveWhitespace(cleaned);
1318
+ const replyToId = lastExplicitId ?? (sawCurrent ? currentMessageId?.trim() || void 0 : void 0);
1319
+ return {
1320
+ text: cleaned,
1321
+ audioAsVoice,
1322
+ replyToId,
1323
+ replyToExplicitId: lastExplicitId,
1324
+ replyToCurrent: sawCurrent,
1325
+ hasAudioTag,
1326
+ hasReplyTag
1327
+ };
1328
+ }
1329
+
1330
+ //#endregion
1331
+ //#region src/gateway/chat-sanitize.ts
1332
+ function stripEnvelopeFromContentWithRole(content, stripUserEnvelope) {
1333
+ let changed = false;
1334
+ return {
1335
+ content: content.map((item) => {
1336
+ if (!item || typeof item !== "object") return item;
1337
+ const entry = item;
1338
+ if (entry.type !== "text" || typeof entry.text !== "string") return item;
1339
+ const inboundStripped = stripInboundMetadata(entry.text);
1340
+ const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
1341
+ if (stripped === entry.text) return item;
1342
+ changed = true;
1343
+ return {
1344
+ ...entry,
1345
+ text: stripped
1346
+ };
1347
+ }),
1348
+ changed
1349
+ };
1350
+ }
1351
+ function stripEnvelopeFromMessage(message) {
1352
+ if (!message || typeof message !== "object") return message;
1353
+ const entry = message;
1354
+ const stripUserEnvelope = (typeof entry.role === "string" ? entry.role.toLowerCase() : "") === "user";
1355
+ let changed = false;
1356
+ const next = { ...entry };
1357
+ if (typeof entry.content === "string") {
1358
+ const inboundStripped = stripInboundMetadata(entry.content);
1359
+ const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
1360
+ if (stripped !== entry.content) {
1361
+ next.content = stripped;
1362
+ changed = true;
1363
+ }
1364
+ } else if (Array.isArray(entry.content)) {
1365
+ const updated = stripEnvelopeFromContentWithRole(entry.content, stripUserEnvelope);
1366
+ if (updated.changed) {
1367
+ next.content = updated.content;
1368
+ changed = true;
1369
+ }
1370
+ } else if (typeof entry.text === "string") {
1371
+ const inboundStripped = stripInboundMetadata(entry.text);
1372
+ const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
1373
+ if (stripped !== entry.text) {
1374
+ next.text = stripped;
1375
+ changed = true;
1376
+ }
1377
+ }
1378
+ return changed ? next : message;
1379
+ }
1380
+ function stripEnvelopeFromMessages(messages) {
1381
+ if (messages.length === 0) return messages;
1382
+ let changed = false;
1383
+ const next = messages.map((message) => {
1384
+ const stripped = stripEnvelopeFromMessage(message);
1385
+ if (stripped !== message) changed = true;
1386
+ return stripped;
1387
+ });
1388
+ return changed ? next : messages;
1389
+ }
1390
+
1391
+ //#endregion
1392
+ //#region src/gateway/session-utils.fs.ts
1393
+ const sessionTitleFieldsCache = /* @__PURE__ */ new Map();
1394
+ const MAX_SESSION_TITLE_FIELDS_CACHE_ENTRIES = 5e3;
1395
+ function readSessionTitleFieldsCacheKey(filePath, opts) {
1396
+ return `${filePath}\t${opts?.includeInterSession === true ? "1" : "0"}`;
1397
+ }
1398
+ function getCachedSessionTitleFields(cacheKey, stat) {
1399
+ const cached = sessionTitleFieldsCache.get(cacheKey);
1400
+ if (!cached) return null;
1401
+ if (cached.mtimeMs !== stat.mtimeMs || cached.size !== stat.size) {
1402
+ sessionTitleFieldsCache.delete(cacheKey);
1403
+ return null;
1404
+ }
1405
+ sessionTitleFieldsCache.delete(cacheKey);
1406
+ sessionTitleFieldsCache.set(cacheKey, cached);
1407
+ return {
1408
+ firstUserMessage: cached.firstUserMessage,
1409
+ lastMessagePreview: cached.lastMessagePreview
1410
+ };
1411
+ }
1412
+ function setCachedSessionTitleFields(cacheKey, stat, value) {
1413
+ sessionTitleFieldsCache.set(cacheKey, {
1414
+ ...value,
1415
+ mtimeMs: stat.mtimeMs,
1416
+ size: stat.size
1417
+ });
1418
+ while (sessionTitleFieldsCache.size > MAX_SESSION_TITLE_FIELDS_CACHE_ENTRIES) {
1419
+ const oldestKey = sessionTitleFieldsCache.keys().next().value;
1420
+ if (typeof oldestKey !== "string" || !oldestKey) break;
1421
+ sessionTitleFieldsCache.delete(oldestKey);
1422
+ }
1423
+ }
1424
+ function readSessionMessages(sessionId, storePath, sessionFile) {
1425
+ const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile).find((p) => fs.existsSync(p));
1426
+ if (!filePath) return [];
1427
+ const lines = fs.readFileSync(filePath, "utf-8").split(/\r?\n/);
1428
+ const messages = [];
1429
+ for (const line of lines) {
1430
+ if (!line.trim()) continue;
1431
+ try {
1432
+ const parsed = JSON.parse(line);
1433
+ if (parsed?.message) {
1434
+ messages.push(parsed.message);
1435
+ continue;
1436
+ }
1437
+ } catch {}
1438
+ }
1439
+ return messages;
1440
+ }
1441
+ function resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId) {
1442
+ const candidates = [];
1443
+ const pushCandidate = (resolve) => {
1444
+ try {
1445
+ candidates.push(resolve());
1446
+ } catch {}
1447
+ };
1448
+ if (storePath) {
1449
+ const sessionsDir = path.dirname(storePath);
1450
+ if (sessionFile) pushCandidate(() => resolveSessionFilePath(sessionId, { sessionFile }, {
1451
+ sessionsDir,
1452
+ agentId
1453
+ }));
1454
+ pushCandidate(() => resolveSessionTranscriptPathInDir(sessionId, sessionsDir));
1455
+ } else if (sessionFile) if (agentId) pushCandidate(() => resolveSessionFilePath(sessionId, { sessionFile }, { agentId }));
1456
+ else {
1457
+ const trimmed = sessionFile.trim();
1458
+ if (trimmed) candidates.push(path.resolve(trimmed));
1459
+ }
1460
+ if (agentId) pushCandidate(() => resolveSessionTranscriptPath(sessionId, agentId));
1461
+ const home = resolveRequiredHomeDir(process.env, os.homedir);
1462
+ const legacyDir = path.join(home, ".remoteclaw", "sessions");
1463
+ pushCandidate(() => resolveSessionTranscriptPathInDir(sessionId, legacyDir));
1464
+ return Array.from(new Set(candidates));
1465
+ }
1466
+ function canonicalizePathForComparison(filePath) {
1467
+ const resolved = path.resolve(filePath);
1468
+ try {
1469
+ return fs.realpathSync(resolved);
1470
+ } catch {
1471
+ return resolved;
1472
+ }
1473
+ }
1474
+ function archiveFileOnDisk(filePath, reason) {
1475
+ const archived = `${filePath}.${reason}.${formatSessionArchiveTimestamp()}`;
1476
+ fs.renameSync(filePath, archived);
1477
+ return archived;
1478
+ }
1479
+ /**
1480
+ * Archives all transcript files for a given session.
1481
+ * Best-effort: silently skips files that don't exist or fail to rename.
1482
+ */
1483
+ function archiveSessionTranscripts(opts) {
1484
+ const archived = [];
1485
+ const storeDir = opts.restrictToStoreDir && opts.storePath ? canonicalizePathForComparison(path.dirname(opts.storePath)) : null;
1486
+ for (const candidate of resolveSessionTranscriptCandidates(opts.sessionId, opts.storePath, opts.sessionFile, opts.agentId)) {
1487
+ const candidatePath = canonicalizePathForComparison(candidate);
1488
+ if (storeDir) {
1489
+ const relative = path.relative(storeDir, candidatePath);
1490
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) continue;
1491
+ }
1492
+ if (!fs.existsSync(candidatePath)) continue;
1493
+ try {
1494
+ archived.push(archiveFileOnDisk(candidatePath, opts.reason));
1495
+ } catch {}
1496
+ }
1497
+ return archived;
1498
+ }
1499
+ async function cleanupArchivedSessionTranscripts(opts) {
1500
+ if (!Number.isFinite(opts.olderThanMs) || opts.olderThanMs < 0) return {
1501
+ removed: 0,
1502
+ scanned: 0
1503
+ };
1504
+ const now = opts.nowMs ?? Date.now();
1505
+ const reason = opts.reason ?? "deleted";
1506
+ const directories = Array.from(new Set(opts.directories.map((dir) => path.resolve(dir))));
1507
+ let removed = 0;
1508
+ let scanned = 0;
1509
+ for (const dir of directories) {
1510
+ const entries = await fs.promises.readdir(dir).catch(() => []);
1511
+ for (const entry of entries) {
1512
+ const timestamp = parseSessionArchiveTimestamp(entry, reason);
1513
+ if (timestamp == null) continue;
1514
+ scanned += 1;
1515
+ if (now - timestamp <= opts.olderThanMs) continue;
1516
+ const fullPath = path.join(dir, entry);
1517
+ if (!(await fs.promises.stat(fullPath).catch(() => null))?.isFile()) continue;
1518
+ await fs.promises.rm(fullPath).catch(() => void 0);
1519
+ removed += 1;
1520
+ }
1521
+ }
1522
+ return {
1523
+ removed,
1524
+ scanned
1525
+ };
1526
+ }
1527
+ function jsonUtf8Bytes(value) {
1528
+ try {
1529
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
1530
+ } catch {
1531
+ return Buffer.byteLength(String(value), "utf8");
1532
+ }
1533
+ }
1534
+ function capArrayByJsonBytes(items, maxBytes) {
1535
+ if (items.length === 0) return {
1536
+ items,
1537
+ bytes: 2
1538
+ };
1539
+ const parts = items.map((item) => jsonUtf8Bytes(item));
1540
+ let bytes = 2 + parts.reduce((a, b) => a + b, 0) + (items.length - 1);
1541
+ let start = 0;
1542
+ while (bytes > maxBytes && start < items.length - 1) {
1543
+ bytes -= parts[start] + 1;
1544
+ start += 1;
1545
+ }
1546
+ return {
1547
+ items: start > 0 ? items.slice(start) : items,
1548
+ bytes
1549
+ };
1550
+ }
1551
+ const MAX_LINES_TO_SCAN = 10;
1552
+ function readSessionTitleFieldsFromTranscript(sessionId, storePath, sessionFile, agentId, opts) {
1553
+ const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId).find((p) => fs.existsSync(p));
1554
+ if (!filePath) return {
1555
+ firstUserMessage: null,
1556
+ lastMessagePreview: null
1557
+ };
1558
+ let stat;
1559
+ try {
1560
+ stat = fs.statSync(filePath);
1561
+ } catch {
1562
+ return {
1563
+ firstUserMessage: null,
1564
+ lastMessagePreview: null
1565
+ };
1566
+ }
1567
+ const cacheKey = readSessionTitleFieldsCacheKey(filePath, opts);
1568
+ const cached = getCachedSessionTitleFields(cacheKey, stat);
1569
+ if (cached) return cached;
1570
+ if (stat.size === 0) {
1571
+ const empty = {
1572
+ firstUserMessage: null,
1573
+ lastMessagePreview: null
1574
+ };
1575
+ setCachedSessionTitleFields(cacheKey, stat, empty);
1576
+ return empty;
1577
+ }
1578
+ let fd = null;
1579
+ try {
1580
+ fd = fs.openSync(filePath, "r");
1581
+ const size = stat.size;
1582
+ let firstUserMessage = null;
1583
+ try {
1584
+ const chunk = readTranscriptHeadChunk(fd);
1585
+ if (chunk) firstUserMessage = extractFirstUserMessageFromTranscriptChunk(chunk, opts);
1586
+ } catch {}
1587
+ let lastMessagePreview = null;
1588
+ try {
1589
+ lastMessagePreview = readLastMessagePreviewFromOpenTranscript({
1590
+ fd,
1591
+ size
1592
+ });
1593
+ } catch {}
1594
+ const result = {
1595
+ firstUserMessage,
1596
+ lastMessagePreview
1597
+ };
1598
+ setCachedSessionTitleFields(cacheKey, stat, result);
1599
+ return result;
1600
+ } catch {
1601
+ return {
1602
+ firstUserMessage: null,
1603
+ lastMessagePreview: null
1604
+ };
1605
+ } finally {
1606
+ if (fd !== null) try {
1607
+ fs.closeSync(fd);
1608
+ } catch {}
1609
+ }
1610
+ }
1611
+ function extractTextFromContent(content) {
1612
+ if (typeof content === "string") return stripInlineDirectiveTagsForDisplay(content).text.trim() || null;
1613
+ if (!Array.isArray(content)) return null;
1614
+ for (const part of content) {
1615
+ if (!part || typeof part.text !== "string") continue;
1616
+ if (part.type === "text" || part.type === "output_text" || part.type === "input_text") {
1617
+ const normalized = stripInlineDirectiveTagsForDisplay(part.text).text.trim();
1618
+ if (normalized) return normalized;
1619
+ }
1620
+ }
1621
+ return null;
1622
+ }
1623
+ function readTranscriptHeadChunk(fd, maxBytes = 8192) {
1624
+ const buf = Buffer.alloc(maxBytes);
1625
+ const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
1626
+ if (bytesRead <= 0) return null;
1627
+ return buf.toString("utf-8", 0, bytesRead);
1628
+ }
1629
+ function extractFirstUserMessageFromTranscriptChunk(chunk, opts) {
1630
+ const lines = chunk.split(/\r?\n/).slice(0, MAX_LINES_TO_SCAN);
1631
+ for (const line of lines) {
1632
+ if (!line.trim()) continue;
1633
+ try {
1634
+ const msg = JSON.parse(line)?.message;
1635
+ if (msg?.role !== "user") continue;
1636
+ if (opts?.includeInterSession !== true && hasInterSessionUserProvenance(msg)) continue;
1637
+ const text = extractTextFromContent(msg.content);
1638
+ if (text) return text;
1639
+ } catch {}
1640
+ }
1641
+ return null;
1642
+ }
1643
+ const LAST_MSG_MAX_BYTES = 16384;
1644
+ const LAST_MSG_MAX_LINES = 20;
1645
+ function readLastMessagePreviewFromOpenTranscript(params) {
1646
+ const readStart = Math.max(0, params.size - LAST_MSG_MAX_BYTES);
1647
+ const readLen = Math.min(params.size, LAST_MSG_MAX_BYTES);
1648
+ const buf = Buffer.alloc(readLen);
1649
+ fs.readSync(params.fd, buf, 0, readLen, readStart);
1650
+ const tailLines = buf.toString("utf-8").split(/\r?\n/).filter((l) => l.trim()).slice(-LAST_MSG_MAX_LINES);
1651
+ for (let i = tailLines.length - 1; i >= 0; i--) {
1652
+ const line = tailLines[i];
1653
+ try {
1654
+ const msg = JSON.parse(line)?.message;
1655
+ if (msg?.role !== "user" && msg?.role !== "assistant") continue;
1656
+ const text = extractTextFromContent(msg.content);
1657
+ if (text) return text;
1658
+ } catch {}
1659
+ }
1660
+ return null;
1661
+ }
1662
+ const PREVIEW_READ_SIZES = [
1663
+ 64 * 1024,
1664
+ 256 * 1024,
1665
+ 1024 * 1024
1666
+ ];
1667
+ const PREVIEW_MAX_LINES = 200;
1668
+ function normalizeRole(role, isTool) {
1669
+ if (isTool) return "tool";
1670
+ switch ((role ?? "").toLowerCase()) {
1671
+ case "user": return "user";
1672
+ case "assistant": return "assistant";
1673
+ case "system": return "system";
1674
+ case "tool": return "tool";
1675
+ default: return "other";
1676
+ }
1677
+ }
1678
+ function truncatePreviewText(text, maxChars) {
1679
+ if (maxChars <= 0 || text.length <= maxChars) return text;
1680
+ if (maxChars <= 3) return text.slice(0, maxChars);
1681
+ return `${text.slice(0, maxChars - 3)}...`;
1682
+ }
1683
+ function extractPreviewText(message) {
1684
+ if (typeof message.content === "string") {
1685
+ const normalized = stripInlineDirectiveTagsForDisplay(message.content).text.trim();
1686
+ return normalized ? normalized : null;
1687
+ }
1688
+ if (Array.isArray(message.content)) {
1689
+ const parts = message.content.map((entry) => typeof entry?.text === "string" ? stripInlineDirectiveTagsForDisplay(entry.text).text : "").filter((text) => text.trim().length > 0);
1690
+ if (parts.length > 0) return parts.join("\n").trim();
1691
+ }
1692
+ if (typeof message.text === "string") {
1693
+ const normalized = stripInlineDirectiveTagsForDisplay(message.text).text.trim();
1694
+ return normalized ? normalized : null;
1695
+ }
1696
+ return null;
1697
+ }
1698
+ function isToolCall(message) {
1699
+ return hasToolCall(message);
1700
+ }
1701
+ function extractToolNames(message) {
1702
+ return extractToolCallNames(message);
1703
+ }
1704
+ function extractMediaSummary(message) {
1705
+ if (!Array.isArray(message.content)) return null;
1706
+ for (const entry of message.content) {
1707
+ const raw = typeof entry?.type === "string" ? entry.type.trim().toLowerCase() : "";
1708
+ if (!raw || raw === "text" || raw === "toolcall" || raw === "tool_call") continue;
1709
+ return `[${raw}]`;
1710
+ }
1711
+ return null;
1712
+ }
1713
+ function buildPreviewItems(messages, maxItems, maxChars) {
1714
+ const items = [];
1715
+ for (const message of messages) {
1716
+ const toolCall = isToolCall(message);
1717
+ const role = normalizeRole(message.role, toolCall);
1718
+ let text = extractPreviewText(message);
1719
+ if (!text) {
1720
+ const toolNames = extractToolNames(message);
1721
+ if (toolNames.length > 0) {
1722
+ const shown = toolNames.slice(0, 2);
1723
+ const overflow = toolNames.length - shown.length;
1724
+ text = `call ${shown.join(", ")}`;
1725
+ if (overflow > 0) text += ` +${overflow}`;
1726
+ }
1727
+ }
1728
+ if (!text) text = extractMediaSummary(message);
1729
+ if (!text) continue;
1730
+ let trimmed = text.trim();
1731
+ if (!trimmed) continue;
1732
+ if (role === "user") trimmed = stripEnvelope(trimmed);
1733
+ trimmed = truncatePreviewText(trimmed, maxChars);
1734
+ items.push({
1735
+ role,
1736
+ text: trimmed
1737
+ });
1738
+ }
1739
+ if (items.length <= maxItems) return items;
1740
+ return items.slice(-maxItems);
1741
+ }
1742
+ function readRecentMessagesFromTranscript(filePath, maxMessages, readBytes) {
1743
+ let fd = null;
1744
+ try {
1745
+ fd = fs.openSync(filePath, "r");
1746
+ const size = fs.fstatSync(fd).size;
1747
+ if (size === 0) return [];
1748
+ const readStart = Math.max(0, size - readBytes);
1749
+ const readLen = Math.min(size, readBytes);
1750
+ const buf = Buffer.alloc(readLen);
1751
+ fs.readSync(fd, buf, 0, readLen, readStart);
1752
+ const tailLines = buf.toString("utf-8").split(/\r?\n/).filter((l) => l.trim()).slice(-PREVIEW_MAX_LINES);
1753
+ const collected = [];
1754
+ for (let i = tailLines.length - 1; i >= 0; i--) {
1755
+ const line = tailLines[i];
1756
+ try {
1757
+ const msg = JSON.parse(line)?.message;
1758
+ if (msg && typeof msg === "object") {
1759
+ collected.push(msg);
1760
+ if (collected.length >= maxMessages) break;
1761
+ }
1762
+ } catch {}
1763
+ }
1764
+ return collected.toReversed();
1765
+ } catch {
1766
+ return [];
1767
+ } finally {
1768
+ if (fd !== null) fs.closeSync(fd);
1769
+ }
1770
+ }
1771
+ function readSessionPreviewItemsFromTranscript(sessionId, storePath, sessionFile, agentId, maxItems, maxChars) {
1772
+ const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId).find((p) => fs.existsSync(p));
1773
+ if (!filePath) return [];
1774
+ const boundedItems = Math.max(1, Math.min(maxItems, 50));
1775
+ const boundedChars = Math.max(20, Math.min(maxChars, 2e3));
1776
+ for (const readSize of PREVIEW_READ_SIZES) {
1777
+ const messages = readRecentMessagesFromTranscript(filePath, boundedItems, readSize);
1778
+ if (messages.length > 0 || readSize === PREVIEW_READ_SIZES[PREVIEW_READ_SIZES.length - 1]) return buildPreviewItems(messages, boundedItems, boundedChars);
1779
+ }
1780
+ return [];
1781
+ }
1782
+
1783
+ //#endregion
1784
+ //#region src/utils/account-id.ts
1785
+ function normalizeAccountId(value) {
1786
+ return normalizeOptionalAccountId(value);
1787
+ }
1788
+
1789
+ //#endregion
1790
+ //#region src/utils/delivery-context.ts
1791
+ function normalizeDeliveryContext(context) {
1792
+ if (!context) return;
1793
+ const channel = typeof context.channel === "string" ? normalizeMessageChannel(context.channel) ?? context.channel.trim() : void 0;
1794
+ const to = typeof context.to === "string" ? context.to.trim() : void 0;
1795
+ const accountId = normalizeAccountId(context.accountId);
1796
+ const threadId = typeof context.threadId === "number" && Number.isFinite(context.threadId) ? Math.trunc(context.threadId) : typeof context.threadId === "string" ? context.threadId.trim() : void 0;
1797
+ const normalizedThreadId = typeof threadId === "string" ? threadId ? threadId : void 0 : threadId;
1798
+ if (!channel && !to && !accountId && normalizedThreadId == null) return;
1799
+ const normalized = {
1800
+ channel: channel || void 0,
1801
+ to: to || void 0,
1802
+ accountId
1803
+ };
1804
+ if (normalizedThreadId != null) normalized.threadId = normalizedThreadId;
1805
+ return normalized;
1806
+ }
1807
+ function normalizeSessionDeliveryFields(source) {
1808
+ if (!source) return {
1809
+ deliveryContext: void 0,
1810
+ lastChannel: void 0,
1811
+ lastTo: void 0,
1812
+ lastAccountId: void 0,
1813
+ lastThreadId: void 0
1814
+ };
1815
+ const merged = mergeDeliveryContext(normalizeDeliveryContext({
1816
+ channel: source.lastChannel ?? source.channel,
1817
+ to: source.lastTo,
1818
+ accountId: source.lastAccountId,
1819
+ threadId: source.lastThreadId
1820
+ }), normalizeDeliveryContext(source.deliveryContext));
1821
+ if (!merged) return {
1822
+ deliveryContext: void 0,
1823
+ lastChannel: void 0,
1824
+ lastTo: void 0,
1825
+ lastAccountId: void 0,
1826
+ lastThreadId: void 0
1827
+ };
1828
+ return {
1829
+ deliveryContext: merged,
1830
+ lastChannel: merged.channel,
1831
+ lastTo: merged.to,
1832
+ lastAccountId: merged.accountId,
1833
+ lastThreadId: merged.threadId
1834
+ };
1835
+ }
1836
+ function deliveryContextFromSession(entry) {
1837
+ if (!entry) return;
1838
+ return normalizeSessionDeliveryFields({
1839
+ channel: entry.channel,
1840
+ lastChannel: entry.lastChannel,
1841
+ lastTo: entry.lastTo,
1842
+ lastAccountId: entry.lastAccountId,
1843
+ lastThreadId: entry.lastThreadId ?? entry.deliveryContext?.threadId ?? entry.origin?.threadId,
1844
+ deliveryContext: entry.deliveryContext
1845
+ }).deliveryContext;
1846
+ }
1847
+ function mergeDeliveryContext(primary, fallback) {
1848
+ const normalizedPrimary = normalizeDeliveryContext(primary);
1849
+ const normalizedFallback = normalizeDeliveryContext(fallback);
1850
+ if (!normalizedPrimary && !normalizedFallback) return;
1851
+ return normalizeDeliveryContext({
1852
+ channel: normalizedPrimary?.channel ?? normalizedFallback?.channel,
1853
+ to: normalizedPrimary?.to ?? normalizedFallback?.to,
1854
+ accountId: normalizedPrimary?.accountId ?? normalizedFallback?.accountId,
1855
+ threadId: normalizedPrimary?.threadId ?? normalizedFallback?.threadId
1856
+ });
1857
+ }
1858
+
1859
+ //#endregion
1860
+ //#region src/config/cache-utils.ts
1861
+ function resolveCacheTtlMs(params) {
1862
+ const { envValue, defaultTtlMs } = params;
1863
+ if (envValue) {
1864
+ const parsed = Number.parseInt(envValue, 10);
1865
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
1866
+ }
1867
+ return defaultTtlMs;
1868
+ }
1869
+ function isCacheEnabled(ttlMs) {
1870
+ return ttlMs > 0;
1871
+ }
1872
+ function getFileMtimeMs(filePath) {
1873
+ try {
1874
+ return fs.statSync(filePath).mtimeMs;
1875
+ } catch {
1876
+ return;
1877
+ }
1878
+ }
1879
+
1880
+ //#endregion
1881
+ //#region src/config/sessions/store.ts
1882
+ const log = createSubsystemLogger("sessions/store");
1883
+ const SESSION_STORE_CACHE = /* @__PURE__ */ new Map();
1884
+ const DEFAULT_SESSION_STORE_TTL_MS = 45e3;
1885
+ function isSessionStoreRecord(value) {
1886
+ return !!value && typeof value === "object" && !Array.isArray(value);
1887
+ }
1888
+ function getSessionStoreTtl() {
1889
+ return resolveCacheTtlMs({
1890
+ envValue: process.env.REMOTECLAW_SESSION_CACHE_TTL_MS,
1891
+ defaultTtlMs: DEFAULT_SESSION_STORE_TTL_MS
1892
+ });
1893
+ }
1894
+ function isSessionStoreCacheEnabled() {
1895
+ return isCacheEnabled(getSessionStoreTtl());
1896
+ }
1897
+ function isSessionStoreCacheValid(entry) {
1898
+ const now = Date.now();
1899
+ const ttl = getSessionStoreTtl();
1900
+ return now - entry.loadedAt <= ttl;
1901
+ }
1902
+ function invalidateSessionStoreCache(storePath) {
1903
+ SESSION_STORE_CACHE.delete(storePath);
1904
+ }
1905
+ function normalizeSessionEntryDelivery(entry) {
1906
+ const normalized = normalizeSessionDeliveryFields({
1907
+ channel: entry.channel,
1908
+ lastChannel: entry.lastChannel,
1909
+ lastTo: entry.lastTo,
1910
+ lastAccountId: entry.lastAccountId,
1911
+ lastThreadId: entry.lastThreadId ?? entry.deliveryContext?.threadId ?? entry.origin?.threadId,
1912
+ deliveryContext: entry.deliveryContext
1913
+ });
1914
+ const nextDelivery = normalized.deliveryContext;
1915
+ const sameDelivery = (entry.deliveryContext?.channel ?? void 0) === nextDelivery?.channel && (entry.deliveryContext?.to ?? void 0) === nextDelivery?.to && (entry.deliveryContext?.accountId ?? void 0) === nextDelivery?.accountId && (entry.deliveryContext?.threadId ?? void 0) === nextDelivery?.threadId;
1916
+ const sameLast = entry.lastChannel === normalized.lastChannel && entry.lastTo === normalized.lastTo && entry.lastAccountId === normalized.lastAccountId && entry.lastThreadId === normalized.lastThreadId;
1917
+ if (sameDelivery && sameLast) return entry;
1918
+ return {
1919
+ ...entry,
1920
+ deliveryContext: nextDelivery,
1921
+ lastChannel: normalized.lastChannel,
1922
+ lastTo: normalized.lastTo,
1923
+ lastAccountId: normalized.lastAccountId,
1924
+ lastThreadId: normalized.lastThreadId
1925
+ };
1926
+ }
1927
+ function removeThreadFromDeliveryContext(context) {
1928
+ if (!context || context.threadId == null) return context;
1929
+ const next = { ...context };
1930
+ delete next.threadId;
1931
+ return next;
1932
+ }
1933
+ function normalizeStoreSessionKey(sessionKey) {
1934
+ return sessionKey.trim().toLowerCase();
1935
+ }
1936
+ function resolveStoreSessionEntry(params) {
1937
+ const trimmedKey = params.sessionKey.trim();
1938
+ const normalizedKey = normalizeStoreSessionKey(trimmedKey);
1939
+ const legacyKeySet = /* @__PURE__ */ new Set();
1940
+ if (trimmedKey !== normalizedKey && Object.prototype.hasOwnProperty.call(params.store, trimmedKey)) legacyKeySet.add(trimmedKey);
1941
+ let existing = params.store[normalizedKey] ?? (legacyKeySet.size > 0 ? params.store[trimmedKey] : void 0);
1942
+ let existingUpdatedAt = existing?.updatedAt ?? 0;
1943
+ for (const [candidateKey, candidateEntry] of Object.entries(params.store)) {
1944
+ if (candidateKey === normalizedKey) continue;
1945
+ if (candidateKey.toLowerCase() !== normalizedKey) continue;
1946
+ legacyKeySet.add(candidateKey);
1947
+ const candidateUpdatedAt = candidateEntry?.updatedAt ?? 0;
1948
+ if (!existing || candidateUpdatedAt > existingUpdatedAt) {
1949
+ existing = candidateEntry;
1950
+ existingUpdatedAt = candidateUpdatedAt;
1951
+ }
1952
+ }
1953
+ return {
1954
+ normalizedKey,
1955
+ existing,
1956
+ legacyKeys: [...legacyKeySet]
1957
+ };
1958
+ }
1959
+ function normalizeSessionStore(store) {
1960
+ for (const [key, entry] of Object.entries(store)) {
1961
+ if (!entry) continue;
1962
+ const normalized = normalizeSessionEntryDelivery(normalizeSessionRuntimeModelFields(entry));
1963
+ if (normalized !== entry) store[key] = normalized;
1964
+ }
1965
+ }
1966
+ function clearSessionStoreCacheForTest() {
1967
+ SESSION_STORE_CACHE.clear();
1968
+ for (const queue of LOCK_QUEUES.values()) for (const task of queue.pending) task.reject(/* @__PURE__ */ new Error("session store queue cleared for test"));
1969
+ LOCK_QUEUES.clear();
1970
+ }
1971
+ /** Expose lock queue size for tests. */
1972
+ function getSessionStoreLockQueueSizeForTest() {
1973
+ return LOCK_QUEUES.size;
1974
+ }
1975
+ async function withSessionStoreLockForTest(storePath, fn, opts = {}) {
1976
+ return await withSessionStoreLock(storePath, fn, opts);
1977
+ }
1978
+ function loadSessionStore(storePath, opts = {}) {
1979
+ if (!opts.skipCache && isSessionStoreCacheEnabled()) {
1980
+ const cached = SESSION_STORE_CACHE.get(storePath);
1981
+ if (cached && isSessionStoreCacheValid(cached)) {
1982
+ if (getFileMtimeMs(storePath) === cached.mtimeMs) return structuredClone(cached.store);
1983
+ invalidateSessionStoreCache(storePath);
1984
+ }
1985
+ }
1986
+ let store = {};
1987
+ let mtimeMs = getFileMtimeMs(storePath);
1988
+ const maxReadAttempts = process.platform === "win32" ? 3 : 1;
1989
+ const retryBuf = maxReadAttempts > 1 ? new Int32Array(new SharedArrayBuffer(4)) : void 0;
1990
+ for (let attempt = 0; attempt < maxReadAttempts; attempt++) try {
1991
+ const raw = fs.readFileSync(storePath, "utf-8");
1992
+ if (raw.length === 0 && attempt < maxReadAttempts - 1) {
1993
+ Atomics.wait(retryBuf, 0, 0, 50);
1994
+ continue;
1995
+ }
1996
+ const parsed = JSON.parse(raw);
1997
+ if (isSessionStoreRecord(parsed)) store = parsed;
1998
+ mtimeMs = getFileMtimeMs(storePath) ?? mtimeMs;
1999
+ break;
2000
+ } catch {
2001
+ if (attempt < maxReadAttempts - 1) {
2002
+ Atomics.wait(retryBuf, 0, 0, 50);
2003
+ continue;
2004
+ }
2005
+ }
2006
+ for (const entry of Object.values(store)) {
2007
+ if (!entry || typeof entry !== "object") continue;
2008
+ const rec = entry;
2009
+ if (typeof rec.channel !== "string" && typeof rec.provider === "string") {
2010
+ rec.channel = rec.provider;
2011
+ delete rec.provider;
2012
+ }
2013
+ if (typeof rec.lastChannel !== "string" && typeof rec.lastProvider === "string") {
2014
+ rec.lastChannel = rec.lastProvider;
2015
+ delete rec.lastProvider;
2016
+ }
2017
+ if (typeof rec.groupChannel !== "string" && typeof rec.room === "string") {
2018
+ rec.groupChannel = rec.room;
2019
+ delete rec.room;
2020
+ } else if ("room" in rec) delete rec.room;
2021
+ }
2022
+ if (!opts.skipCache && isSessionStoreCacheEnabled()) SESSION_STORE_CACHE.set(storePath, {
2023
+ store: structuredClone(store),
2024
+ loadedAt: Date.now(),
2025
+ storePath,
2026
+ mtimeMs
2027
+ });
2028
+ return structuredClone(store);
2029
+ }
2030
+ function readSessionUpdatedAt(params) {
2031
+ try {
2032
+ return resolveStoreSessionEntry({
2033
+ store: loadSessionStore(params.storePath),
2034
+ sessionKey: params.sessionKey
2035
+ }).existing?.updatedAt;
2036
+ } catch {
2037
+ return;
2038
+ }
2039
+ }
2040
+ const DEFAULT_SESSION_PRUNE_AFTER_MS = 720 * 60 * 60 * 1e3;
2041
+ const DEFAULT_SESSION_MAX_ENTRIES = 500;
2042
+ const DEFAULT_SESSION_ROTATE_BYTES = 10485760;
2043
+ const DEFAULT_SESSION_MAINTENANCE_MODE = "warn";
2044
+ const DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO = .8;
2045
+ function resolvePruneAfterMs(maintenance) {
2046
+ const raw = maintenance?.pruneAfter ?? maintenance?.pruneDays;
2047
+ if (raw === void 0 || raw === null || raw === "") return DEFAULT_SESSION_PRUNE_AFTER_MS;
2048
+ try {
2049
+ return parseDurationMs(String(raw).trim(), { defaultUnit: "d" });
2050
+ } catch {
2051
+ return DEFAULT_SESSION_PRUNE_AFTER_MS;
2052
+ }
2053
+ }
2054
+ function resolveRotateBytes(maintenance) {
2055
+ const raw = maintenance?.rotateBytes;
2056
+ if (raw === void 0 || raw === null || raw === "") return DEFAULT_SESSION_ROTATE_BYTES;
2057
+ try {
2058
+ return parseByteSize(String(raw).trim(), { defaultUnit: "b" });
2059
+ } catch {
2060
+ return DEFAULT_SESSION_ROTATE_BYTES;
2061
+ }
2062
+ }
2063
+ function resolveResetArchiveRetentionMs(maintenance, pruneAfterMs) {
2064
+ const raw = maintenance?.resetArchiveRetention;
2065
+ if (raw === false) return null;
2066
+ if (raw === void 0 || raw === null || raw === "") return pruneAfterMs;
2067
+ try {
2068
+ return parseDurationMs(String(raw).trim(), { defaultUnit: "d" });
2069
+ } catch {
2070
+ return pruneAfterMs;
2071
+ }
2072
+ }
2073
+ function resolveMaxDiskBytes(maintenance) {
2074
+ const raw = maintenance?.maxDiskBytes;
2075
+ if (raw === void 0 || raw === null || raw === "") return null;
2076
+ try {
2077
+ return parseByteSize(String(raw).trim(), { defaultUnit: "b" });
2078
+ } catch {
2079
+ return null;
2080
+ }
2081
+ }
2082
+ function resolveHighWaterBytes(maintenance, maxDiskBytes) {
2083
+ const computeDefault = () => {
2084
+ if (maxDiskBytes == null) return null;
2085
+ if (maxDiskBytes <= 0) return 0;
2086
+ return Math.max(1, Math.min(maxDiskBytes, Math.floor(maxDiskBytes * DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO)));
2087
+ };
2088
+ if (maxDiskBytes == null) return null;
2089
+ const raw = maintenance?.highWaterBytes;
2090
+ if (raw === void 0 || raw === null || raw === "") return computeDefault();
2091
+ try {
2092
+ const parsed = parseByteSize(String(raw).trim(), { defaultUnit: "b" });
2093
+ return Math.min(parsed, maxDiskBytes);
2094
+ } catch {
2095
+ return computeDefault();
2096
+ }
2097
+ }
2098
+ /**
2099
+ * Resolve maintenance settings from remoteclaw.json (`session.maintenance`).
2100
+ * Falls back to built-in defaults when config is missing or unset.
2101
+ */
2102
+ function resolveMaintenanceConfig() {
2103
+ let maintenance;
2104
+ try {
2105
+ maintenance = loadConfig().session?.maintenance;
2106
+ } catch {}
2107
+ const pruneAfterMs = resolvePruneAfterMs(maintenance);
2108
+ const maxDiskBytes = resolveMaxDiskBytes(maintenance);
2109
+ return {
2110
+ mode: maintenance?.mode ?? DEFAULT_SESSION_MAINTENANCE_MODE,
2111
+ pruneAfterMs,
2112
+ maxEntries: maintenance?.maxEntries ?? DEFAULT_SESSION_MAX_ENTRIES,
2113
+ rotateBytes: resolveRotateBytes(maintenance),
2114
+ resetArchiveRetentionMs: resolveResetArchiveRetentionMs(maintenance, pruneAfterMs),
2115
+ maxDiskBytes,
2116
+ highWaterBytes: resolveHighWaterBytes(maintenance, maxDiskBytes)
2117
+ };
2118
+ }
2119
+ /**
2120
+ * Remove entries whose `updatedAt` is older than the configured threshold.
2121
+ * Entries without `updatedAt` are kept (cannot determine staleness).
2122
+ * Mutates `store` in-place.
2123
+ */
2124
+ function pruneStaleEntries(store, overrideMaxAgeMs, opts = {}) {
2125
+ const maxAgeMs = overrideMaxAgeMs ?? resolveMaintenanceConfig().pruneAfterMs;
2126
+ const cutoffMs = Date.now() - maxAgeMs;
2127
+ let pruned = 0;
2128
+ for (const [key, entry] of Object.entries(store)) if (entry?.updatedAt != null && entry.updatedAt < cutoffMs) {
2129
+ opts.onPruned?.({
2130
+ key,
2131
+ entry
2132
+ });
2133
+ delete store[key];
2134
+ pruned++;
2135
+ }
2136
+ if (pruned > 0 && opts.log !== false) log.info("pruned stale session entries", {
2137
+ pruned,
2138
+ maxAgeMs
2139
+ });
2140
+ return pruned;
2141
+ }
2142
+ /**
2143
+ * Cap the store to the N most recently updated entries.
2144
+ * Entries without `updatedAt` are sorted last (removed first when over limit).
2145
+ * Mutates `store` in-place.
2146
+ */
2147
+ function getEntryUpdatedAt(entry) {
2148
+ return entry?.updatedAt ?? Number.NEGATIVE_INFINITY;
2149
+ }
2150
+ function getActiveSessionMaintenanceWarning(params) {
2151
+ const activeSessionKey = params.activeSessionKey.trim();
2152
+ if (!activeSessionKey) return null;
2153
+ const activeEntry = params.store[activeSessionKey];
2154
+ if (!activeEntry) return null;
2155
+ const cutoffMs = (params.nowMs ?? Date.now()) - params.pruneAfterMs;
2156
+ const wouldPrune = activeEntry.updatedAt != null ? activeEntry.updatedAt < cutoffMs : false;
2157
+ const keys = Object.keys(params.store);
2158
+ const wouldCap = keys.length > params.maxEntries && keys.toSorted((a, b) => getEntryUpdatedAt(params.store[b]) - getEntryUpdatedAt(params.store[a])).slice(params.maxEntries).includes(activeSessionKey);
2159
+ if (!wouldPrune && !wouldCap) return null;
2160
+ return {
2161
+ activeSessionKey,
2162
+ activeUpdatedAt: activeEntry.updatedAt,
2163
+ totalEntries: keys.length,
2164
+ pruneAfterMs: params.pruneAfterMs,
2165
+ maxEntries: params.maxEntries,
2166
+ wouldPrune,
2167
+ wouldCap
2168
+ };
2169
+ }
2170
+ function capEntryCount(store, overrideMax, opts = {}) {
2171
+ const maxEntries = overrideMax ?? resolveMaintenanceConfig().maxEntries;
2172
+ const keys = Object.keys(store);
2173
+ if (keys.length <= maxEntries) return 0;
2174
+ const toRemove = keys.toSorted((a, b) => {
2175
+ const aTime = getEntryUpdatedAt(store[a]);
2176
+ return getEntryUpdatedAt(store[b]) - aTime;
2177
+ }).slice(maxEntries);
2178
+ for (const key of toRemove) {
2179
+ const entry = store[key];
2180
+ if (entry) opts.onCapped?.({
2181
+ key,
2182
+ entry
2183
+ });
2184
+ delete store[key];
2185
+ }
2186
+ if (opts.log !== false) log.info("capped session entry count", {
2187
+ removed: toRemove.length,
2188
+ maxEntries
2189
+ });
2190
+ return toRemove.length;
2191
+ }
2192
+ async function getSessionFileSize(storePath) {
2193
+ try {
2194
+ return (await fs.promises.stat(storePath)).size;
2195
+ } catch {
2196
+ return null;
2197
+ }
2198
+ }
2199
+ /**
2200
+ * Rotate the sessions file if it exceeds the configured size threshold.
2201
+ * Renames the current file to `sessions.json.bak.{timestamp}` and cleans up
2202
+ * old rotation backups, keeping only the 3 most recent `.bak.*` files.
2203
+ */
2204
+ async function rotateSessionFile(storePath, overrideBytes) {
2205
+ const maxBytes = overrideBytes ?? resolveMaintenanceConfig().rotateBytes;
2206
+ const fileSize = await getSessionFileSize(storePath);
2207
+ if (fileSize == null) return false;
2208
+ if (fileSize <= maxBytes) return false;
2209
+ const backupPath = `${storePath}.bak.${Date.now()}`;
2210
+ try {
2211
+ await fs.promises.rename(storePath, backupPath);
2212
+ log.info("rotated session store file", {
2213
+ backupPath: path.basename(backupPath),
2214
+ sizeBytes: fileSize
2215
+ });
2216
+ } catch {
2217
+ return false;
2218
+ }
2219
+ try {
2220
+ const dir = path.dirname(storePath);
2221
+ const baseName = path.basename(storePath);
2222
+ const backups = (await fs.promises.readdir(dir)).filter((f) => f.startsWith(`${baseName}.bak.`)).toSorted().toReversed();
2223
+ const maxBackups = 3;
2224
+ if (backups.length > maxBackups) {
2225
+ const toDelete = backups.slice(maxBackups);
2226
+ for (const old of toDelete) await fs.promises.unlink(path.join(dir, old)).catch(() => void 0);
2227
+ log.info("cleaned up old session store backups", { deleted: toDelete.length });
2228
+ }
2229
+ } catch {}
2230
+ return true;
2231
+ }
2232
+ async function saveSessionStoreUnlocked(storePath, store, opts) {
2233
+ invalidateSessionStoreCache(storePath);
2234
+ normalizeSessionStore(store);
2235
+ if (!opts?.skipMaintenance) {
2236
+ const maintenance = {
2237
+ ...resolveMaintenanceConfig(),
2238
+ ...opts?.maintenanceOverride
2239
+ };
2240
+ const shouldWarnOnly = maintenance.mode === "warn";
2241
+ const beforeCount = Object.keys(store).length;
2242
+ if (shouldWarnOnly) {
2243
+ const activeSessionKey = opts?.activeSessionKey?.trim();
2244
+ if (activeSessionKey) {
2245
+ const warning = getActiveSessionMaintenanceWarning({
2246
+ store,
2247
+ activeSessionKey,
2248
+ pruneAfterMs: maintenance.pruneAfterMs,
2249
+ maxEntries: maintenance.maxEntries
2250
+ });
2251
+ if (warning) {
2252
+ log.warn("session maintenance would evict active session; skipping enforcement", {
2253
+ activeSessionKey: warning.activeSessionKey,
2254
+ wouldPrune: warning.wouldPrune,
2255
+ wouldCap: warning.wouldCap,
2256
+ pruneAfterMs: warning.pruneAfterMs,
2257
+ maxEntries: warning.maxEntries
2258
+ });
2259
+ await opts?.onWarn?.(warning);
2260
+ }
2261
+ }
2262
+ const diskBudget = await enforceSessionDiskBudget({
2263
+ store,
2264
+ storePath,
2265
+ activeSessionKey: opts?.activeSessionKey,
2266
+ maintenance,
2267
+ warnOnly: true,
2268
+ log
2269
+ });
2270
+ await opts?.onMaintenanceApplied?.({
2271
+ mode: maintenance.mode,
2272
+ beforeCount,
2273
+ afterCount: Object.keys(store).length,
2274
+ pruned: 0,
2275
+ capped: 0,
2276
+ diskBudget
2277
+ });
2278
+ } else {
2279
+ const removedSessionFiles = /* @__PURE__ */ new Map();
2280
+ const pruned = pruneStaleEntries(store, maintenance.pruneAfterMs, { onPruned: ({ entry }) => {
2281
+ if (!removedSessionFiles.has(entry.sessionId) || entry.sessionFile) removedSessionFiles.set(entry.sessionId, entry.sessionFile);
2282
+ } });
2283
+ const capped = capEntryCount(store, maintenance.maxEntries, { onCapped: ({ entry }) => {
2284
+ if (!removedSessionFiles.has(entry.sessionId) || entry.sessionFile) removedSessionFiles.set(entry.sessionId, entry.sessionFile);
2285
+ } });
2286
+ const archivedDirs = /* @__PURE__ */ new Set();
2287
+ const referencedSessionIds = new Set(Object.values(store).map((entry) => entry?.sessionId).filter((id) => Boolean(id)));
2288
+ for (const [sessionId, sessionFile] of removedSessionFiles) {
2289
+ if (referencedSessionIds.has(sessionId)) continue;
2290
+ const archived = archiveSessionTranscripts({
2291
+ sessionId,
2292
+ storePath,
2293
+ sessionFile,
2294
+ reason: "deleted",
2295
+ restrictToStoreDir: true
2296
+ });
2297
+ for (const archivedPath of archived) archivedDirs.add(path.dirname(archivedPath));
2298
+ }
2299
+ if (archivedDirs.size > 0 || maintenance.resetArchiveRetentionMs != null) {
2300
+ const targetDirs = archivedDirs.size > 0 ? [...archivedDirs] : [path.dirname(path.resolve(storePath))];
2301
+ await cleanupArchivedSessionTranscripts({
2302
+ directories: targetDirs,
2303
+ olderThanMs: maintenance.pruneAfterMs,
2304
+ reason: "deleted"
2305
+ });
2306
+ if (maintenance.resetArchiveRetentionMs != null) await cleanupArchivedSessionTranscripts({
2307
+ directories: targetDirs,
2308
+ olderThanMs: maintenance.resetArchiveRetentionMs,
2309
+ reason: "reset"
2310
+ });
2311
+ }
2312
+ await rotateSessionFile(storePath, maintenance.rotateBytes);
2313
+ const diskBudget = await enforceSessionDiskBudget({
2314
+ store,
2315
+ storePath,
2316
+ activeSessionKey: opts?.activeSessionKey,
2317
+ maintenance,
2318
+ warnOnly: false,
2319
+ log
2320
+ });
2321
+ await opts?.onMaintenanceApplied?.({
2322
+ mode: maintenance.mode,
2323
+ beforeCount,
2324
+ afterCount: Object.keys(store).length,
2325
+ pruned,
2326
+ capped,
2327
+ diskBudget
2328
+ });
2329
+ }
2330
+ }
2331
+ await fs.promises.mkdir(path.dirname(storePath), { recursive: true });
2332
+ const json = JSON.stringify(store, null, 2);
2333
+ if (process.platform === "win32") {
2334
+ const tmp = `${storePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
2335
+ try {
2336
+ await fs.promises.writeFile(tmp, json, "utf-8");
2337
+ for (let i = 0; i < 5; i++) try {
2338
+ await fs.promises.rename(tmp, storePath);
2339
+ break;
2340
+ } catch {
2341
+ if (i < 4) await new Promise((r) => setTimeout(r, 50 * (i + 1)));
2342
+ if (i === 4) log.warn(`rename failed after 5 attempts: ${storePath}`);
2343
+ }
2344
+ } catch (err) {
2345
+ if ((err && typeof err === "object" && "code" in err ? String(err.code) : null) === "ENOENT") return;
2346
+ throw err;
2347
+ } finally {
2348
+ await fs.promises.rm(tmp, { force: true }).catch(() => void 0);
2349
+ }
2350
+ return;
2351
+ }
2352
+ const tmp = `${storePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
2353
+ try {
2354
+ await fs.promises.writeFile(tmp, json, {
2355
+ mode: 384,
2356
+ encoding: "utf-8"
2357
+ });
2358
+ await fs.promises.rename(tmp, storePath);
2359
+ await fs.promises.chmod(storePath, 384);
2360
+ } catch (err) {
2361
+ if ((err && typeof err === "object" && "code" in err ? String(err.code) : null) === "ENOENT") {
2362
+ try {
2363
+ await fs.promises.mkdir(path.dirname(storePath), { recursive: true });
2364
+ await fs.promises.writeFile(storePath, json, {
2365
+ mode: 384,
2366
+ encoding: "utf-8"
2367
+ });
2368
+ await fs.promises.chmod(storePath, 384);
2369
+ } catch (err2) {
2370
+ if ((err2 && typeof err2 === "object" && "code" in err2 ? String(err2.code) : null) === "ENOENT") return;
2371
+ throw err2;
2372
+ }
2373
+ return;
2374
+ }
2375
+ throw err;
2376
+ } finally {
2377
+ await fs.promises.rm(tmp, { force: true });
2378
+ }
2379
+ }
2380
+ async function saveSessionStore(storePath, store, opts) {
2381
+ await withSessionStoreLock(storePath, async () => {
2382
+ await saveSessionStoreUnlocked(storePath, store, opts);
2383
+ });
2384
+ }
2385
+ async function updateSessionStore(storePath, mutator, opts) {
2386
+ return await withSessionStoreLock(storePath, async () => {
2387
+ const store = loadSessionStore(storePath, { skipCache: true });
2388
+ const result = await mutator(store);
2389
+ await saveSessionStoreUnlocked(storePath, store, opts);
2390
+ return result;
2391
+ });
2392
+ }
2393
+ const LOCK_QUEUES = /* @__PURE__ */ new Map();
2394
+ function lockTimeoutError(storePath) {
2395
+ return /* @__PURE__ */ new Error(`timeout waiting for session store lock: ${storePath}`);
2396
+ }
2397
+ function getOrCreateLockQueue(storePath) {
2398
+ const existing = LOCK_QUEUES.get(storePath);
2399
+ if (existing) return existing;
2400
+ const created = {
2401
+ running: false,
2402
+ pending: []
2403
+ };
2404
+ LOCK_QUEUES.set(storePath, created);
2405
+ return created;
2406
+ }
2407
+ async function drainSessionStoreLockQueue(storePath) {
2408
+ const queue = LOCK_QUEUES.get(storePath);
2409
+ if (!queue || queue.running) return;
2410
+ queue.running = true;
2411
+ try {
2412
+ while (queue.pending.length > 0) {
2413
+ const task = queue.pending.shift();
2414
+ if (!task) continue;
2415
+ const remainingTimeoutMs = task.timeoutMs ?? Number.POSITIVE_INFINITY;
2416
+ if (task.timeoutMs != null && remainingTimeoutMs <= 0) {
2417
+ task.reject(lockTimeoutError(storePath));
2418
+ continue;
2419
+ }
2420
+ let lock;
2421
+ let result;
2422
+ let failed;
2423
+ let hasFailure = false;
2424
+ try {
2425
+ lock = await acquireSessionWriteLock({
2426
+ sessionFile: storePath,
2427
+ timeoutMs: remainingTimeoutMs,
2428
+ staleMs: task.staleMs
2429
+ });
2430
+ result = await task.fn();
2431
+ } catch (err) {
2432
+ hasFailure = true;
2433
+ failed = err;
2434
+ } finally {
2435
+ await lock?.release().catch(() => void 0);
2436
+ }
2437
+ if (hasFailure) {
2438
+ task.reject(failed);
2439
+ continue;
2440
+ }
2441
+ task.resolve(result);
2442
+ }
2443
+ } finally {
2444
+ queue.running = false;
2445
+ if (queue.pending.length === 0) LOCK_QUEUES.delete(storePath);
2446
+ else queueMicrotask(() => {
2447
+ drainSessionStoreLockQueue(storePath);
2448
+ });
2449
+ }
2450
+ }
2451
+ async function withSessionStoreLock(storePath, fn, opts = {}) {
2452
+ if (!storePath || typeof storePath !== "string") throw new Error(`withSessionStoreLock: storePath must be a non-empty string, got ${JSON.stringify(storePath)}`);
2453
+ const timeoutMs = opts.timeoutMs ?? 1e4;
2454
+ const staleMs = opts.staleMs ?? 3e4;
2455
+ opts.pollIntervalMs;
2456
+ const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
2457
+ const queue = getOrCreateLockQueue(storePath);
2458
+ return await new Promise((resolve, reject) => {
2459
+ const task = {
2460
+ fn: async () => await fn(),
2461
+ resolve: (value) => resolve(value),
2462
+ reject,
2463
+ timeoutMs: hasTimeout ? timeoutMs : void 0,
2464
+ staleMs
2465
+ };
2466
+ queue.pending.push(task);
2467
+ drainSessionStoreLockQueue(storePath);
2468
+ });
2469
+ }
2470
+ async function updateSessionStoreEntry(params) {
2471
+ const { storePath, sessionKey, update } = params;
2472
+ return await withSessionStoreLock(storePath, async () => {
2473
+ const store = loadSessionStore(storePath, { skipCache: true });
2474
+ const resolved = resolveStoreSessionEntry({
2475
+ store,
2476
+ sessionKey
2477
+ });
2478
+ const existing = resolved.existing;
2479
+ if (!existing) return null;
2480
+ const patch = await update(existing);
2481
+ if (!patch) return existing;
2482
+ const next = mergeSessionEntry(existing, patch);
2483
+ store[resolved.normalizedKey] = next;
2484
+ for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2485
+ await saveSessionStoreUnlocked(storePath, store, { activeSessionKey: resolved.normalizedKey });
2486
+ return next;
2487
+ });
2488
+ }
2489
+ async function recordSessionMetaFromInbound(params) {
2490
+ const { storePath, sessionKey, ctx } = params;
2491
+ const createIfMissing = params.createIfMissing ?? true;
2492
+ return await updateSessionStore(storePath, (store) => {
2493
+ const resolved = resolveStoreSessionEntry({
2494
+ store,
2495
+ sessionKey
2496
+ });
2497
+ const existing = resolved.existing;
2498
+ const patch = deriveSessionMetaPatch({
2499
+ ctx,
2500
+ sessionKey: resolved.normalizedKey,
2501
+ existing,
2502
+ groupResolution: params.groupResolution
2503
+ });
2504
+ if (!patch) {
2505
+ if (existing && resolved.legacyKeys.length > 0) {
2506
+ store[resolved.normalizedKey] = existing;
2507
+ for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2508
+ }
2509
+ return existing ?? null;
2510
+ }
2511
+ if (!existing && !createIfMissing) return null;
2512
+ const next = mergeSessionEntry(existing, patch);
2513
+ store[resolved.normalizedKey] = next;
2514
+ for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2515
+ return next;
2516
+ }, { activeSessionKey: normalizeStoreSessionKey(sessionKey) });
2517
+ }
2518
+ async function updateLastRoute(params) {
2519
+ const { storePath, sessionKey, channel, to, accountId, threadId, ctx } = params;
2520
+ return await withSessionStoreLock(storePath, async () => {
2521
+ const store = loadSessionStore(storePath);
2522
+ const resolved = resolveStoreSessionEntry({
2523
+ store,
2524
+ sessionKey
2525
+ });
2526
+ const existing = resolved.existing;
2527
+ const now = Date.now();
2528
+ const explicitContext = normalizeDeliveryContext(params.deliveryContext);
2529
+ const inlineContext = normalizeDeliveryContext({
2530
+ channel,
2531
+ to,
2532
+ accountId,
2533
+ threadId
2534
+ });
2535
+ const mergedInput = mergeDeliveryContext(explicitContext, inlineContext);
2536
+ const explicitDeliveryContext = params.deliveryContext;
2537
+ const explicitThreadValue = (explicitDeliveryContext != null && Object.prototype.hasOwnProperty.call(explicitDeliveryContext, "threadId") ? explicitDeliveryContext.threadId : void 0) ?? (threadId != null && threadId !== "" ? threadId : void 0);
2538
+ const merged = mergeDeliveryContext(mergedInput, Boolean(explicitContext?.channel || explicitContext?.to || inlineContext?.channel || inlineContext?.to) && explicitThreadValue == null ? removeThreadFromDeliveryContext(deliveryContextFromSession(existing)) : deliveryContextFromSession(existing));
2539
+ const normalized = normalizeSessionDeliveryFields({ deliveryContext: {
2540
+ channel: merged?.channel,
2541
+ to: merged?.to,
2542
+ accountId: merged?.accountId,
2543
+ threadId: merged?.threadId
2544
+ } });
2545
+ const metaPatch = ctx ? deriveSessionMetaPatch({
2546
+ ctx,
2547
+ sessionKey: resolved.normalizedKey,
2548
+ existing,
2549
+ groupResolution: params.groupResolution
2550
+ }) : null;
2551
+ const basePatch = {
2552
+ updatedAt: Math.max(existing?.updatedAt ?? 0, now),
2553
+ deliveryContext: normalized.deliveryContext,
2554
+ lastChannel: normalized.lastChannel,
2555
+ lastTo: normalized.lastTo,
2556
+ lastAccountId: normalized.lastAccountId,
2557
+ lastThreadId: normalized.lastThreadId
2558
+ };
2559
+ const next = mergeSessionEntry(existing, metaPatch ? {
2560
+ ...basePatch,
2561
+ ...metaPatch
2562
+ } : basePatch);
2563
+ store[resolved.normalizedKey] = next;
2564
+ for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2565
+ await saveSessionStoreUnlocked(storePath, store, { activeSessionKey: resolved.normalizedKey });
2566
+ return next;
2567
+ });
2568
+ }
2569
+
2570
+ //#endregion
2571
+ export { formatSessionArchiveTimestamp as $, enforceSessionDiskBudget as A, resolveChannelResetConfig as B, resolveSessionTranscriptCandidates as C, stripInlineDirectiveTagsForDisplay as D, parseInlineDirectives as E, resolveAndPersistSessionFile as F, resolveFreshSessionTotalTokens as G, resolveSessionResetType as H, CURRENT_SESSION_VERSION as I, resolveExplicitAgentSessionKey as J, canonicalizeMainSessionAlias as K, deriveSessionKey as L, parseSessionThreadInfo as M, appendAssistantMessageToSessionTranscript as N, stripInlineDirectiveTagsFromMessageForDisplay as O, resolveMirroredTranscriptText as P, snapshotSessionOrigin as Q, resolveSessionKey as R, readSessionTitleFieldsFromTranscript as S, stripEnvelopeFromMessages as T, resolveThreadFlag as U, resolveSessionResetPolicy as V, DEFAULT_RESET_TRIGGERS as W, resolveMainSessionKeyFromConfig as X, resolveMainSessionKey as Y, deriveSessionMetaPatch as Z, archiveSessionTranscripts as _, recordSessionMetaFromInbound as a, readSessionMessages as b, updateLastRoute as c, deliveryContextFromSession as d, isPrimarySessionTranscriptFileName as et, mergeDeliveryContext as f, archiveFileOnDisk as g, normalizeAccountId as h, readSessionUpdatedAt as i, extractDeliveryInfo as j, sessions_exports as k, updateSessionStore as l, normalizeSessionDeliveryFields as m, loadSessionStore as n, resolveGroupSessionKey as nt, resolveMaintenanceConfig as o, normalizeDeliveryContext as p, resolveAgentMainSessionKey as q, pruneStaleEntries as r, cleanStaleLockFiles as rt, saveSessionStore as s, capEntryCount as t, buildGroupDisplayName as tt, updateSessionStoreEntry as u, capArrayByJsonBytes as v, stripEnvelopeFromMessage as w, readSessionPreviewItemsFromTranscript as x, cleanupArchivedSessionTranscripts as y, evaluateSessionFreshness as z };