@openacp/cli 0.6.10 → 2026.326.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/dist/{action-detect-P7ZE4NEM.js → action-detect-QPA775HB.js} +2 -2
  2. package/dist/adapter-6ANPBSVU.js +16 -0
  3. package/dist/{discord-OMC52Y54.js → adapter-77ZCVABT.js} +520 -365
  4. package/dist/adapter-77ZCVABT.js.map +1 -0
  5. package/dist/{adapter-ZOANORGM.js → adapter-PQGHVG4K.js} +300 -93
  6. package/dist/adapter-PQGHVG4K.js.map +1 -0
  7. package/dist/{admin-6SYB6XCZ.js → admin-GBPZFFAU.js} +3 -3
  8. package/dist/agent-catalog-YHBFERYO.js +11 -0
  9. package/dist/{agent-dependencies-4OWBMZWZ.js → agent-dependencies-WS7Z2DFW.js} +2 -2
  10. package/dist/agent-registry-5LZT7CUB.js +9 -0
  11. package/dist/agent-store-VSHNY5GT.js +9 -0
  12. package/dist/{agents-QO7DKARJ.js → agents-BWU4MRRD.js} +3 -3
  13. package/dist/{api-client-CFQT5U7D.js → api-client-AQPNKXI2.js} +2 -2
  14. package/dist/api-server-3PYLRBCN.js +8 -0
  15. package/dist/api-server-CHVSUDBX.js +11 -0
  16. package/dist/{autostart-X33OGMX6.js → autostart-6JS565RY.js} +3 -3
  17. package/dist/chunk-2CX4IEEC.js +124 -0
  18. package/dist/chunk-2CX4IEEC.js.map +1 -0
  19. package/dist/{chunk-O7CPGUAI.js → chunk-4KGLKKQK.js} +4 -4
  20. package/dist/chunk-4KGLKKQK.js.map +1 -0
  21. package/dist/{chunk-W3EYKZNQ.js → chunk-4WXALZA3.js} +2 -2
  22. package/dist/chunk-4WXALZA3.js.map +1 -0
  23. package/dist/chunk-5OCGO27U.js +125 -0
  24. package/dist/chunk-5OCGO27U.js.map +1 -0
  25. package/dist/{chunk-OWP7RZ62.js → chunk-5ZOFBTOR.js} +118 -262
  26. package/dist/chunk-5ZOFBTOR.js.map +1 -0
  27. package/dist/chunk-6RXVEXF3.js +23 -0
  28. package/dist/chunk-6RXVEXF3.js.map +1 -0
  29. package/dist/{chunk-34M4OS5P.js → chunk-A6Y4GZM3.js} +3 -3
  30. package/dist/chunk-A6Y4GZM3.js.map +1 -0
  31. package/dist/chunk-AD3X6DGK.js +166 -0
  32. package/dist/chunk-AD3X6DGK.js.map +1 -0
  33. package/dist/{chunk-7QJS2XBD.js → chunk-AFKX424Q.js} +2 -2
  34. package/dist/chunk-AFKX424Q.js.map +1 -0
  35. package/dist/chunk-APS6UEFU.js +259 -0
  36. package/dist/chunk-APS6UEFU.js.map +1 -0
  37. package/dist/chunk-BLQUXO7S.js +113 -0
  38. package/dist/chunk-BLQUXO7S.js.map +1 -0
  39. package/dist/{chunk-WTZDAYZX.js → chunk-BQ6FR32N.js} +3 -3
  40. package/dist/chunk-BQ6FR32N.js.map +1 -0
  41. package/dist/chunk-FNRSWA2K.js +1 -0
  42. package/dist/chunk-FQEBWOZR.js +3557 -0
  43. package/dist/chunk-FQEBWOZR.js.map +1 -0
  44. package/dist/{chunk-4CTX774K.js → chunk-GJOY37U7.js} +4 -4
  45. package/dist/chunk-GJOY37U7.js.map +1 -0
  46. package/dist/{chunk-I7WC6E5S.js → chunk-HVBNCPAY.js} +2 -2
  47. package/dist/chunk-HVBNCPAY.js.map +1 -0
  48. package/dist/{chunk-2HMQOC7N.js → chunk-I3CGU5W7.js} +4 -4
  49. package/dist/chunk-I3CGU5W7.js.map +1 -0
  50. package/dist/{chunk-NVPG6JCL.js → chunk-L7YNNBI5.js} +3 -3
  51. package/dist/chunk-L7YNNBI5.js.map +1 -0
  52. package/dist/chunk-LGFWH3AE.js +26 -0
  53. package/dist/chunk-LGFWH3AE.js.map +1 -0
  54. package/dist/chunk-MLF4W5R6.js +101 -0
  55. package/dist/chunk-MLF4W5R6.js.map +1 -0
  56. package/dist/{chunk-KIRH7TUJ.js → chunk-MTSDOSXS.js} +3 -3
  57. package/dist/chunk-MTSDOSXS.js.map +1 -0
  58. package/dist/{chunk-J4SJTKIK.js → chunk-NAM4ERUW.js} +3 -3
  59. package/dist/chunk-NAM4ERUW.js.map +1 -0
  60. package/dist/{chunk-MKHUZLII.js → chunk-NBFIBGAT.js} +39 -25
  61. package/dist/chunk-NBFIBGAT.js.map +1 -0
  62. package/dist/{chunk-BNLGTZ34.js → chunk-O5RG4YZY.js} +3 -3
  63. package/dist/chunk-O5RG4YZY.js.map +1 -0
  64. package/dist/{chunk-JHYXKVV2.js → chunk-ODUM3D6X.js} +2 -2
  65. package/dist/chunk-ODUM3D6X.js.map +1 -0
  66. package/dist/chunk-OYSAN7UX.js +15 -0
  67. package/dist/chunk-OYSAN7UX.js.map +1 -0
  68. package/dist/chunk-P4SNGQNI.js +158 -0
  69. package/dist/chunk-P4SNGQNI.js.map +1 -0
  70. package/dist/{chunk-2CJ46J3C.js → chunk-PPSMUECX.js} +3 -3
  71. package/dist/chunk-PPSMUECX.js.map +1 -0
  72. package/dist/chunk-Q6ZXJTZB.js +56 -0
  73. package/dist/chunk-Q6ZXJTZB.js.map +1 -0
  74. package/dist/{chunk-XANPHG7W.js → chunk-QSDZDHNS.js} +7 -7
  75. package/dist/chunk-QSDZDHNS.js.map +1 -0
  76. package/dist/{chunk-33RP6K2O.js → chunk-QVMEF6FB.js} +6 -6
  77. package/dist/chunk-QVMEF6FB.js.map +1 -0
  78. package/dist/chunk-QWP76EBW.js +536 -0
  79. package/dist/chunk-QWP76EBW.js.map +1 -0
  80. package/dist/{chunk-V5GZQEIY.js → chunk-RBYBSSGO.js} +4 -4
  81. package/dist/chunk-RBYBSSGO.js.map +1 -0
  82. package/dist/{chunk-CS3KCJ5D.js → chunk-RKB2ZK6S.js} +555 -383
  83. package/dist/chunk-RKB2ZK6S.js.map +1 -0
  84. package/dist/{chunk-UKT3G5IA.js → chunk-SHTGQGAU.js} +7 -7
  85. package/dist/chunk-SHTGQGAU.js.map +1 -0
  86. package/dist/chunk-SNPYTMPR.js +51 -0
  87. package/dist/chunk-SNPYTMPR.js.map +1 -0
  88. package/dist/chunk-UB2QB6DE.js +124 -0
  89. package/dist/chunk-UB2QB6DE.js.map +1 -0
  90. package/dist/chunk-UNJUWWQO.js +1108 -0
  91. package/dist/chunk-UNJUWWQO.js.map +1 -0
  92. package/dist/chunk-V2M243KZ.js +445 -0
  93. package/dist/chunk-V2M243KZ.js.map +1 -0
  94. package/dist/chunk-V5JT5TPD.js +97 -0
  95. package/dist/chunk-V5JT5TPD.js.map +1 -0
  96. package/dist/chunk-W26AUH5B.js +61 -0
  97. package/dist/chunk-W26AUH5B.js.map +1 -0
  98. package/dist/chunk-WAAD23KY.js +222 -0
  99. package/dist/chunk-WAAD23KY.js.map +1 -0
  100. package/dist/chunk-WIIZNPCR.js +150 -0
  101. package/dist/chunk-WIIZNPCR.js.map +1 -0
  102. package/dist/chunk-WQCJTU2C.js +84 -0
  103. package/dist/chunk-WQCJTU2C.js.map +1 -0
  104. package/dist/chunk-WVLDNYOJ.js +150 -0
  105. package/dist/chunk-WVLDNYOJ.js.map +1 -0
  106. package/dist/chunk-WXVT3AOY.js +22 -0
  107. package/dist/chunk-WXVT3AOY.js.map +1 -0
  108. package/dist/{chunk-GAK6PIBW.js → chunk-XMMAGAT4.js} +2 -2
  109. package/dist/chunk-XMMAGAT4.js.map +1 -0
  110. package/dist/chunk-Y64XWMJ4.js +212 -0
  111. package/dist/chunk-Y64XWMJ4.js.map +1 -0
  112. package/dist/chunk-YEULD3SG.js +62 -0
  113. package/dist/chunk-YEULD3SG.js.map +1 -0
  114. package/dist/chunk-ZHGPZBS4.js +49 -0
  115. package/dist/chunk-ZHGPZBS4.js.map +1 -0
  116. package/dist/{chunk-JKBFUAJK.js → chunk-ZSLHHQPQ.js} +2 -2
  117. package/dist/chunk-ZSLHHQPQ.js.map +1 -0
  118. package/dist/cli.js +496 -150
  119. package/dist/cli.js.map +1 -1
  120. package/dist/{config-6S355X75.js → config-I4FMCJGZ.js} +3 -3
  121. package/dist/config-editor-HNEKXRLQ.js +11 -0
  122. package/dist/{config-registry-AHYI4MYL.js → config-registry-CUMNXFGK.js} +2 -2
  123. package/dist/context-XM6E22LM.js +10 -0
  124. package/dist/core-plugins-VEUNFTMB.js +27 -0
  125. package/dist/{daemon-4CS6HMB5.js → daemon-PXO5QPCR.js} +4 -4
  126. package/dist/dev-loader-RDC5E2CW.js +50 -0
  127. package/dist/dev-loader-RDC5E2CW.js.map +1 -0
  128. package/dist/discord-NOJQ5PZO.js +8 -0
  129. package/dist/doctor-H72BZOPA.js +10 -0
  130. package/dist/{doctor-OLYBO3V3.js → doctor-RF6BHMCC.js} +5 -5
  131. package/dist/file-service-EUODJAIT.js +9 -0
  132. package/dist/file-service-EUODJAIT.js.map +1 -0
  133. package/dist/index.d.ts +1293 -188
  134. package/dist/index.js +387 -48
  135. package/dist/index.js.map +1 -1
  136. package/dist/{install-cloudflared-Z7VCGOVG.js → install-cloudflared-AN24L4DP.js} +5 -5
  137. package/dist/install-cloudflared-AN24L4DP.js.map +1 -0
  138. package/dist/install-context-XPWTFT3J.js +78 -0
  139. package/dist/install-context-XPWTFT3J.js.map +1 -0
  140. package/dist/{install-jq-HUYSQWKR.js → install-jq-CRVDJGF3.js} +5 -5
  141. package/dist/install-jq-CRVDJGF3.js.map +1 -0
  142. package/dist/{integrate-PNEHRY2I.js → integrate-5C6KSU6D.js} +2 -2
  143. package/dist/integrate-5C6KSU6D.js.map +1 -0
  144. package/dist/{log-NXABYJTT.js → log-LZ7FTRKG.js} +2 -2
  145. package/dist/log-LZ7FTRKG.js.map +1 -0
  146. package/dist/main-T5WVCCFN.js +715 -0
  147. package/dist/main-T5WVCCFN.js.map +1 -0
  148. package/dist/{menu-YY5MKHEK.js → menu-YDQ2LWAR.js} +2 -2
  149. package/dist/menu-YDQ2LWAR.js.map +1 -0
  150. package/dist/{new-session-FEO4J4VU.js → new-session-AVQCNXRG.js} +5 -5
  151. package/dist/new-session-AVQCNXRG.js.map +1 -0
  152. package/dist/notifications-D5BRDNSU.js +9 -0
  153. package/dist/notifications-D5BRDNSU.js.map +1 -0
  154. package/dist/plugin-create-LYF5PP5W.js +327 -0
  155. package/dist/plugin-create-LYF5PP5W.js.map +1 -0
  156. package/dist/plugin-registry-WB3DR67H.js +8 -0
  157. package/dist/plugin-registry-WB3DR67H.js.map +1 -0
  158. package/dist/{post-upgrade-CJG5I7M2.js → post-upgrade-XLHZ6ZB7.js} +8 -8
  159. package/dist/post-upgrade-XLHZ6ZB7.js.map +1 -0
  160. package/dist/read-text-file-IRZM3QLM.js +8 -0
  161. package/dist/read-text-file-IRZM3QLM.js.map +1 -0
  162. package/dist/security-YNRBW6S7.js +9 -0
  163. package/dist/security-YNRBW6S7.js.map +1 -0
  164. package/dist/{session-IUSI7P5S.js → session-KZFA6Z26.js} +4 -4
  165. package/dist/session-KZFA6Z26.js.map +1 -0
  166. package/dist/{settings-RQPAM4KC.js → settings-MFYM7CZO.js} +4 -4
  167. package/dist/settings-MFYM7CZO.js.map +1 -0
  168. package/dist/settings-manager-MD2U4ZV2.js +8 -0
  169. package/dist/settings-manager-MD2U4ZV2.js.map +1 -0
  170. package/dist/{chunk-LCRLAV4G.js → setup-BAI2F24H.js} +154 -492
  171. package/dist/setup-BAI2F24H.js.map +1 -0
  172. package/dist/slack-KH7E3VBS.js +8 -0
  173. package/dist/slack-KH7E3VBS.js.map +1 -0
  174. package/dist/speech-2GHQNRIO.js +9 -0
  175. package/dist/speech-2GHQNRIO.js.map +1 -0
  176. package/dist/telegram-ZDC3JQF2.js +8 -0
  177. package/dist/telegram-ZDC3JQF2.js.map +1 -0
  178. package/dist/tunnel-M47I7H4B.js +8 -0
  179. package/dist/tunnel-M47I7H4B.js.map +1 -0
  180. package/dist/{tunnel-service-CJLUH6SZ.js → tunnel-service-WADYHREX.js} +17 -17
  181. package/dist/tunnel-service-WADYHREX.js.map +1 -0
  182. package/dist/usage-WYNK6ZC5.js +10 -0
  183. package/dist/usage-WYNK6ZC5.js.map +1 -0
  184. package/dist/validators-6CLEZUBD.js +8 -0
  185. package/dist/validators-6CLEZUBD.js.map +1 -0
  186. package/dist/validators-WSTBNKRW.js +12 -0
  187. package/dist/validators-WSTBNKRW.js.map +1 -0
  188. package/package.json +1 -1
  189. package/dist/adapter-ZOANORGM.js.map +0 -1
  190. package/dist/agent-catalog-FC3HGDEQ.js +0 -11
  191. package/dist/agent-registry-WT4NXPYG.js +0 -9
  192. package/dist/agent-store-VZLFPTZU.js +0 -9
  193. package/dist/chunk-2CJ46J3C.js.map +0 -1
  194. package/dist/chunk-2HMQOC7N.js.map +0 -1
  195. package/dist/chunk-33RP6K2O.js.map +0 -1
  196. package/dist/chunk-34M4OS5P.js.map +0 -1
  197. package/dist/chunk-4CTX774K.js.map +0 -1
  198. package/dist/chunk-7QJS2XBD.js.map +0 -1
  199. package/dist/chunk-BNLGTZ34.js.map +0 -1
  200. package/dist/chunk-CS3KCJ5D.js.map +0 -1
  201. package/dist/chunk-GAK6PIBW.js.map +0 -1
  202. package/dist/chunk-I7WC6E5S.js.map +0 -1
  203. package/dist/chunk-J4SJTKIK.js.map +0 -1
  204. package/dist/chunk-JHYXKVV2.js.map +0 -1
  205. package/dist/chunk-JKBFUAJK.js.map +0 -1
  206. package/dist/chunk-KIRH7TUJ.js.map +0 -1
  207. package/dist/chunk-LBIKITQT.js +0 -22
  208. package/dist/chunk-LBIKITQT.js.map +0 -1
  209. package/dist/chunk-LCRLAV4G.js.map +0 -1
  210. package/dist/chunk-LGP2YGRL.js +0 -4880
  211. package/dist/chunk-LGP2YGRL.js.map +0 -1
  212. package/dist/chunk-MKHUZLII.js.map +0 -1
  213. package/dist/chunk-NAMYZIS5.js +0 -1
  214. package/dist/chunk-NVPG6JCL.js.map +0 -1
  215. package/dist/chunk-O7CPGUAI.js.map +0 -1
  216. package/dist/chunk-OWP7RZ62.js.map +0 -1
  217. package/dist/chunk-UKT3G5IA.js.map +0 -1
  218. package/dist/chunk-V5GZQEIY.js.map +0 -1
  219. package/dist/chunk-VOIJ6OY4.js +0 -63
  220. package/dist/chunk-VOIJ6OY4.js.map +0 -1
  221. package/dist/chunk-W3EYKZNQ.js.map +0 -1
  222. package/dist/chunk-WTZDAYZX.js.map +0 -1
  223. package/dist/chunk-XANPHG7W.js.map +0 -1
  224. package/dist/config-editor-QQTZMWGD.js +0 -13
  225. package/dist/discord-OMC52Y54.js.map +0 -1
  226. package/dist/doctor-HZZ5BSHB.js +0 -10
  227. package/dist/install-cloudflared-Z7VCGOVG.js.map +0 -1
  228. package/dist/install-jq-HUYSQWKR.js.map +0 -1
  229. package/dist/integrate-PNEHRY2I.js.map +0 -1
  230. package/dist/main-XOZCLFUK.js +0 -238
  231. package/dist/main-XOZCLFUK.js.map +0 -1
  232. package/dist/post-upgrade-CJG5I7M2.js.map +0 -1
  233. package/dist/setup-XHS4OMPM.js +0 -37
  234. package/dist/tunnel-service-CJLUH6SZ.js.map +0 -1
  235. /package/dist/{action-detect-P7ZE4NEM.js.map → action-detect-QPA775HB.js.map} +0 -0
  236. /package/dist/{admin-6SYB6XCZ.js.map → adapter-6ANPBSVU.js.map} +0 -0
  237. /package/dist/{agent-catalog-FC3HGDEQ.js.map → admin-GBPZFFAU.js.map} +0 -0
  238. /package/dist/{agent-dependencies-4OWBMZWZ.js.map → agent-catalog-YHBFERYO.js.map} +0 -0
  239. /package/dist/{agent-registry-WT4NXPYG.js.map → agent-dependencies-WS7Z2DFW.js.map} +0 -0
  240. /package/dist/{agent-store-VZLFPTZU.js.map → agent-registry-5LZT7CUB.js.map} +0 -0
  241. /package/dist/{agents-QO7DKARJ.js.map → agent-store-VSHNY5GT.js.map} +0 -0
  242. /package/dist/{api-client-CFQT5U7D.js.map → agents-BWU4MRRD.js.map} +0 -0
  243. /package/dist/{autostart-X33OGMX6.js.map → api-client-AQPNKXI2.js.map} +0 -0
  244. /package/dist/{chunk-NAMYZIS5.js.map → api-server-3PYLRBCN.js.map} +0 -0
  245. /package/dist/{config-6S355X75.js.map → api-server-CHVSUDBX.js.map} +0 -0
  246. /package/dist/{config-editor-QQTZMWGD.js.map → autostart-6JS565RY.js.map} +0 -0
  247. /package/dist/{config-registry-AHYI4MYL.js.map → chunk-FNRSWA2K.js.map} +0 -0
  248. /package/dist/{daemon-4CS6HMB5.js.map → config-I4FMCJGZ.js.map} +0 -0
  249. /package/dist/{doctor-HZZ5BSHB.js.map → config-editor-HNEKXRLQ.js.map} +0 -0
  250. /package/dist/{doctor-OLYBO3V3.js.map → config-registry-CUMNXFGK.js.map} +0 -0
  251. /package/dist/{log-NXABYJTT.js.map → context-XM6E22LM.js.map} +0 -0
  252. /package/dist/{menu-YY5MKHEK.js.map → core-plugins-VEUNFTMB.js.map} +0 -0
  253. /package/dist/{new-session-FEO4J4VU.js.map → daemon-PXO5QPCR.js.map} +0 -0
  254. /package/dist/{session-IUSI7P5S.js.map → discord-NOJQ5PZO.js.map} +0 -0
  255. /package/dist/{settings-RQPAM4KC.js.map → doctor-H72BZOPA.js.map} +0 -0
  256. /package/dist/{setup-XHS4OMPM.js.map → doctor-RF6BHMCC.js.map} +0 -0
@@ -0,0 +1,3557 @@
1
+ import {
2
+ AgentCatalog
3
+ } from "./chunk-SHTGQGAU.js";
4
+ import {
5
+ getAgentCapabilities
6
+ } from "./chunk-ZSLHHQPQ.js";
7
+ import {
8
+ readTextFileWithRange
9
+ } from "./chunk-OYSAN7UX.js";
10
+ import {
11
+ createChildLogger,
12
+ createSessionLogger
13
+ } from "./chunk-XMMAGAT4.js";
14
+
15
+ // src/core/utils/streams.ts
16
+ function nodeToWebWritable(nodeStream) {
17
+ return new WritableStream({
18
+ write(chunk) {
19
+ return new Promise((resolve, reject) => {
20
+ nodeStream.write(Buffer.from(chunk), (err) => {
21
+ if (err) reject(err);
22
+ else resolve();
23
+ });
24
+ });
25
+ }
26
+ });
27
+ }
28
+ function nodeToWebReadable(nodeStream) {
29
+ return new ReadableStream({
30
+ start(controller) {
31
+ nodeStream.on("data", (chunk) => {
32
+ controller.enqueue(new Uint8Array(chunk));
33
+ });
34
+ nodeStream.on("end", () => controller.close());
35
+ nodeStream.on("error", (err) => controller.error(err));
36
+ }
37
+ });
38
+ }
39
+
40
+ // src/core/utils/stderr-capture.ts
41
+ var StderrCapture = class {
42
+ constructor(maxLines = 50) {
43
+ this.maxLines = maxLines;
44
+ }
45
+ lines = [];
46
+ append(chunk) {
47
+ this.lines.push(...chunk.split("\n").filter(Boolean));
48
+ if (this.lines.length > this.maxLines) {
49
+ this.lines = this.lines.slice(-this.maxLines);
50
+ }
51
+ }
52
+ getLastLines() {
53
+ return this.lines.join("\n");
54
+ }
55
+ };
56
+
57
+ // src/core/utils/typed-emitter.ts
58
+ var TypedEmitter = class {
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ listeners = /* @__PURE__ */ new Map();
61
+ paused = false;
62
+ buffer = [];
63
+ on(event, listener) {
64
+ let set = this.listeners.get(event);
65
+ if (!set) {
66
+ set = /* @__PURE__ */ new Set();
67
+ this.listeners.set(event, set);
68
+ }
69
+ set.add(listener);
70
+ return this;
71
+ }
72
+ off(event, listener) {
73
+ this.listeners.get(event)?.delete(listener);
74
+ return this;
75
+ }
76
+ emit(event, ...args) {
77
+ if (this.paused) {
78
+ if (this.passthroughFn?.(event, args)) {
79
+ this.deliver(event, args);
80
+ } else {
81
+ this.buffer.push({ event, args });
82
+ }
83
+ return;
84
+ }
85
+ this.deliver(event, args);
86
+ }
87
+ /**
88
+ * Pause event delivery. Events emitted while paused are buffered.
89
+ * Optionally pass a filter to allow specific events through even while paused.
90
+ */
91
+ pause(passthrough) {
92
+ this.paused = true;
93
+ this.passthroughFn = passthrough;
94
+ }
95
+ passthroughFn;
96
+ /** Resume event delivery and replay buffered events in order. */
97
+ resume() {
98
+ this.paused = false;
99
+ this.passthroughFn = void 0;
100
+ const buffered = this.buffer.splice(0);
101
+ for (const { event, args } of buffered) {
102
+ this.deliver(event, args);
103
+ }
104
+ }
105
+ /** Discard all buffered events without delivering them. */
106
+ clearBuffer() {
107
+ this.buffer.length = 0;
108
+ }
109
+ get isPaused() {
110
+ return this.paused;
111
+ }
112
+ get bufferSize() {
113
+ return this.buffer.length;
114
+ }
115
+ removeAllListeners(event) {
116
+ if (event) {
117
+ this.listeners.delete(event);
118
+ } else {
119
+ this.listeners.clear();
120
+ }
121
+ }
122
+ deliver(event, args) {
123
+ const set = this.listeners.get(event);
124
+ if (!set) return;
125
+ for (const listener of set) {
126
+ listener(...args);
127
+ }
128
+ }
129
+ };
130
+
131
+ // src/core/agents/agent-instance.ts
132
+ import { spawn as spawn2, execFileSync } from "child_process";
133
+ import { Transform } from "stream";
134
+ import fs from "fs";
135
+ import path from "path";
136
+ import { ClientSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";
137
+ import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
138
+
139
+ // src/core/sessions/terminal-manager.ts
140
+ import { spawn } from "child_process";
141
+ import { randomUUID } from "crypto";
142
+ var TerminalManager = class {
143
+ terminals = /* @__PURE__ */ new Map();
144
+ maxOutputBytes;
145
+ constructor(maxOutputBytes = 1024 * 1024) {
146
+ this.maxOutputBytes = maxOutputBytes;
147
+ }
148
+ async createTerminal(sessionId, params, middlewareChain) {
149
+ let termCommand = params.command;
150
+ let termArgs = params.args ?? [];
151
+ let termEnvArr = params.env ?? [];
152
+ let termCwd = params.cwd ?? void 0;
153
+ if (middlewareChain) {
154
+ const envRecord = {};
155
+ for (const ev of termEnvArr) {
156
+ envRecord[ev.name] = ev.value;
157
+ }
158
+ const result = await middlewareChain.execute("terminal:beforeCreate", {
159
+ sessionId,
160
+ command: termCommand,
161
+ args: termArgs,
162
+ env: envRecord,
163
+ cwd: termCwd
164
+ }, async (p) => p);
165
+ if (!result) return { terminalId: "" };
166
+ termCommand = result.command;
167
+ termArgs = result.args ?? termArgs;
168
+ termCwd = result.cwd ?? termCwd;
169
+ if (result.env) {
170
+ termEnvArr = Object.entries(result.env).map(([name, value]) => ({ name, value }));
171
+ }
172
+ }
173
+ const terminalId = randomUUID();
174
+ const args = termArgs;
175
+ const env = {};
176
+ for (const ev of termEnvArr) {
177
+ env[ev.name] = ev.value;
178
+ }
179
+ const childProcess = spawn(termCommand, args, {
180
+ cwd: termCwd,
181
+ env: { ...process.env, ...env },
182
+ shell: false
183
+ });
184
+ const state = {
185
+ process: childProcess,
186
+ output: "",
187
+ exitStatus: null,
188
+ command: termCommand,
189
+ startTime: Date.now()
190
+ };
191
+ this.terminals.set(terminalId, state);
192
+ const outputByteLimit = params.outputByteLimit ?? this.maxOutputBytes;
193
+ const appendOutput = (chunk) => {
194
+ state.output += chunk;
195
+ const bytes = Buffer.byteLength(state.output, "utf-8");
196
+ if (bytes > outputByteLimit) {
197
+ const excess = bytes - outputByteLimit;
198
+ state.output = state.output.slice(excess);
199
+ }
200
+ };
201
+ childProcess.stdout?.on(
202
+ "data",
203
+ (chunk) => appendOutput(chunk.toString())
204
+ );
205
+ childProcess.stderr?.on(
206
+ "data",
207
+ (chunk) => appendOutput(chunk.toString())
208
+ );
209
+ childProcess.on("exit", (code, signal) => {
210
+ state.exitStatus = { exitCode: code, signal };
211
+ if (middlewareChain) {
212
+ middlewareChain.execute("terminal:afterExit", {
213
+ sessionId,
214
+ terminalId,
215
+ command: state.command,
216
+ exitCode: code ?? -1,
217
+ durationMs: Date.now() - state.startTime
218
+ }, async (p) => p).catch(() => {
219
+ });
220
+ }
221
+ });
222
+ return { terminalId };
223
+ }
224
+ getOutput(terminalId) {
225
+ const state = this.terminals.get(terminalId);
226
+ if (!state) {
227
+ throw new Error(`Terminal not found: ${terminalId}`);
228
+ }
229
+ return {
230
+ output: state.output,
231
+ truncated: false,
232
+ exitStatus: state.exitStatus ? {
233
+ exitCode: state.exitStatus.exitCode,
234
+ signal: state.exitStatus.signal
235
+ } : void 0
236
+ };
237
+ }
238
+ async waitForExit(terminalId) {
239
+ const state = this.terminals.get(terminalId);
240
+ if (!state) {
241
+ throw new Error(`Terminal not found: ${terminalId}`);
242
+ }
243
+ if (state.exitStatus !== null) {
244
+ return {
245
+ exitCode: state.exitStatus.exitCode,
246
+ signal: state.exitStatus.signal
247
+ };
248
+ }
249
+ return new Promise((resolve) => {
250
+ state.process.on("exit", (code, signal) => {
251
+ resolve({ exitCode: code, signal });
252
+ });
253
+ });
254
+ }
255
+ kill(terminalId) {
256
+ const state = this.terminals.get(terminalId);
257
+ if (!state) {
258
+ throw new Error(`Terminal not found: ${terminalId}`);
259
+ }
260
+ state.process.kill("SIGTERM");
261
+ }
262
+ release(terminalId) {
263
+ const state = this.terminals.get(terminalId);
264
+ if (!state) {
265
+ return;
266
+ }
267
+ state.process.kill("SIGKILL");
268
+ this.terminals.delete(terminalId);
269
+ }
270
+ destroyAll() {
271
+ for (const [, t] of this.terminals) {
272
+ t.process.kill("SIGKILL");
273
+ }
274
+ this.terminals.clear();
275
+ }
276
+ };
277
+
278
+ // src/core/agents/mcp-manager.ts
279
+ var McpManager = class {
280
+ /**
281
+ * Resolve the MCP server config to pass to ACP session methods.
282
+ * Returns the provided config array or an empty array if none given.
283
+ */
284
+ resolve(sessionConfig) {
285
+ return sessionConfig ?? [];
286
+ }
287
+ };
288
+
289
+ // src/core/agents/agent-instance.ts
290
+ var log = createChildLogger({ module: "agent-instance" });
291
+ function findPackageRoot(startDir) {
292
+ let dir = startDir;
293
+ while (dir !== path.dirname(dir)) {
294
+ if (fs.existsSync(path.join(dir, "package.json"))) {
295
+ return dir;
296
+ }
297
+ dir = path.dirname(dir);
298
+ }
299
+ return startDir;
300
+ }
301
+ function resolveAgentCommand(cmd) {
302
+ const searchRoots = [process.cwd()];
303
+ const ownDir = findPackageRoot(import.meta.dirname);
304
+ if (ownDir !== process.cwd()) {
305
+ searchRoots.push(ownDir);
306
+ }
307
+ for (const root of searchRoots) {
308
+ const packageDirs = [
309
+ path.resolve(root, "node_modules", "@zed-industries", cmd, "dist", "index.js"),
310
+ path.resolve(root, "node_modules", cmd, "dist", "index.js")
311
+ ];
312
+ for (const jsPath of packageDirs) {
313
+ if (fs.existsSync(jsPath)) {
314
+ return { command: process.execPath, args: [jsPath] };
315
+ }
316
+ }
317
+ }
318
+ for (const root of searchRoots) {
319
+ const localBin = path.resolve(root, "node_modules", ".bin", cmd);
320
+ if (fs.existsSync(localBin)) {
321
+ const content = fs.readFileSync(localBin, "utf-8");
322
+ if (content.startsWith("#!/usr/bin/env node")) {
323
+ return { command: process.execPath, args: [localBin] };
324
+ }
325
+ const match = content.match(/"([^"]+\.js)"/);
326
+ if (match) {
327
+ const target = path.resolve(path.dirname(localBin), match[1]);
328
+ if (fs.existsSync(target)) {
329
+ return { command: process.execPath, args: [target] };
330
+ }
331
+ }
332
+ }
333
+ }
334
+ try {
335
+ const fullPath = execFileSync("which", [cmd], { encoding: "utf-8" }).trim();
336
+ if (fullPath) {
337
+ const content = fs.readFileSync(fullPath, "utf-8");
338
+ if (content.startsWith("#!/usr/bin/env node")) {
339
+ return { command: process.execPath, args: [fullPath] };
340
+ }
341
+ }
342
+ } catch {
343
+ }
344
+ return { command: cmd, args: [] };
345
+ }
346
+ var AgentInstance = class _AgentInstance extends TypedEmitter {
347
+ connection;
348
+ child;
349
+ stderrCapture;
350
+ terminalManager = new TerminalManager();
351
+ static mcpManager = new McpManager();
352
+ sessionId;
353
+ agentName;
354
+ promptCapabilities;
355
+ middlewareChain;
356
+ // Callback — set by core when wiring events
357
+ onPermissionRequest = async () => "";
358
+ constructor(agentName) {
359
+ super();
360
+ this.agentName = agentName;
361
+ }
362
+ static async spawnSubprocess(agentDef, workingDirectory) {
363
+ const instance = new _AgentInstance(agentDef.name);
364
+ const resolved = resolveAgentCommand(agentDef.command);
365
+ log.debug(
366
+ {
367
+ agentName: agentDef.name,
368
+ command: resolved.command,
369
+ args: resolved.args
370
+ },
371
+ "Resolved agent command"
372
+ );
373
+ instance.child = spawn2(
374
+ resolved.command,
375
+ [...resolved.args, ...agentDef.args],
376
+ {
377
+ stdio: ["pipe", "pipe", "pipe"],
378
+ cwd: workingDirectory,
379
+ env: { ...process.env, ...agentDef.env }
380
+ }
381
+ );
382
+ await new Promise((resolve, reject) => {
383
+ instance.child.on("error", (err) => {
384
+ reject(
385
+ new Error(
386
+ `Failed to spawn agent "${agentDef.name}": ${err.message}. Is "${agentDef.command}" installed?`
387
+ )
388
+ );
389
+ });
390
+ instance.child.on("spawn", () => resolve());
391
+ });
392
+ instance.stderrCapture = new StderrCapture(50);
393
+ instance.child.stderr.on("data", (chunk) => {
394
+ instance.stderrCapture.append(chunk.toString());
395
+ });
396
+ const stdinLogger = new Transform({
397
+ transform(chunk, _enc, cb) {
398
+ log.debug(
399
+ { direction: "send", raw: chunk.toString().trimEnd() },
400
+ "ACP raw"
401
+ );
402
+ cb(null, chunk);
403
+ }
404
+ });
405
+ stdinLogger.pipe(instance.child.stdin);
406
+ const stdoutLogger = new Transform({
407
+ transform(chunk, _enc, cb) {
408
+ log.debug(
409
+ { direction: "recv", raw: chunk.toString().trimEnd() },
410
+ "ACP raw"
411
+ );
412
+ cb(null, chunk);
413
+ }
414
+ });
415
+ instance.child.stdout.pipe(stdoutLogger);
416
+ const toAgent = nodeToWebWritable(stdinLogger);
417
+ const fromAgent = nodeToWebReadable(stdoutLogger);
418
+ const stream = ndJsonStream(toAgent, fromAgent);
419
+ instance.connection = new ClientSideConnection(
420
+ (_agent) => instance.createClient(_agent),
421
+ stream
422
+ );
423
+ const initResponse = await instance.connection.initialize({
424
+ protocolVersion: PROTOCOL_VERSION,
425
+ clientCapabilities: {
426
+ fs: { readTextFile: true, writeTextFile: true },
427
+ terminal: true
428
+ }
429
+ });
430
+ if (initResponse.protocolVersion !== PROTOCOL_VERSION) {
431
+ log.warn(
432
+ { expected: PROTOCOL_VERSION, got: initResponse.protocolVersion },
433
+ "ACP protocol version mismatch \u2014 some features may not work correctly"
434
+ );
435
+ }
436
+ instance.promptCapabilities = initResponse.agentCapabilities?.promptCapabilities;
437
+ log.info(
438
+ { promptCapabilities: instance.promptCapabilities ?? {} },
439
+ "Agent prompt capabilities"
440
+ );
441
+ return instance;
442
+ }
443
+ setupCrashDetection() {
444
+ this.child.on("exit", (code, signal) => {
445
+ log.info(
446
+ { sessionId: this.sessionId, exitCode: code, signal },
447
+ "Agent process exited"
448
+ );
449
+ if (code !== 0 && code !== null) {
450
+ const stderr = this.stderrCapture.getLastLines();
451
+ this.emit("agent_event", {
452
+ type: "error",
453
+ message: `Agent crashed (exit code ${code})
454
+ ${stderr}`
455
+ });
456
+ }
457
+ });
458
+ this.connection.closed.then(() => {
459
+ log.debug({ sessionId: this.sessionId }, "ACP connection closed");
460
+ });
461
+ }
462
+ static async spawn(agentDef, workingDirectory, mcpServers) {
463
+ log.debug(
464
+ { agentName: agentDef.name, command: agentDef.command },
465
+ "Spawning agent"
466
+ );
467
+ const spawnStart = Date.now();
468
+ const instance = await _AgentInstance.spawnSubprocess(
469
+ agentDef,
470
+ workingDirectory
471
+ );
472
+ const resolvedMcp = _AgentInstance.mcpManager.resolve(mcpServers);
473
+ const response = await instance.connection.newSession({
474
+ cwd: workingDirectory,
475
+ mcpServers: resolvedMcp
476
+ });
477
+ instance.sessionId = response.sessionId;
478
+ instance.setupCrashDetection();
479
+ log.info(
480
+ { sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
481
+ "Agent spawn complete"
482
+ );
483
+ return instance;
484
+ }
485
+ static async resume(agentDef, workingDirectory, agentSessionId, mcpServers) {
486
+ log.debug({ agentName: agentDef.name, agentSessionId }, "Resuming agent");
487
+ const spawnStart = Date.now();
488
+ const instance = await _AgentInstance.spawnSubprocess(
489
+ agentDef,
490
+ workingDirectory
491
+ );
492
+ try {
493
+ const response = await instance.connection.unstable_resumeSession({
494
+ sessionId: agentSessionId,
495
+ cwd: workingDirectory
496
+ });
497
+ instance.sessionId = response.sessionId;
498
+ log.info(
499
+ { sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
500
+ "Agent resume complete"
501
+ );
502
+ } catch (err) {
503
+ log.warn(
504
+ { err, agentSessionId },
505
+ "Resume failed, falling back to new session"
506
+ );
507
+ const resolvedMcp = _AgentInstance.mcpManager.resolve(mcpServers);
508
+ const response = await instance.connection.newSession({
509
+ cwd: workingDirectory,
510
+ mcpServers: resolvedMcp
511
+ });
512
+ instance.sessionId = response.sessionId;
513
+ log.info(
514
+ { sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
515
+ "Agent fallback spawn complete"
516
+ );
517
+ }
518
+ instance.setupCrashDetection();
519
+ return instance;
520
+ }
521
+ // createClient — implemented in Task 6b
522
+ createClient(_agent) {
523
+ const self = this;
524
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
525
+ return {
526
+ // ── Session updates ──────────────────────────────────────────────────
527
+ async sessionUpdate(params) {
528
+ const update = params.update;
529
+ let event = null;
530
+ switch (update.sessionUpdate) {
531
+ case "agent_message_chunk":
532
+ if (update.content.type === "text") {
533
+ event = { type: "text", content: update.content.text };
534
+ } else if (update.content.type === "image") {
535
+ const c = update.content;
536
+ event = { type: "image_content", data: c.data, mimeType: c.mimeType };
537
+ } else if (update.content.type === "audio") {
538
+ const c = update.content;
539
+ event = { type: "audio_content", data: c.data, mimeType: c.mimeType };
540
+ } else if (update.content.type === "resource") {
541
+ const c = update.content;
542
+ event = {
543
+ type: "resource_content",
544
+ uri: c.resource.uri,
545
+ name: c.resource.uri,
546
+ text: c.resource.text ?? void 0,
547
+ blob: c.resource.blob ?? void 0,
548
+ mimeType: c.resource.mimeType ?? void 0
549
+ };
550
+ } else if (update.content.type === "resource_link") {
551
+ const c = update.content;
552
+ event = {
553
+ type: "resource_link",
554
+ uri: c.uri,
555
+ name: c.name,
556
+ mimeType: c.mimeType ?? void 0,
557
+ title: c.title ?? void 0,
558
+ description: c.description ?? void 0,
559
+ size: c.size ?? void 0
560
+ };
561
+ }
562
+ break;
563
+ case "agent_thought_chunk":
564
+ if (update.content.type === "text") {
565
+ event = { type: "thought", content: update.content.text };
566
+ }
567
+ break;
568
+ case "tool_call": {
569
+ const tc = update;
570
+ event = {
571
+ type: "tool_call",
572
+ id: update.toolCallId,
573
+ name: update.title,
574
+ kind: update.kind ?? void 0,
575
+ status: update.status ?? "pending",
576
+ content: update.content ?? void 0,
577
+ rawInput: tc.rawInput ?? void 0,
578
+ rawOutput: tc.rawOutput ?? void 0,
579
+ meta: tc._meta ?? void 0
580
+ };
581
+ break;
582
+ }
583
+ case "tool_call_update": {
584
+ const tcu = update;
585
+ event = {
586
+ type: "tool_update",
587
+ id: update.toolCallId,
588
+ name: update.title ?? void 0,
589
+ kind: update.kind ?? void 0,
590
+ status: update.status ?? "pending",
591
+ content: update.content ?? void 0,
592
+ rawInput: tcu.rawInput ?? void 0,
593
+ rawOutput: tcu.rawOutput ?? void 0,
594
+ meta: tcu._meta ?? void 0
595
+ };
596
+ break;
597
+ }
598
+ case "plan":
599
+ event = { type: "plan", entries: update.entries };
600
+ break;
601
+ case "usage_update":
602
+ event = {
603
+ type: "usage",
604
+ tokensUsed: update.used,
605
+ contextSize: update.size,
606
+ cost: update.cost ?? void 0
607
+ };
608
+ break;
609
+ case "available_commands_update":
610
+ event = {
611
+ type: "commands_update",
612
+ commands: update.availableCommands
613
+ };
614
+ break;
615
+ case "session_info_update": {
616
+ const si = update;
617
+ event = {
618
+ type: "session_info_update",
619
+ title: si.title ?? void 0,
620
+ updatedAt: si.updatedAt ?? void 0,
621
+ _meta: si._meta ?? void 0
622
+ };
623
+ break;
624
+ }
625
+ case "current_mode_update": {
626
+ const cm = update;
627
+ event = {
628
+ type: "current_mode_update",
629
+ modeId: cm.currentModeId
630
+ };
631
+ break;
632
+ }
633
+ case "config_option_update": {
634
+ const co = update;
635
+ event = {
636
+ type: "config_option_update",
637
+ options: co.configOptions ?? []
638
+ };
639
+ break;
640
+ }
641
+ case "user_message_chunk": {
642
+ const um = update;
643
+ event = {
644
+ type: "user_message_chunk",
645
+ content: um.content?.text ?? ""
646
+ };
647
+ break;
648
+ }
649
+ // NOTE: model_update is NOT a session update type in the ACP SDK schema.
650
+ // Model changes are applied via the unstable_setSessionModel() method and
651
+ // the response is synchronous — the SDK does not push a model_update
652
+ // notification to the client. Therefore AgentEvent "model_update" cannot
653
+ // originate from sessionUpdate and must be emitted by callers of setModel()
654
+ // if they need to propagate the change downstream.
655
+ default:
656
+ return;
657
+ }
658
+ if (event !== null) {
659
+ self.emit("agent_event", event);
660
+ }
661
+ },
662
+ // ── Permission requests ──────────────────────────────────────────────
663
+ async requestPermission(params) {
664
+ const permissionRequest = {
665
+ id: params.toolCall.toolCallId,
666
+ description: params.toolCall.title ?? params.toolCall.toolCallId,
667
+ options: params.options.map((opt) => ({
668
+ id: opt.optionId,
669
+ label: opt.name,
670
+ isAllow: opt.kind === "allow_once" || opt.kind === "allow_always"
671
+ }))
672
+ };
673
+ const selectedOptionId = await self.onPermissionRequest(permissionRequest);
674
+ return {
675
+ outcome: { outcome: "selected", optionId: selectedOptionId }
676
+ };
677
+ },
678
+ // ── File operations ──────────────────────────────────────────────────
679
+ async readTextFile(params) {
680
+ const p = params;
681
+ if (self.middlewareChain) {
682
+ const result = await self.middlewareChain.execute("fs:beforeRead", { sessionId: self.sessionId, path: p.path, line: p.line, limit: p.limit }, async (r) => r);
683
+ if (!result) return { content: "" };
684
+ p.path = result.path;
685
+ }
686
+ const content = await readTextFileWithRange(p.path, {
687
+ line: p.line ?? void 0,
688
+ limit: p.limit ?? void 0
689
+ });
690
+ return { content };
691
+ },
692
+ async writeTextFile(params) {
693
+ let writePath = params.path;
694
+ let writeContent = params.content;
695
+ if (self.middlewareChain) {
696
+ const result = await self.middlewareChain.execute("fs:beforeWrite", { sessionId: self.sessionId, path: writePath, content: writeContent }, async (r) => r);
697
+ if (!result) return {};
698
+ writePath = result.path;
699
+ writeContent = result.content;
700
+ }
701
+ await fs.promises.mkdir(path.dirname(writePath), { recursive: true });
702
+ await fs.promises.writeFile(writePath, writeContent, "utf-8");
703
+ return {};
704
+ },
705
+ // ── Terminal operations (delegated to TerminalManager) ─────────────
706
+ async createTerminal(params) {
707
+ return self.terminalManager.createTerminal(
708
+ self.sessionId,
709
+ {
710
+ command: params.command,
711
+ args: params.args,
712
+ env: params.env,
713
+ cwd: params.cwd,
714
+ outputByteLimit: params.outputByteLimit ?? MAX_OUTPUT_BYTES
715
+ },
716
+ self.middlewareChain
717
+ );
718
+ },
719
+ async terminalOutput(params) {
720
+ return self.terminalManager.getOutput(params.terminalId);
721
+ },
722
+ async waitForTerminalExit(params) {
723
+ return self.terminalManager.waitForExit(params.terminalId);
724
+ },
725
+ async killTerminal(params) {
726
+ self.terminalManager.kill(params.terminalId);
727
+ return {};
728
+ },
729
+ async releaseTerminal(params) {
730
+ self.terminalManager.release(params.terminalId);
731
+ }
732
+ };
733
+ }
734
+ // ── New ACP methods ──────────────────────────────────────────────────
735
+ async setMode(modeId) {
736
+ await this.connection.setSessionMode({ sessionId: this.sessionId, modeId });
737
+ }
738
+ async setConfigOption(configId, value) {
739
+ return await this.connection.setSessionConfigOption({
740
+ sessionId: this.sessionId,
741
+ configId,
742
+ ...value
743
+ });
744
+ }
745
+ async setModel(modelId) {
746
+ await this.connection.unstable_setSessionModel({
747
+ sessionId: this.sessionId,
748
+ modelId
749
+ });
750
+ }
751
+ async listSessions(cwd, cursor) {
752
+ return await this.connection.listSessions({
753
+ cwd: cwd ?? null,
754
+ cursor: cursor ?? null
755
+ });
756
+ }
757
+ async loadSession(sessionId, cwd, mcpServers) {
758
+ const resolvedMcp = _AgentInstance.mcpManager.resolve(mcpServers);
759
+ return await this.connection.loadSession({
760
+ sessionId,
761
+ cwd,
762
+ mcpServers: resolvedMcp
763
+ });
764
+ }
765
+ async authenticate(methodId) {
766
+ await this.connection.authenticate({ methodId });
767
+ }
768
+ async forkSession(sessionId, cwd, mcpServers) {
769
+ const resolvedMcp = _AgentInstance.mcpManager.resolve(mcpServers);
770
+ return await this.connection.unstable_forkSession({
771
+ sessionId,
772
+ cwd,
773
+ mcpServers: resolvedMcp
774
+ });
775
+ }
776
+ async closeSession(sessionId) {
777
+ await this.connection.unstable_closeSession({ sessionId });
778
+ }
779
+ // ── Prompt & lifecycle ──────────────────────────────────────────────
780
+ async prompt(text, attachments) {
781
+ const contentBlocks = [{ type: "text", text }];
782
+ const SUPPORTED_IMAGE_MIMES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
783
+ for (const att of attachments ?? []) {
784
+ const tooLarge = att.size > 10 * 1024 * 1024;
785
+ if (att.type === "image" && this.promptCapabilities?.image && !tooLarge && SUPPORTED_IMAGE_MIMES.has(att.mimeType)) {
786
+ const data = await fs.promises.readFile(att.filePath);
787
+ contentBlocks.push({ type: "image", data: data.toString("base64"), mimeType: att.mimeType });
788
+ } else if (att.type === "audio" && this.promptCapabilities?.audio && !tooLarge) {
789
+ const data = await fs.promises.readFile(att.filePath);
790
+ contentBlocks.push({ type: "audio", data: data.toString("base64"), mimeType: att.mimeType });
791
+ } else {
792
+ if ((att.type === "image" || att.type === "audio") && !tooLarge) {
793
+ log.debug(
794
+ { type: att.type, capabilities: this.promptCapabilities ?? {} },
795
+ "Agent does not support %s content, falling back to file path",
796
+ att.type
797
+ );
798
+ }
799
+ contentBlocks[0].text += `
800
+
801
+ [Attached file: ${att.filePath}]`;
802
+ }
803
+ }
804
+ return this.connection.prompt({
805
+ sessionId: this.sessionId,
806
+ prompt: contentBlocks
807
+ });
808
+ }
809
+ async cancel() {
810
+ await this.connection.cancel({ sessionId: this.sessionId });
811
+ }
812
+ async destroy() {
813
+ this.terminalManager.destroyAll();
814
+ this.child.kill("SIGTERM");
815
+ setTimeout(() => {
816
+ if (!this.child.killed) this.child.kill("SIGKILL");
817
+ }, 1e4);
818
+ }
819
+ };
820
+
821
+ // src/core/agents/agent-manager.ts
822
+ var AgentManager = class {
823
+ constructor(catalog) {
824
+ this.catalog = catalog;
825
+ }
826
+ getAvailableAgents() {
827
+ const installed = this.catalog.getInstalledEntries();
828
+ return Object.entries(installed).map(([key, agent]) => ({
829
+ name: key,
830
+ command: agent.command,
831
+ args: agent.args,
832
+ env: agent.env
833
+ }));
834
+ }
835
+ getAgent(name) {
836
+ return this.catalog.resolve(name);
837
+ }
838
+ async spawn(agentName, workingDirectory) {
839
+ const agentDef = this.getAgent(agentName);
840
+ if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
841
+ return AgentInstance.spawn(agentDef, workingDirectory);
842
+ }
843
+ async resume(agentName, workingDirectory, agentSessionId) {
844
+ const agentDef = this.getAgent(agentName);
845
+ if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
846
+ return AgentInstance.resume(agentDef, workingDirectory, agentSessionId);
847
+ }
848
+ };
849
+
850
+ // src/core/sessions/prompt-queue.ts
851
+ var PromptQueue = class {
852
+ constructor(processor, onError) {
853
+ this.processor = processor;
854
+ this.onError = onError;
855
+ }
856
+ queue = [];
857
+ processing = false;
858
+ abortController = null;
859
+ async enqueue(text, attachments) {
860
+ if (this.processing) {
861
+ return new Promise((resolve) => {
862
+ this.queue.push({ text, attachments, resolve });
863
+ });
864
+ }
865
+ await this.process(text, attachments);
866
+ }
867
+ async process(text, attachments) {
868
+ this.processing = true;
869
+ this.abortController = new AbortController();
870
+ const { signal } = this.abortController;
871
+ try {
872
+ await Promise.race([
873
+ this.processor(text, attachments),
874
+ new Promise((_, reject) => {
875
+ signal.addEventListener("abort", () => reject(new Error("Prompt aborted")), { once: true });
876
+ })
877
+ ]);
878
+ } catch (err) {
879
+ if (!(err instanceof Error && err.message === "Prompt aborted")) {
880
+ this.onError?.(err);
881
+ }
882
+ } finally {
883
+ this.abortController = null;
884
+ this.processing = false;
885
+ this.drainNext();
886
+ }
887
+ }
888
+ drainNext() {
889
+ const next = this.queue.shift();
890
+ if (next) {
891
+ this.process(next.text, next.attachments).then(next.resolve);
892
+ }
893
+ }
894
+ clear() {
895
+ if (this.abortController) {
896
+ this.abortController.abort();
897
+ }
898
+ for (const item of this.queue) {
899
+ item.resolve();
900
+ }
901
+ this.queue = [];
902
+ }
903
+ get pending() {
904
+ return this.queue.length;
905
+ }
906
+ get isProcessing() {
907
+ return this.processing;
908
+ }
909
+ };
910
+
911
+ // src/core/sessions/permission-gate.ts
912
+ var DEFAULT_TIMEOUT_MS = 10 * 60 * 1e3;
913
+ var PermissionGate = class {
914
+ request;
915
+ resolveFn;
916
+ rejectFn;
917
+ settled = false;
918
+ timeoutTimer;
919
+ timeoutMs;
920
+ constructor(timeoutMs) {
921
+ this.timeoutMs = timeoutMs ?? DEFAULT_TIMEOUT_MS;
922
+ }
923
+ setPending(request) {
924
+ this.request = request;
925
+ this.settled = false;
926
+ this.clearTimeout();
927
+ return new Promise((resolve, reject) => {
928
+ this.resolveFn = resolve;
929
+ this.rejectFn = reject;
930
+ this.timeoutTimer = setTimeout(() => {
931
+ this.reject("Permission request timed out (no response received)");
932
+ }, this.timeoutMs);
933
+ });
934
+ }
935
+ resolve(optionId) {
936
+ if (this.settled || !this.resolveFn) return;
937
+ this.settled = true;
938
+ this.clearTimeout();
939
+ this.resolveFn(optionId);
940
+ this.cleanup();
941
+ }
942
+ reject(reason) {
943
+ if (this.settled || !this.rejectFn) return;
944
+ this.settled = true;
945
+ this.clearTimeout();
946
+ this.rejectFn(new Error(reason ?? "Permission rejected"));
947
+ this.cleanup();
948
+ }
949
+ get isPending() {
950
+ return !!this.request && !this.settled;
951
+ }
952
+ get currentRequest() {
953
+ return this.isPending ? this.request : void 0;
954
+ }
955
+ /** The request ID of the current pending request, undefined after settlement */
956
+ get requestId() {
957
+ return this.request?.id;
958
+ }
959
+ clearTimeout() {
960
+ if (this.timeoutTimer) {
961
+ clearTimeout(this.timeoutTimer);
962
+ this.timeoutTimer = void 0;
963
+ }
964
+ }
965
+ cleanup() {
966
+ this.request = void 0;
967
+ this.resolveFn = void 0;
968
+ this.rejectFn = void 0;
969
+ }
970
+ };
971
+
972
+ // src/core/sessions/session.ts
973
+ import { nanoid } from "nanoid";
974
+ import * as fs2 from "fs";
975
+ var moduleLog = createChildLogger({ module: "session" });
976
+ var TTS_PROMPT_INSTRUCTION = `
977
+
978
+ Additionally, include a [TTS]...[/TTS] block with a spoken-friendly summary of your response. Focus on key information, decisions the user needs to make, or actions required. The agent decides what to say and how long. Respond in the same language the user is using. This instruction applies to this message only.`;
979
+ var TTS_BLOCK_REGEX = /\[TTS\]([\s\S]*?)\[\/TTS\]/;
980
+ var TTS_MAX_LENGTH = 5e3;
981
+ var TTS_TIMEOUT_MS = 3e4;
982
+ var VALID_TRANSITIONS = {
983
+ initializing: /* @__PURE__ */ new Set(["active", "error"]),
984
+ active: /* @__PURE__ */ new Set(["error", "finished", "cancelled"]),
985
+ error: /* @__PURE__ */ new Set(["active"]),
986
+ cancelled: /* @__PURE__ */ new Set(["active"]),
987
+ finished: /* @__PURE__ */ new Set()
988
+ };
989
+ var Session = class extends TypedEmitter {
990
+ id;
991
+ channelId;
992
+ threadId = "";
993
+ agentName;
994
+ workingDirectory;
995
+ agentInstance;
996
+ agentSessionId = "";
997
+ _status = "initializing";
998
+ name;
999
+ createdAt = /* @__PURE__ */ new Date();
1000
+ voiceMode = "off";
1001
+ dangerousMode = false;
1002
+ currentMode;
1003
+ availableModes = [];
1004
+ configOptions = [];
1005
+ currentModel;
1006
+ availableModels = [];
1007
+ agentCapabilities;
1008
+ archiving = false;
1009
+ promptCount = 0;
1010
+ log;
1011
+ middlewareChain;
1012
+ permissionGate = new PermissionGate();
1013
+ queue;
1014
+ speechService;
1015
+ pendingContext = null;
1016
+ constructor(opts) {
1017
+ super();
1018
+ this.id = opts.id || nanoid(12);
1019
+ this.channelId = opts.channelId;
1020
+ this.agentName = opts.agentName;
1021
+ this.workingDirectory = opts.workingDirectory;
1022
+ this.agentInstance = opts.agentInstance;
1023
+ this.speechService = opts.speechService;
1024
+ this.log = createSessionLogger(this.id, moduleLog);
1025
+ this.log.info({ agentName: this.agentName }, "Session created");
1026
+ this.queue = new PromptQueue(
1027
+ (text, attachments) => this.processPrompt(text, attachments),
1028
+ (err) => {
1029
+ this.fail("Prompt execution failed");
1030
+ this.log.error({ err }, "Prompt execution failed");
1031
+ }
1032
+ );
1033
+ }
1034
+ // --- State Machine ---
1035
+ get status() {
1036
+ return this._status;
1037
+ }
1038
+ /** Transition to active — from initializing, error, or cancelled */
1039
+ activate() {
1040
+ this.transition("active");
1041
+ }
1042
+ /** Transition to error — from initializing or active */
1043
+ fail(reason) {
1044
+ this.transition("error");
1045
+ this.emit("error", new Error(reason));
1046
+ }
1047
+ /** Transition to finished — from active only. Emits session_end for backward compat. */
1048
+ finish(reason) {
1049
+ this.transition("finished");
1050
+ this.emit("session_end", reason ?? "completed");
1051
+ }
1052
+ /** Transition to cancelled — from active only (terminal session cancel) */
1053
+ markCancelled() {
1054
+ this.transition("cancelled");
1055
+ }
1056
+ transition(to) {
1057
+ const from = this._status;
1058
+ const allowed = VALID_TRANSITIONS[from];
1059
+ if (!allowed?.has(to)) {
1060
+ throw new Error(
1061
+ `Invalid session transition: ${from} \u2192 ${to}`
1062
+ );
1063
+ }
1064
+ this._status = to;
1065
+ this.log.debug({ from, to }, "Session status transition");
1066
+ this.emit("status_change", from, to);
1067
+ }
1068
+ /** Number of prompts waiting in queue */
1069
+ get queueDepth() {
1070
+ return this.queue.pending;
1071
+ }
1072
+ get promptRunning() {
1073
+ return this.queue.isProcessing;
1074
+ }
1075
+ // --- Context Injection ---
1076
+ setContext(markdown) {
1077
+ this.pendingContext = markdown;
1078
+ }
1079
+ // --- Voice Mode ---
1080
+ setVoiceMode(mode) {
1081
+ this.voiceMode = mode;
1082
+ this.log.info({ voiceMode: mode }, "TTS mode changed");
1083
+ }
1084
+ // --- Public API ---
1085
+ async enqueuePrompt(text, attachments) {
1086
+ if (this.middlewareChain) {
1087
+ const payload = { text, attachments, sessionId: this.id };
1088
+ const result = await this.middlewareChain.execute("agent:beforePrompt", payload, async (p) => p);
1089
+ if (!result) return;
1090
+ text = result.text;
1091
+ attachments = result.attachments;
1092
+ }
1093
+ await this.queue.enqueue(text, attachments);
1094
+ }
1095
+ async processPrompt(text, attachments) {
1096
+ if (text === "\0__warmup__") {
1097
+ await this.runWarmup();
1098
+ return;
1099
+ }
1100
+ this.promptCount++;
1101
+ if (this._status === "initializing") {
1102
+ this.activate();
1103
+ }
1104
+ const promptStart = Date.now();
1105
+ this.log.debug("Prompt execution started");
1106
+ if (this.pendingContext) {
1107
+ text = `[CONVERSATION HISTORY - This is context from previous sessions, not current conversation]
1108
+
1109
+ ${this.pendingContext}
1110
+
1111
+ [END CONVERSATION HISTORY]
1112
+
1113
+ ${text}`;
1114
+ this.pendingContext = null;
1115
+ this.log.debug("Context injected into prompt");
1116
+ }
1117
+ const processed = await this.maybeTranscribeAudio(text, attachments);
1118
+ const ttsActive = this.voiceMode !== "off" && !!this.speechService?.isTTSAvailable();
1119
+ if (ttsActive) {
1120
+ processed.text += TTS_PROMPT_INSTRUCTION;
1121
+ if (this.voiceMode === "next") {
1122
+ this.voiceMode = "off";
1123
+ }
1124
+ }
1125
+ let accumulatedText = "";
1126
+ const accumulatorListener = ttsActive ? (event) => {
1127
+ if (event.type === "text") {
1128
+ accumulatedText += event.content;
1129
+ }
1130
+ } : null;
1131
+ if (accumulatorListener) {
1132
+ this.on("agent_event", accumulatorListener);
1133
+ }
1134
+ if (this.middlewareChain) {
1135
+ this.middlewareChain.execute("turn:start", { sessionId: this.id, promptText: processed.text, promptNumber: this.promptCount }, async (p) => p).catch(() => {
1136
+ });
1137
+ }
1138
+ let stopReason = "end_turn";
1139
+ try {
1140
+ const response = await this.agentInstance.prompt(processed.text, processed.attachments);
1141
+ if (response && typeof response === "object" && "stopReason" in response) {
1142
+ stopReason = response.stopReason ?? "end_turn";
1143
+ }
1144
+ } finally {
1145
+ if (accumulatorListener) {
1146
+ this.off("agent_event", accumulatorListener);
1147
+ }
1148
+ }
1149
+ if (this.middlewareChain) {
1150
+ this.middlewareChain.execute("turn:end", { sessionId: this.id, stopReason, durationMs: Date.now() - promptStart }, async (p) => p).catch(() => {
1151
+ });
1152
+ }
1153
+ this.log.info(
1154
+ { durationMs: Date.now() - promptStart },
1155
+ "Prompt execution completed"
1156
+ );
1157
+ if (ttsActive && accumulatedText) {
1158
+ this.processTTSResponse(accumulatedText).catch((err) => {
1159
+ this.log.warn({ err }, "TTS post-processing failed");
1160
+ });
1161
+ }
1162
+ if (!this.name) {
1163
+ await this.autoName();
1164
+ }
1165
+ }
1166
+ async maybeTranscribeAudio(text, attachments) {
1167
+ if (!attachments?.length || !this.speechService) {
1168
+ return { text, attachments };
1169
+ }
1170
+ const hasAudioCapability = this.agentInstance.promptCapabilities?.audio === true;
1171
+ if (hasAudioCapability) {
1172
+ return { text, attachments };
1173
+ }
1174
+ if (!this.speechService.isSTTAvailable()) {
1175
+ return { text, attachments };
1176
+ }
1177
+ let transcribedText = text;
1178
+ const remainingAttachments = [];
1179
+ for (const att of attachments) {
1180
+ if (att.type !== "audio") {
1181
+ remainingAttachments.push(att);
1182
+ continue;
1183
+ }
1184
+ try {
1185
+ const audioPath = att.originalFilePath || att.filePath;
1186
+ const audioMime = att.originalFilePath ? "audio/ogg" : att.mimeType;
1187
+ const audioBuffer = await fs2.promises.readFile(audioPath);
1188
+ const result = await this.speechService.transcribe(audioBuffer, audioMime);
1189
+ this.log.info({ provider: "stt", duration: result.duration }, "Voice transcribed");
1190
+ this.emit("agent_event", {
1191
+ type: "system_message",
1192
+ message: `\u{1F3A4} You said: ${result.text}`
1193
+ });
1194
+ transcribedText = transcribedText.replace(/\[Audio:\s*[^\]]*\]\s*/g, "").trim();
1195
+ transcribedText = transcribedText ? `${transcribedText}
1196
+ ${result.text}` : result.text;
1197
+ } catch (err) {
1198
+ this.log.warn({ err }, "STT transcription failed, keeping audio attachment");
1199
+ this.emit("agent_event", {
1200
+ type: "error",
1201
+ message: `Voice transcription failed: ${err.message}`
1202
+ });
1203
+ remainingAttachments.push(att);
1204
+ }
1205
+ }
1206
+ return {
1207
+ text: transcribedText,
1208
+ attachments: remainingAttachments.length > 0 ? remainingAttachments : void 0
1209
+ };
1210
+ }
1211
+ async processTTSResponse(responseText) {
1212
+ const match = TTS_BLOCK_REGEX.exec(responseText);
1213
+ if (!match?.[1]) {
1214
+ this.log.debug("No [TTS] block found in response, skipping synthesis");
1215
+ return;
1216
+ }
1217
+ let ttsText = match[1].trim();
1218
+ if (!ttsText) return;
1219
+ if (ttsText.length > TTS_MAX_LENGTH) {
1220
+ ttsText = ttsText.slice(0, TTS_MAX_LENGTH);
1221
+ }
1222
+ try {
1223
+ const timeoutPromise = new Promise(
1224
+ (_, reject) => setTimeout(() => reject(new Error("TTS synthesis timed out")), TTS_TIMEOUT_MS)
1225
+ );
1226
+ const result = await Promise.race([
1227
+ this.speechService.synthesize(ttsText),
1228
+ timeoutPromise
1229
+ ]);
1230
+ const base64 = result.audioBuffer.toString("base64");
1231
+ this.emit("agent_event", {
1232
+ type: "audio_content",
1233
+ data: base64,
1234
+ mimeType: result.mimeType
1235
+ });
1236
+ this.log.info("TTS synthesis completed");
1237
+ } catch (err) {
1238
+ this.log.warn({ err }, "TTS synthesis failed, skipping");
1239
+ }
1240
+ }
1241
+ // NOTE: This injects a summary prompt into the agent's conversation history.
1242
+ async autoName() {
1243
+ let title = "";
1244
+ const captureHandler = (event) => {
1245
+ if (event.type === "text") title += event.content;
1246
+ };
1247
+ this.pause((event) => event !== "agent_event");
1248
+ this.agentInstance.on("agent_event", captureHandler);
1249
+ try {
1250
+ await this.agentInstance.prompt(
1251
+ "Summarize this conversation in max 5 words for a topic title. Reply ONLY with the title, nothing else."
1252
+ );
1253
+ this.name = title.trim().slice(0, 50) || `Session ${this.id.slice(0, 6)}`;
1254
+ this.log.info({ name: this.name }, "Session auto-named");
1255
+ this.emit("named", this.name);
1256
+ } catch {
1257
+ this.name = `Session ${this.id.slice(0, 6)}`;
1258
+ } finally {
1259
+ this.agentInstance.off("agent_event", captureHandler);
1260
+ this.clearBuffer();
1261
+ this.resume();
1262
+ }
1263
+ }
1264
+ async generateSummary(timeoutMs = 15e3) {
1265
+ let summary = "";
1266
+ let timer;
1267
+ const captureHandler = (event) => {
1268
+ if (event.type === "text") summary += event.content;
1269
+ };
1270
+ this.pause((event) => event !== "agent_event");
1271
+ this.agentInstance.on("agent_event", captureHandler);
1272
+ try {
1273
+ const promptPromise = this.agentInstance.prompt(
1274
+ "Summarize what you've accomplished so far in this session in 2-3 sentences. Include: key files changed, decisions made, and current status. Reply ONLY with the summary, nothing else."
1275
+ );
1276
+ const timeoutPromise = new Promise((_, reject) => {
1277
+ timer = setTimeout(() => reject(new Error("summary timeout")), timeoutMs);
1278
+ });
1279
+ await Promise.race([promptPromise, timeoutPromise]);
1280
+ return summary.trim().slice(0, 500);
1281
+ } catch {
1282
+ this.log.warn("Failed to generate session summary");
1283
+ return "";
1284
+ } finally {
1285
+ if (timer) clearTimeout(timer);
1286
+ this.agentInstance.off("agent_event", captureHandler);
1287
+ this.clearBuffer();
1288
+ this.resume();
1289
+ }
1290
+ }
1291
+ /** Fire-and-forget warm-up: primes model cache while user types their first message */
1292
+ async warmup() {
1293
+ await this.queue.enqueue("\0__warmup__");
1294
+ }
1295
+ async runWarmup() {
1296
+ this.pause((_event, args) => {
1297
+ const agentEvent = args[0];
1298
+ return agentEvent?.type === "commands_update";
1299
+ });
1300
+ try {
1301
+ const start = Date.now();
1302
+ await this.agentInstance.prompt('Reply with only "ready".');
1303
+ this.activate();
1304
+ this.log.info({ durationMs: Date.now() - start }, "Warm-up complete");
1305
+ } catch (err) {
1306
+ this.log.error({ err }, "Warm-up failed");
1307
+ } finally {
1308
+ this.clearBuffer();
1309
+ this.resume();
1310
+ }
1311
+ }
1312
+ // --- ACP Mode / Config / Model State ---
1313
+ setInitialAcpState(state) {
1314
+ if (state.modes) {
1315
+ this.currentMode = state.modes.currentModeId;
1316
+ this.availableModes = state.modes.availableModes;
1317
+ }
1318
+ if (state.configOptions) {
1319
+ this.configOptions = state.configOptions;
1320
+ }
1321
+ if (state.models) {
1322
+ this.currentModel = state.models.currentModelId;
1323
+ this.availableModels = state.models.availableModels;
1324
+ }
1325
+ if (state.agentCapabilities) {
1326
+ this.agentCapabilities = state.agentCapabilities;
1327
+ }
1328
+ }
1329
+ /** Set session name explicitly and emit 'named' event */
1330
+ setName(name) {
1331
+ this.name = name;
1332
+ this.emit("named", name);
1333
+ }
1334
+ async updateMode(modeId) {
1335
+ if (this.middlewareChain) {
1336
+ const result = await this.middlewareChain.execute("mode:beforeChange", { sessionId: this.id, fromMode: this.currentMode, toMode: modeId }, async (p) => p);
1337
+ if (!result) return;
1338
+ }
1339
+ this.currentMode = modeId;
1340
+ }
1341
+ async updateConfigOptions(options) {
1342
+ if (this.middlewareChain) {
1343
+ const result = await this.middlewareChain.execute("config:beforeChange", { sessionId: this.id, configId: "options", oldValue: this.configOptions, newValue: options }, async (p) => p);
1344
+ if (!result) return;
1345
+ }
1346
+ this.configOptions = options;
1347
+ }
1348
+ async updateModel(modelId) {
1349
+ if (this.middlewareChain) {
1350
+ const result = await this.middlewareChain.execute("model:beforeChange", { sessionId: this.id, fromModel: this.currentModel, toModel: modelId }, async (p) => p);
1351
+ if (!result) return;
1352
+ }
1353
+ this.currentModel = modelId;
1354
+ }
1355
+ /** Cancel the current prompt and clear the queue. Stays in active state. */
1356
+ async abortPrompt() {
1357
+ if (this.middlewareChain) {
1358
+ const result = await this.middlewareChain.execute("agent:beforeCancel", { sessionId: this.id }, async (p) => p);
1359
+ if (!result) return;
1360
+ }
1361
+ this.queue.clear();
1362
+ this.log.info("Prompt aborted");
1363
+ await this.agentInstance.cancel();
1364
+ }
1365
+ async destroy() {
1366
+ this.log.info("Session destroyed");
1367
+ await this.agentInstance.destroy();
1368
+ }
1369
+ };
1370
+
1371
+ // src/core/sessions/session-manager.ts
1372
+ var SessionManager = class {
1373
+ sessions = /* @__PURE__ */ new Map();
1374
+ store;
1375
+ eventBus;
1376
+ middlewareChain;
1377
+ setEventBus(eventBus) {
1378
+ this.eventBus = eventBus;
1379
+ }
1380
+ constructor(store = null) {
1381
+ this.store = store;
1382
+ }
1383
+ async createSession(channelId, agentName, workingDirectory, agentManager) {
1384
+ const agentInstance = await agentManager.spawn(agentName, workingDirectory);
1385
+ const session = new Session({
1386
+ channelId,
1387
+ agentName,
1388
+ workingDirectory,
1389
+ agentInstance
1390
+ });
1391
+ this.sessions.set(session.id, session);
1392
+ session.agentSessionId = session.agentInstance.sessionId;
1393
+ if (this.store) {
1394
+ await this.store.save({
1395
+ sessionId: session.id,
1396
+ agentSessionId: session.agentInstance.sessionId,
1397
+ agentName: session.agentName,
1398
+ workingDir: session.workingDirectory,
1399
+ channelId,
1400
+ status: session.status,
1401
+ createdAt: session.createdAt.toISOString(),
1402
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString(),
1403
+ name: session.name,
1404
+ dangerousMode: false,
1405
+ platform: {}
1406
+ });
1407
+ }
1408
+ return session;
1409
+ }
1410
+ getSession(sessionId) {
1411
+ return this.sessions.get(sessionId);
1412
+ }
1413
+ getSessionByThread(channelId, threadId) {
1414
+ for (const session of this.sessions.values()) {
1415
+ if (session.channelId === channelId && session.threadId === threadId) {
1416
+ return session;
1417
+ }
1418
+ }
1419
+ return void 0;
1420
+ }
1421
+ getSessionByAgentSessionId(agentSessionId) {
1422
+ for (const session of this.sessions.values()) {
1423
+ if (session.agentSessionId === agentSessionId) {
1424
+ return session;
1425
+ }
1426
+ }
1427
+ return void 0;
1428
+ }
1429
+ getRecordByAgentSessionId(agentSessionId) {
1430
+ return this.store?.findByAgentSessionId(agentSessionId);
1431
+ }
1432
+ getRecordByThread(channelId, threadId) {
1433
+ return this.store?.findByPlatform(
1434
+ channelId,
1435
+ (p) => String(p.topicId) === threadId || p.threadId === threadId
1436
+ );
1437
+ }
1438
+ registerSession(session) {
1439
+ this.sessions.set(session.id, session);
1440
+ }
1441
+ async patchRecord(sessionId, patch) {
1442
+ if (!this.store) return;
1443
+ const record = this.store.get(sessionId);
1444
+ if (record) {
1445
+ await this.store.save({ ...record, ...patch });
1446
+ } else if (patch.sessionId) {
1447
+ await this.store.save(patch);
1448
+ }
1449
+ }
1450
+ getSessionRecord(sessionId) {
1451
+ return this.store?.get(sessionId);
1452
+ }
1453
+ async cancelSession(sessionId) {
1454
+ const session = this.sessions.get(sessionId);
1455
+ if (session) {
1456
+ await session.abortPrompt();
1457
+ session.markCancelled();
1458
+ }
1459
+ if (this.store) {
1460
+ const record = this.store.get(sessionId);
1461
+ if (record && record.status !== "cancelled") {
1462
+ await this.store.save({ ...record, status: "cancelled" });
1463
+ }
1464
+ }
1465
+ if (this.middlewareChain) {
1466
+ this.middlewareChain.execute("session:afterDestroy", { sessionId }, async (p) => p).catch(() => {
1467
+ });
1468
+ }
1469
+ }
1470
+ listSessions(channelId) {
1471
+ const all = Array.from(this.sessions.values());
1472
+ if (channelId) return all.filter((s) => s.channelId === channelId);
1473
+ return all;
1474
+ }
1475
+ listRecords(filter) {
1476
+ if (!this.store) return [];
1477
+ let records = this.store.list();
1478
+ if (filter?.statuses?.length) {
1479
+ records = records.filter((r) => filter.statuses.includes(r.status));
1480
+ }
1481
+ return records;
1482
+ }
1483
+ async removeRecord(sessionId) {
1484
+ if (!this.store) return;
1485
+ await this.store.remove(sessionId);
1486
+ this.eventBus?.emit("session:deleted", { sessionId });
1487
+ }
1488
+ async destroyAll() {
1489
+ if (this.store) {
1490
+ for (const session of this.sessions.values()) {
1491
+ const record = this.store.get(session.id);
1492
+ if (record) {
1493
+ await this.store.save({ ...record, status: "finished" });
1494
+ }
1495
+ }
1496
+ }
1497
+ const sessionIds = [...this.sessions.keys()];
1498
+ for (const session of this.sessions.values()) {
1499
+ await session.destroy();
1500
+ }
1501
+ this.sessions.clear();
1502
+ if (this.middlewareChain) {
1503
+ for (const sessionId of sessionIds) {
1504
+ this.middlewareChain.execute("session:afterDestroy", { sessionId }, async (p) => p).catch(() => {
1505
+ });
1506
+ }
1507
+ }
1508
+ }
1509
+ };
1510
+
1511
+ // src/core/sessions/session-bridge.ts
1512
+ var log2 = createChildLogger({ module: "session-bridge" });
1513
+ var SessionBridge = class {
1514
+ constructor(session, adapter, deps) {
1515
+ this.session = session;
1516
+ this.adapter = adapter;
1517
+ this.deps = deps;
1518
+ }
1519
+ connected = false;
1520
+ agentEventHandler;
1521
+ sessionEventHandler;
1522
+ statusChangeHandler;
1523
+ namedHandler;
1524
+ /** Send message to adapter, optionally running through message:outgoing middleware */
1525
+ async sendMessage(sessionId, message) {
1526
+ const mw = this.deps.middlewareChain;
1527
+ if (mw) {
1528
+ const result = await mw.execute("message:outgoing", { sessionId, message }, async (m) => m);
1529
+ if (!result) return;
1530
+ this.adapter.sendMessage(sessionId, result.message);
1531
+ } else {
1532
+ this.adapter.sendMessage(sessionId, message);
1533
+ }
1534
+ }
1535
+ connect() {
1536
+ if (this.connected) return;
1537
+ this.connected = true;
1538
+ this.wireAgentToSession();
1539
+ this.wireSessionToAdapter();
1540
+ this.wirePermissions();
1541
+ this.wireLifecycle();
1542
+ }
1543
+ disconnect() {
1544
+ if (!this.connected) return;
1545
+ this.connected = false;
1546
+ if (this.agentEventHandler) {
1547
+ this.session.agentInstance.off("agent_event", this.agentEventHandler);
1548
+ }
1549
+ if (this.sessionEventHandler) {
1550
+ this.session.off("agent_event", this.sessionEventHandler);
1551
+ }
1552
+ if (this.statusChangeHandler) {
1553
+ this.session.off("status_change", this.statusChangeHandler);
1554
+ }
1555
+ if (this.namedHandler) {
1556
+ this.session.off("named", this.namedHandler);
1557
+ }
1558
+ this.session.agentInstance.onPermissionRequest = async () => "";
1559
+ }
1560
+ wireAgentToSession() {
1561
+ this.agentEventHandler = (event) => {
1562
+ this.session.emit("agent_event", event);
1563
+ };
1564
+ this.session.agentInstance.on("agent_event", this.agentEventHandler);
1565
+ }
1566
+ wireSessionToAdapter() {
1567
+ this.sessionEventHandler = (event) => {
1568
+ const mw = this.deps.middlewareChain;
1569
+ if (mw) {
1570
+ mw.execute("agent:beforeEvent", { sessionId: this.session.id, event }, async (e) => e).then((result) => {
1571
+ if (!result) return;
1572
+ const transformedEvent = result.event;
1573
+ const outgoing = this.handleAgentEvent(transformedEvent);
1574
+ mw.execute("agent:afterEvent", {
1575
+ sessionId: this.session.id,
1576
+ event: transformedEvent,
1577
+ outgoingMessage: outgoing ?? { type: "text", text: "" }
1578
+ }, async (e) => e).catch(() => {
1579
+ });
1580
+ }).catch(() => {
1581
+ this.handleAgentEvent(event);
1582
+ });
1583
+ } else {
1584
+ this.handleAgentEvent(event);
1585
+ }
1586
+ };
1587
+ this.session.on("agent_event", this.sessionEventHandler);
1588
+ }
1589
+ handleAgentEvent(event) {
1590
+ const session = this.session;
1591
+ const ctx = {
1592
+ get id() {
1593
+ return session.id;
1594
+ },
1595
+ get workingDirectory() {
1596
+ return session.workingDirectory;
1597
+ }
1598
+ };
1599
+ let outgoing;
1600
+ switch (event.type) {
1601
+ case "text":
1602
+ case "thought":
1603
+ case "tool_call":
1604
+ case "tool_update":
1605
+ case "plan":
1606
+ case "usage":
1607
+ outgoing = this.deps.messageTransformer.transform(event, ctx);
1608
+ this.sendMessage(this.session.id, outgoing);
1609
+ break;
1610
+ case "session_end":
1611
+ this.session.finish(event.reason);
1612
+ this.adapter.cleanupSkillCommands?.(this.session.id);
1613
+ outgoing = this.deps.messageTransformer.transform(event);
1614
+ this.sendMessage(this.session.id, outgoing);
1615
+ this.deps.notificationManager.notify(this.session.channelId, {
1616
+ sessionId: this.session.id,
1617
+ sessionName: this.session.name,
1618
+ type: "completed",
1619
+ summary: `Session "${this.session.name || this.session.id}" completed
1620
+ \u23F1 ${Math.round((Date.now() - this.session.createdAt.getTime()) / 6e4)} min \xB7 \u{1F4AC} ${this.session.promptCount} prompts`
1621
+ });
1622
+ break;
1623
+ case "error":
1624
+ this.session.fail(event.message);
1625
+ this.adapter.cleanupSkillCommands?.(this.session.id);
1626
+ outgoing = this.deps.messageTransformer.transform(event);
1627
+ this.sendMessage(this.session.id, outgoing);
1628
+ this.deps.notificationManager.notify(this.session.channelId, {
1629
+ sessionId: this.session.id,
1630
+ sessionName: this.session.name,
1631
+ type: "error",
1632
+ summary: event.message
1633
+ });
1634
+ break;
1635
+ case "image_content": {
1636
+ if (this.deps.fileService) {
1637
+ const fs5 = this.deps.fileService;
1638
+ const sid = this.session.id;
1639
+ const { data, mimeType } = event;
1640
+ const buffer = Buffer.from(data, "base64");
1641
+ const ext = fs5.extensionFromMime(mimeType);
1642
+ fs5.saveFile(sid, `agent-image${ext}`, buffer, mimeType).then((att) => {
1643
+ this.sendMessage(sid, {
1644
+ type: "attachment",
1645
+ text: "",
1646
+ attachment: att
1647
+ });
1648
+ }).catch((err) => log2.error({ err }, "Failed to save agent image"));
1649
+ }
1650
+ break;
1651
+ }
1652
+ case "audio_content": {
1653
+ if (this.deps.fileService) {
1654
+ const fs5 = this.deps.fileService;
1655
+ const sid = this.session.id;
1656
+ const { data, mimeType } = event;
1657
+ const buffer = Buffer.from(data, "base64");
1658
+ const ext = fs5.extensionFromMime(mimeType);
1659
+ fs5.saveFile(sid, `agent-audio${ext}`, buffer, mimeType).then((att) => {
1660
+ this.sendMessage(sid, {
1661
+ type: "attachment",
1662
+ text: "",
1663
+ attachment: att
1664
+ });
1665
+ }).catch((err) => log2.error({ err }, "Failed to save agent audio"));
1666
+ }
1667
+ break;
1668
+ }
1669
+ case "commands_update":
1670
+ log2.debug({ commands: event.commands }, "Commands available");
1671
+ this.adapter.sendSkillCommands?.(this.session.id, event.commands);
1672
+ break;
1673
+ case "system_message":
1674
+ outgoing = this.deps.messageTransformer.transform(event);
1675
+ this.sendMessage(this.session.id, outgoing);
1676
+ break;
1677
+ case "session_info_update":
1678
+ if (event.title) {
1679
+ this.session.setName(event.title);
1680
+ }
1681
+ outgoing = this.deps.messageTransformer.transform(event);
1682
+ this.sendMessage(this.session.id, outgoing);
1683
+ break;
1684
+ case "current_mode_update":
1685
+ this.session.updateMode(event.modeId);
1686
+ outgoing = this.deps.messageTransformer.transform(event);
1687
+ this.sendMessage(this.session.id, outgoing);
1688
+ break;
1689
+ case "config_option_update":
1690
+ this.session.updateConfigOptions(event.options);
1691
+ outgoing = this.deps.messageTransformer.transform(event);
1692
+ this.sendMessage(this.session.id, outgoing);
1693
+ break;
1694
+ case "model_update":
1695
+ this.session.updateModel(event.modelId);
1696
+ outgoing = this.deps.messageTransformer.transform(event);
1697
+ this.sendMessage(this.session.id, outgoing);
1698
+ break;
1699
+ case "user_message_chunk":
1700
+ outgoing = this.deps.messageTransformer.transform(event);
1701
+ this.sendMessage(this.session.id, outgoing);
1702
+ break;
1703
+ case "resource_content":
1704
+ case "resource_link":
1705
+ outgoing = this.deps.messageTransformer.transform(event);
1706
+ this.sendMessage(this.session.id, outgoing);
1707
+ break;
1708
+ }
1709
+ this.deps.eventBus?.emit("agent:event", {
1710
+ sessionId: this.session.id,
1711
+ event
1712
+ });
1713
+ return outgoing;
1714
+ }
1715
+ wirePermissions() {
1716
+ const mw = this.deps.middlewareChain;
1717
+ this.session.agentInstance.onPermissionRequest = async (request) => {
1718
+ const startTime = Date.now();
1719
+ let permReq = request;
1720
+ if (mw) {
1721
+ const payload = { sessionId: this.session.id, request, autoResolve: void 0 };
1722
+ const result = await mw.execute("permission:beforeRequest", payload, async (r) => r);
1723
+ if (!result) return "";
1724
+ permReq = result.request;
1725
+ if (result.autoResolve) {
1726
+ if (mw) {
1727
+ mw.execute("permission:afterResolve", {
1728
+ sessionId: this.session.id,
1729
+ requestId: permReq.id,
1730
+ decision: result.autoResolve,
1731
+ userId: "middleware",
1732
+ durationMs: Date.now() - startTime
1733
+ }, async (p) => p).catch(() => {
1734
+ });
1735
+ }
1736
+ return result.autoResolve;
1737
+ }
1738
+ }
1739
+ this.session.emit("permission_request", permReq);
1740
+ this.deps.eventBus?.emit("permission:request", {
1741
+ sessionId: this.session.id,
1742
+ permission: permReq
1743
+ });
1744
+ if (permReq.description.toLowerCase().includes("openacp")) {
1745
+ const allowOption = permReq.options.find((o) => o.isAllow);
1746
+ if (allowOption) {
1747
+ log2.info(
1748
+ { sessionId: this.session.id, requestId: permReq.id },
1749
+ "Auto-approving openacp command"
1750
+ );
1751
+ if (mw) {
1752
+ mw.execute("permission:afterResolve", {
1753
+ sessionId: this.session.id,
1754
+ requestId: permReq.id,
1755
+ decision: allowOption.id,
1756
+ userId: "system",
1757
+ durationMs: Date.now() - startTime
1758
+ }, async (p) => p).catch(() => {
1759
+ });
1760
+ }
1761
+ return allowOption.id;
1762
+ }
1763
+ }
1764
+ if (this.session.dangerousMode) {
1765
+ const allowOption = permReq.options.find((o) => o.isAllow);
1766
+ if (allowOption) {
1767
+ log2.info(
1768
+ { sessionId: this.session.id, requestId: permReq.id, optionId: allowOption.id },
1769
+ "Dangerous mode: auto-approving permission"
1770
+ );
1771
+ if (mw) {
1772
+ mw.execute("permission:afterResolve", {
1773
+ sessionId: this.session.id,
1774
+ requestId: permReq.id,
1775
+ decision: allowOption.id,
1776
+ userId: "system",
1777
+ durationMs: Date.now() - startTime
1778
+ }, async (p) => p).catch(() => {
1779
+ });
1780
+ }
1781
+ return allowOption.id;
1782
+ }
1783
+ }
1784
+ const promise = this.session.permissionGate.setPending(permReq);
1785
+ await this.adapter.sendPermissionRequest(this.session.id, permReq);
1786
+ const optionId = await promise;
1787
+ if (mw) {
1788
+ mw.execute("permission:afterResolve", {
1789
+ sessionId: this.session.id,
1790
+ requestId: permReq.id,
1791
+ decision: optionId,
1792
+ userId: "user",
1793
+ durationMs: Date.now() - startTime
1794
+ }, async (p) => p).catch(() => {
1795
+ });
1796
+ }
1797
+ return optionId;
1798
+ };
1799
+ }
1800
+ wireLifecycle() {
1801
+ this.statusChangeHandler = (from, to) => {
1802
+ this.deps.sessionManager.patchRecord(this.session.id, {
1803
+ status: to,
1804
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1805
+ });
1806
+ this.deps.eventBus?.emit("session:updated", {
1807
+ sessionId: this.session.id,
1808
+ status: to
1809
+ });
1810
+ if (to === "finished" || to === "cancelled") {
1811
+ queueMicrotask(() => this.disconnect());
1812
+ }
1813
+ };
1814
+ this.session.on("status_change", this.statusChangeHandler);
1815
+ this.namedHandler = (name) => {
1816
+ this.deps.sessionManager.patchRecord(this.session.id, { name });
1817
+ this.deps.eventBus?.emit("session:updated", {
1818
+ sessionId: this.session.id,
1819
+ name
1820
+ });
1821
+ this.adapter.renameSessionThread(this.session.id, name);
1822
+ };
1823
+ this.session.on("named", this.namedHandler);
1824
+ }
1825
+ };
1826
+
1827
+ // src/core/utils/extract-file-info.ts
1828
+ function extractFileInfo(name, kind, content, rawInput, meta) {
1829
+ if (kind && !["read", "edit", "write"].includes(kind)) return null;
1830
+ let info = null;
1831
+ if (meta) {
1832
+ const m = meta;
1833
+ const claudeCode = m?.claudeCode;
1834
+ const tr = claudeCode?.toolResponse;
1835
+ const file = tr?.file;
1836
+ if (typeof file?.filePath === "string" && typeof file?.content === "string") {
1837
+ info = { filePath: file.filePath, content: file.content };
1838
+ }
1839
+ if (!info && typeof tr?.filePath === "string" && typeof tr?.content === "string") {
1840
+ info = { filePath: tr.filePath, content: tr.content };
1841
+ }
1842
+ }
1843
+ if (!info && rawInput && typeof rawInput === "object") {
1844
+ const ri = rawInput;
1845
+ const filePath = ri?.file_path || ri?.filePath || ri?.path;
1846
+ if (typeof filePath === "string") {
1847
+ const parsed = content ? parseContent(content) : null;
1848
+ const riContent = typeof ri?.content === "string" ? ri.content : void 0;
1849
+ info = { filePath, content: parsed?.content || riContent, oldContent: parsed?.oldContent };
1850
+ }
1851
+ }
1852
+ if (!info && content) {
1853
+ info = parseContent(content);
1854
+ }
1855
+ if (!info) return null;
1856
+ if (!info.filePath) {
1857
+ const pathMatch = name.match(/(?:Read|Edit|Write|View)\s+(.+)/i);
1858
+ if (pathMatch) info.filePath = pathMatch[1].trim();
1859
+ }
1860
+ if (!info.filePath || !info.content) return null;
1861
+ return info;
1862
+ }
1863
+ function parseContent(content) {
1864
+ if (typeof content === "string") {
1865
+ return { content };
1866
+ }
1867
+ if (Array.isArray(content)) {
1868
+ for (const block of content) {
1869
+ const result = parseContent(block);
1870
+ if (result?.content || result?.filePath) return result;
1871
+ }
1872
+ return null;
1873
+ }
1874
+ if (typeof content === "object" && content !== null) {
1875
+ const c = content;
1876
+ if (c.type === "diff" && typeof c.path === "string") {
1877
+ const newText = c.newText;
1878
+ const oldText = c.oldText;
1879
+ if (newText) {
1880
+ return {
1881
+ filePath: c.path,
1882
+ content: newText,
1883
+ oldContent: oldText ?? void 0
1884
+ };
1885
+ }
1886
+ }
1887
+ if (c.type === "content" && c.content) {
1888
+ return parseContent(c.content);
1889
+ }
1890
+ if (c.type === "text" && typeof c.text === "string") {
1891
+ return { content: c.text, filePath: c.filePath };
1892
+ }
1893
+ if (typeof c.text === "string") {
1894
+ return { content: c.text, filePath: c.filePath };
1895
+ }
1896
+ if (typeof c.file_path === "string" || typeof c.filePath === "string" || typeof c.path === "string") {
1897
+ const filePath = c.file_path || c.filePath || c.path;
1898
+ const fileContent = c.content || c.text || c.output || c.newText;
1899
+ if (typeof fileContent === "string") {
1900
+ return {
1901
+ filePath,
1902
+ content: fileContent,
1903
+ oldContent: c.old_content || c.oldText
1904
+ };
1905
+ }
1906
+ }
1907
+ if (c.input) {
1908
+ const result = parseContent(c.input);
1909
+ if (result) return result;
1910
+ }
1911
+ if (c.output) {
1912
+ const result = parseContent(c.output);
1913
+ if (result) return result;
1914
+ }
1915
+ }
1916
+ return null;
1917
+ }
1918
+
1919
+ // src/core/message-transformer.ts
1920
+ var log3 = createChildLogger({ module: "message-transformer" });
1921
+ var MessageTransformer = class {
1922
+ constructor(tunnelService) {
1923
+ this.tunnelService = tunnelService;
1924
+ }
1925
+ transform(event, sessionContext) {
1926
+ switch (event.type) {
1927
+ case "text":
1928
+ return { type: "text", text: event.content };
1929
+ case "thought":
1930
+ return { type: "thought", text: event.content };
1931
+ case "tool_call": {
1932
+ const meta = event.meta;
1933
+ const metadata = {
1934
+ id: event.id,
1935
+ name: event.name,
1936
+ kind: event.kind,
1937
+ status: event.status,
1938
+ content: event.content,
1939
+ locations: event.locations,
1940
+ rawInput: event.rawInput,
1941
+ displaySummary: meta?.displaySummary,
1942
+ displayTitle: meta?.displayTitle,
1943
+ displayKind: meta?.displayKind
1944
+ };
1945
+ this.enrichWithViewerLinks(event, metadata, sessionContext);
1946
+ return { type: "tool_call", text: event.name, metadata };
1947
+ }
1948
+ case "tool_update": {
1949
+ const meta = event.meta;
1950
+ const metadata = {
1951
+ id: event.id,
1952
+ name: event.name,
1953
+ kind: event.kind,
1954
+ status: event.status,
1955
+ content: event.content,
1956
+ rawInput: event.rawInput,
1957
+ displaySummary: meta?.displaySummary,
1958
+ displayTitle: meta?.displayTitle,
1959
+ displayKind: meta?.displayKind
1960
+ };
1961
+ this.enrichWithViewerLinks(event, metadata, sessionContext);
1962
+ return { type: "tool_update", text: "", metadata };
1963
+ }
1964
+ case "plan":
1965
+ return {
1966
+ type: "plan",
1967
+ text: "",
1968
+ metadata: { entries: event.entries }
1969
+ };
1970
+ case "usage":
1971
+ return {
1972
+ type: "usage",
1973
+ text: "",
1974
+ metadata: {
1975
+ tokensUsed: event.tokensUsed,
1976
+ contextSize: event.contextSize,
1977
+ cost: event.cost
1978
+ }
1979
+ };
1980
+ case "session_end":
1981
+ return { type: "session_end", text: `Done (${event.reason})` };
1982
+ case "error":
1983
+ return { type: "error", text: event.message };
1984
+ case "system_message":
1985
+ return { type: "system_message", text: event.message };
1986
+ case "session_info_update":
1987
+ return {
1988
+ type: "system_message",
1989
+ text: `Session updated: ${event.title ?? ""}`.trim(),
1990
+ metadata: { title: event.title, updatedAt: event.updatedAt }
1991
+ };
1992
+ case "current_mode_update":
1993
+ return {
1994
+ type: "mode_change",
1995
+ text: `Mode: ${event.modeId}`,
1996
+ metadata: { modeId: event.modeId }
1997
+ };
1998
+ case "config_option_update":
1999
+ return {
2000
+ type: "config_update",
2001
+ text: "Config updated",
2002
+ metadata: { options: event.options }
2003
+ };
2004
+ case "model_update":
2005
+ return {
2006
+ type: "model_update",
2007
+ text: `Model: ${event.modelId}`,
2008
+ metadata: { modelId: event.modelId }
2009
+ };
2010
+ case "user_message_chunk":
2011
+ return {
2012
+ type: "user_replay",
2013
+ text: event.content
2014
+ };
2015
+ case "resource_content":
2016
+ return {
2017
+ type: "resource",
2018
+ text: event.name,
2019
+ metadata: { uri: event.uri, text: event.text, blob: event.blob, mimeType: event.mimeType }
2020
+ };
2021
+ case "resource_link":
2022
+ return {
2023
+ type: "resource_link",
2024
+ text: event.name,
2025
+ metadata: { uri: event.uri, mimeType: event.mimeType, title: event.title, description: event.description, size: event.size }
2026
+ };
2027
+ default:
2028
+ return { type: "text", text: "" };
2029
+ }
2030
+ }
2031
+ enrichWithViewerLinks(event, metadata, sessionContext) {
2032
+ if (!this.tunnelService || !sessionContext) return;
2033
+ const name = "name" in event ? event.name || "" : "";
2034
+ const kind = "kind" in event ? event.kind : void 0;
2035
+ log3.debug(
2036
+ { name, kind, status: event.status, hasContent: !!event.content },
2037
+ "enrichWithViewerLinks: inspecting event"
2038
+ );
2039
+ const fileInfo = extractFileInfo(
2040
+ name,
2041
+ kind,
2042
+ event.content,
2043
+ event.rawInput,
2044
+ event.meta
2045
+ );
2046
+ if (!fileInfo) return;
2047
+ log3.info(
2048
+ {
2049
+ name,
2050
+ kind,
2051
+ filePath: fileInfo.filePath,
2052
+ hasOldContent: !!fileInfo.oldContent
2053
+ },
2054
+ "enrichWithViewerLinks: extracted file info"
2055
+ );
2056
+ const store = this.tunnelService.getStore();
2057
+ const viewerLinks = {};
2058
+ if (fileInfo.oldContent) {
2059
+ const id2 = store.storeDiff(
2060
+ sessionContext.id,
2061
+ fileInfo.filePath,
2062
+ fileInfo.oldContent,
2063
+ fileInfo.content,
2064
+ sessionContext.workingDirectory
2065
+ );
2066
+ if (id2) viewerLinks.diff = this.tunnelService.diffUrl(id2);
2067
+ }
2068
+ const id = store.storeFile(
2069
+ sessionContext.id,
2070
+ fileInfo.filePath,
2071
+ fileInfo.content,
2072
+ sessionContext.workingDirectory
2073
+ );
2074
+ if (id) viewerLinks.file = this.tunnelService.fileUrl(id);
2075
+ if (Object.keys(viewerLinks).length > 0) {
2076
+ metadata.viewerLinks = viewerLinks;
2077
+ metadata.viewerFilePath = fileInfo.filePath;
2078
+ }
2079
+ }
2080
+ };
2081
+
2082
+ // src/core/sessions/session-factory.ts
2083
+ import { nanoid as nanoid2 } from "nanoid";
2084
+ var log4 = createChildLogger({ module: "session-factory" });
2085
+ var SessionFactory = class {
2086
+ constructor(agentManager, sessionManager, speechServiceAccessor, eventBus) {
2087
+ this.agentManager = agentManager;
2088
+ this.sessionManager = sessionManager;
2089
+ this.speechServiceAccessor = speechServiceAccessor;
2090
+ this.eventBus = eventBus;
2091
+ }
2092
+ middlewareChain;
2093
+ get speechService() {
2094
+ return typeof this.speechServiceAccessor === "function" ? this.speechServiceAccessor() : this.speechServiceAccessor;
2095
+ }
2096
+ async create(params) {
2097
+ let createParams = params;
2098
+ if (this.middlewareChain) {
2099
+ const payload = {
2100
+ agentName: params.agentName,
2101
+ workingDir: params.workingDirectory,
2102
+ userId: "",
2103
+ // userId is not part of SessionCreateParams — resolved upstream
2104
+ channelId: params.channelId,
2105
+ threadId: ""
2106
+ // threadId is assigned after session creation
2107
+ };
2108
+ const result = await this.middlewareChain.execute("session:beforeCreate", payload, async (p) => p);
2109
+ if (!result) throw new Error("Session creation blocked by middleware");
2110
+ createParams = {
2111
+ ...params,
2112
+ agentName: result.agentName,
2113
+ workingDirectory: result.workingDir,
2114
+ channelId: result.channelId
2115
+ };
2116
+ }
2117
+ const agentInstance = createParams.resumeAgentSessionId ? await this.agentManager.resume(
2118
+ createParams.agentName,
2119
+ createParams.workingDirectory,
2120
+ createParams.resumeAgentSessionId
2121
+ ) : await this.agentManager.spawn(
2122
+ createParams.agentName,
2123
+ createParams.workingDirectory
2124
+ );
2125
+ agentInstance.middlewareChain = this.middlewareChain;
2126
+ const session = new Session({
2127
+ id: createParams.existingSessionId,
2128
+ channelId: createParams.channelId,
2129
+ agentName: createParams.agentName,
2130
+ workingDirectory: createParams.workingDirectory,
2131
+ agentInstance,
2132
+ speechService: this.speechService
2133
+ });
2134
+ session.agentSessionId = agentInstance.sessionId;
2135
+ session.middlewareChain = this.middlewareChain;
2136
+ if (createParams.initialName) {
2137
+ session.name = createParams.initialName;
2138
+ }
2139
+ this.sessionManager.registerSession(session);
2140
+ this.eventBus.emit("session:created", {
2141
+ sessionId: session.id,
2142
+ agent: session.agentName,
2143
+ status: session.status
2144
+ });
2145
+ return session;
2146
+ }
2147
+ wireSideEffects(session, deps) {
2148
+ if (deps.usageStore) {
2149
+ const usageStore = deps.usageStore;
2150
+ const usageBudget = deps.usageBudget;
2151
+ const notificationManager = deps.notificationManager;
2152
+ session.on("agent_event", (event) => {
2153
+ if (event.type !== "usage") return;
2154
+ const record = {
2155
+ id: nanoid2(),
2156
+ sessionId: session.id,
2157
+ agentName: session.agentName,
2158
+ tokensUsed: event.tokensUsed ?? 0,
2159
+ contextSize: event.contextSize ?? 0,
2160
+ cost: event.cost,
2161
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2162
+ };
2163
+ usageStore.append(record);
2164
+ if (usageBudget) {
2165
+ const result = usageBudget.check();
2166
+ if (result.message) {
2167
+ notificationManager.notifyAll({
2168
+ sessionId: session.id,
2169
+ sessionName: session.name,
2170
+ type: "budget_warning",
2171
+ summary: result.message
2172
+ });
2173
+ }
2174
+ }
2175
+ });
2176
+ }
2177
+ session.on("status_change", (_from, to) => {
2178
+ if ((to === "finished" || to === "cancelled") && deps.tunnelService) {
2179
+ deps.tunnelService.stopBySession(session.id).then((stopped) => {
2180
+ for (const entry of stopped) {
2181
+ deps.notificationManager.notifyAll({
2182
+ sessionId: session.id,
2183
+ sessionName: session.name,
2184
+ type: "completed",
2185
+ summary: `Tunnel stopped: port ${entry.port}${entry.label ? ` (${entry.label})` : ""} \u2014 session ended`
2186
+ }).catch(() => {
2187
+ });
2188
+ }
2189
+ }).catch(() => {
2190
+ });
2191
+ }
2192
+ });
2193
+ }
2194
+ };
2195
+
2196
+ // src/core/event-bus.ts
2197
+ var EventBus = class extends TypedEmitter {
2198
+ };
2199
+
2200
+ // src/core/core.ts
2201
+ import path4 from "path";
2202
+ import os from "os";
2203
+
2204
+ // src/core/sessions/session-store.ts
2205
+ import fs3 from "fs";
2206
+ import path2 from "path";
2207
+ var log5 = createChildLogger({ module: "session-store" });
2208
+ var DEBOUNCE_MS = 2e3;
2209
+ var JsonFileSessionStore = class {
2210
+ records = /* @__PURE__ */ new Map();
2211
+ filePath;
2212
+ ttlDays;
2213
+ debounceTimer = null;
2214
+ cleanupInterval = null;
2215
+ flushHandler = null;
2216
+ constructor(filePath, ttlDays) {
2217
+ this.filePath = filePath;
2218
+ this.ttlDays = ttlDays;
2219
+ this.load();
2220
+ this.cleanup();
2221
+ this.cleanupInterval = setInterval(
2222
+ () => this.cleanup(),
2223
+ 24 * 60 * 60 * 1e3
2224
+ );
2225
+ this.flushHandler = () => this.flushSync();
2226
+ process.on("SIGTERM", this.flushHandler);
2227
+ process.on("SIGINT", this.flushHandler);
2228
+ process.on("exit", this.flushHandler);
2229
+ }
2230
+ async save(record) {
2231
+ this.records.set(record.sessionId, { ...record });
2232
+ this.scheduleDiskWrite();
2233
+ }
2234
+ get(sessionId) {
2235
+ return this.records.get(sessionId);
2236
+ }
2237
+ findByPlatform(channelId, predicate) {
2238
+ for (const record of this.records.values()) {
2239
+ if (record.channelId === channelId && predicate(record.platform)) {
2240
+ return record;
2241
+ }
2242
+ }
2243
+ return void 0;
2244
+ }
2245
+ findByAgentSessionId(agentSessionId) {
2246
+ return [...this.records.values()].find(
2247
+ (r) => r.agentSessionId === agentSessionId || r.originalAgentSessionId === agentSessionId
2248
+ );
2249
+ }
2250
+ list(channelId) {
2251
+ const all = [...this.records.values()];
2252
+ if (channelId) return all.filter((r) => r.channelId === channelId);
2253
+ return all;
2254
+ }
2255
+ async remove(sessionId) {
2256
+ this.records.delete(sessionId);
2257
+ this.scheduleDiskWrite();
2258
+ }
2259
+ flushSync() {
2260
+ if (this.debounceTimer) {
2261
+ clearTimeout(this.debounceTimer);
2262
+ this.debounceTimer = null;
2263
+ }
2264
+ const data = {
2265
+ version: 1,
2266
+ sessions: Object.fromEntries(this.records)
2267
+ };
2268
+ const dir = path2.dirname(this.filePath);
2269
+ if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
2270
+ fs3.writeFileSync(this.filePath, JSON.stringify(data, null, 2));
2271
+ }
2272
+ destroy() {
2273
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
2274
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
2275
+ if (this.flushHandler) {
2276
+ process.removeListener("SIGTERM", this.flushHandler);
2277
+ process.removeListener("SIGINT", this.flushHandler);
2278
+ process.removeListener("exit", this.flushHandler);
2279
+ this.flushHandler = null;
2280
+ }
2281
+ }
2282
+ load() {
2283
+ if (!fs3.existsSync(this.filePath)) return;
2284
+ try {
2285
+ const raw = JSON.parse(
2286
+ fs3.readFileSync(this.filePath, "utf-8")
2287
+ );
2288
+ if (raw.version !== 1) {
2289
+ log5.warn(
2290
+ { version: raw.version },
2291
+ "Unknown session store version, skipping load"
2292
+ );
2293
+ return;
2294
+ }
2295
+ for (const [id, record] of Object.entries(raw.sessions)) {
2296
+ this.records.set(id, record);
2297
+ }
2298
+ log5.debug({ count: this.records.size }, "Loaded session records");
2299
+ } catch (err) {
2300
+ log5.error({ err }, "Failed to load session store");
2301
+ }
2302
+ }
2303
+ cleanup() {
2304
+ const cutoff = Date.now() - this.ttlDays * 24 * 60 * 60 * 1e3;
2305
+ let removed = 0;
2306
+ for (const [id, record] of this.records) {
2307
+ if (record.status === "active" || record.status === "initializing")
2308
+ continue;
2309
+ const lastActive = new Date(record.lastActiveAt).getTime();
2310
+ if (lastActive < cutoff) {
2311
+ this.records.delete(id);
2312
+ removed++;
2313
+ }
2314
+ }
2315
+ if (removed > 0) {
2316
+ log5.info({ removed }, "Cleaned up expired session records");
2317
+ this.scheduleDiskWrite();
2318
+ }
2319
+ }
2320
+ scheduleDiskWrite() {
2321
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
2322
+ this.debounceTimer = setTimeout(() => {
2323
+ this.flushSync();
2324
+ }, DEBOUNCE_MS);
2325
+ }
2326
+ };
2327
+
2328
+ // src/core/plugin/plugin-loader.ts
2329
+ import { createHash } from "crypto";
2330
+ import { readFileSync } from "fs";
2331
+ function resolveLoadOrder(plugins) {
2332
+ const overrideTargets = /* @__PURE__ */ new Set();
2333
+ for (const p of plugins) {
2334
+ if (p.overrides) {
2335
+ overrideTargets.add(p.overrides);
2336
+ }
2337
+ }
2338
+ let remaining = plugins.filter((p) => !overrideTargets.has(p.name));
2339
+ const byName = /* @__PURE__ */ new Map();
2340
+ for (const p of remaining) {
2341
+ byName.set(p.name, p);
2342
+ }
2343
+ const skipped = /* @__PURE__ */ new Set();
2344
+ function cascadeSkip(name) {
2345
+ if (skipped.has(name)) return;
2346
+ skipped.add(name);
2347
+ for (const p of remaining) {
2348
+ if (p.pluginDependencies && name in p.pluginDependencies) {
2349
+ cascadeSkip(p.name);
2350
+ }
2351
+ }
2352
+ }
2353
+ for (const p of remaining) {
2354
+ if (p.pluginDependencies) {
2355
+ for (const dep of Object.keys(p.pluginDependencies)) {
2356
+ if (!byName.has(dep)) {
2357
+ cascadeSkip(p.name);
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ remaining = remaining.filter((p) => !skipped.has(p.name));
2363
+ byName.clear();
2364
+ for (const p of remaining) {
2365
+ byName.set(p.name, p);
2366
+ }
2367
+ const visited = /* @__PURE__ */ new Set();
2368
+ const inStack = /* @__PURE__ */ new Set();
2369
+ const order = [];
2370
+ function visit(name) {
2371
+ if (visited.has(name)) return;
2372
+ if (inStack.has(name)) {
2373
+ throw new Error(`Circular dependency detected: ${name}`);
2374
+ }
2375
+ inStack.add(name);
2376
+ const plugin = byName.get(name);
2377
+ if (plugin.pluginDependencies) {
2378
+ for (const dep of Object.keys(plugin.pluginDependencies)) {
2379
+ visit(dep);
2380
+ }
2381
+ }
2382
+ inStack.delete(name);
2383
+ visited.add(name);
2384
+ order.push(plugin);
2385
+ }
2386
+ for (const p of remaining) {
2387
+ visit(p.name);
2388
+ }
2389
+ return order;
2390
+ }
2391
+
2392
+ // src/core/plugin/service-registry.ts
2393
+ var ServiceRegistry = class {
2394
+ services = /* @__PURE__ */ new Map();
2395
+ register(name, implementation, pluginName) {
2396
+ if (this.services.has(name)) {
2397
+ const existing = this.services.get(name);
2398
+ throw new Error(`Service '${name}' already registered by ${existing.pluginName}. Plugin ${pluginName} cannot register it without override.`);
2399
+ }
2400
+ this.services.set(name, { implementation, pluginName });
2401
+ }
2402
+ registerOverride(name, implementation, pluginName) {
2403
+ this.services.set(name, { implementation, pluginName });
2404
+ }
2405
+ get(name) {
2406
+ return this.services.get(name)?.implementation;
2407
+ }
2408
+ has(name) {
2409
+ return this.services.has(name);
2410
+ }
2411
+ list() {
2412
+ return [...this.services.entries()].map(([name, { pluginName }]) => ({ name, pluginName }));
2413
+ }
2414
+ unregister(name) {
2415
+ this.services.delete(name);
2416
+ }
2417
+ unregisterByPlugin(pluginName) {
2418
+ for (const [name, entry] of this.services) {
2419
+ if (entry.pluginName === pluginName) {
2420
+ this.services.delete(name);
2421
+ }
2422
+ }
2423
+ }
2424
+ };
2425
+
2426
+ // src/core/plugin/middleware-chain.ts
2427
+ var MIDDLEWARE_TIMEOUT_MS = 5e3;
2428
+ var MiddlewareChain = class {
2429
+ chains = /* @__PURE__ */ new Map();
2430
+ errorHandler;
2431
+ errorTracker;
2432
+ add(hook, pluginName, opts) {
2433
+ const entry = {
2434
+ pluginName,
2435
+ priority: opts.priority ?? 100,
2436
+ handler: opts.handler
2437
+ };
2438
+ const existing = this.chains.get(hook);
2439
+ if (existing) {
2440
+ existing.push(entry);
2441
+ } else {
2442
+ this.chains.set(hook, [entry]);
2443
+ }
2444
+ }
2445
+ async execute(hook, payload, coreHandler) {
2446
+ const handlers = this.chains.get(hook);
2447
+ if (!handlers || handlers.length === 0) {
2448
+ return coreHandler(payload);
2449
+ }
2450
+ const sorted = [...handlers].sort((a, b) => a.priority - b.priority);
2451
+ let cachedResult = void 0;
2452
+ const buildNext = (index, currentPayload) => {
2453
+ return async () => {
2454
+ if (cachedResult !== void 0) {
2455
+ return cachedResult.value;
2456
+ }
2457
+ if (index >= sorted.length) {
2458
+ const result = await coreHandler(currentPayload);
2459
+ cachedResult = { value: result };
2460
+ return result;
2461
+ }
2462
+ const entry = sorted[index];
2463
+ if (this.errorTracker?.isDisabled(entry.pluginName)) {
2464
+ const skipFn = buildNext(index + 1, currentPayload);
2465
+ return skipFn();
2466
+ }
2467
+ const nextFn = buildNext(index + 1, currentPayload);
2468
+ let nextCalled = false;
2469
+ let nextResult = null;
2470
+ const wrappedNext = async (newPayload) => {
2471
+ if (!nextCalled) {
2472
+ nextCalled = true;
2473
+ const payloadForNext = newPayload !== void 0 ? newPayload : currentPayload;
2474
+ const newNextFn = buildNext(index + 1, payloadForNext);
2475
+ nextResult = await newNextFn();
2476
+ }
2477
+ return nextResult;
2478
+ };
2479
+ let handlerResult;
2480
+ try {
2481
+ const timeoutPromise = new Promise((_, reject) => {
2482
+ const timer = setTimeout(
2483
+ () => reject(new Error(`Middleware timeout: ${entry.pluginName} on hook ${hook}`)),
2484
+ MIDDLEWARE_TIMEOUT_MS
2485
+ );
2486
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
2487
+ ;
2488
+ timer.unref();
2489
+ }
2490
+ });
2491
+ handlerResult = await Promise.race([
2492
+ entry.handler(currentPayload, wrappedNext),
2493
+ timeoutPromise
2494
+ ]);
2495
+ } catch (err) {
2496
+ if (this.errorHandler) {
2497
+ this.errorHandler(entry.pluginName, err instanceof Error ? err : new Error(String(err)));
2498
+ }
2499
+ this.errorTracker?.increment(entry.pluginName);
2500
+ return nextFn();
2501
+ }
2502
+ if (handlerResult === null) {
2503
+ return null;
2504
+ }
2505
+ return handlerResult;
2506
+ };
2507
+ };
2508
+ const start = buildNext(0, payload);
2509
+ return start();
2510
+ }
2511
+ removeAll(pluginName) {
2512
+ for (const [hook, handlers] of this.chains.entries()) {
2513
+ const filtered = handlers.filter((h) => h.pluginName !== pluginName);
2514
+ if (filtered.length === 0) {
2515
+ this.chains.delete(hook);
2516
+ } else {
2517
+ this.chains.set(hook, filtered);
2518
+ }
2519
+ }
2520
+ }
2521
+ setErrorHandler(fn) {
2522
+ this.errorHandler = fn;
2523
+ }
2524
+ setErrorTracker(tracker) {
2525
+ this.errorTracker = tracker;
2526
+ }
2527
+ };
2528
+
2529
+ // src/core/plugin/error-tracker.ts
2530
+ var ErrorTracker = class {
2531
+ errors = /* @__PURE__ */ new Map();
2532
+ disabled = /* @__PURE__ */ new Set();
2533
+ exempt = /* @__PURE__ */ new Set();
2534
+ config;
2535
+ onDisabled;
2536
+ constructor(config) {
2537
+ this.config = { maxErrors: config?.maxErrors ?? 10, windowMs: config?.windowMs ?? 36e5 };
2538
+ }
2539
+ increment(pluginName) {
2540
+ if (this.exempt.has(pluginName)) return;
2541
+ const now = Date.now();
2542
+ const entry = this.errors.get(pluginName);
2543
+ if (!entry || now - entry.windowStart >= this.config.windowMs) {
2544
+ this.errors.set(pluginName, { count: 1, windowStart: now });
2545
+ } else {
2546
+ entry.count += 1;
2547
+ }
2548
+ const current = this.errors.get(pluginName);
2549
+ if (current.count >= this.config.maxErrors && !this.disabled.has(pluginName)) {
2550
+ this.disabled.add(pluginName);
2551
+ const reason = `Error budget exceeded: ${current.count} errors within ${this.config.windowMs}ms window`;
2552
+ this.onDisabled?.(pluginName, reason);
2553
+ }
2554
+ }
2555
+ isDisabled(pluginName) {
2556
+ return this.disabled.has(pluginName);
2557
+ }
2558
+ reset(pluginName) {
2559
+ this.disabled.delete(pluginName);
2560
+ this.errors.delete(pluginName);
2561
+ }
2562
+ setExempt(pluginName) {
2563
+ this.exempt.add(pluginName);
2564
+ }
2565
+ };
2566
+
2567
+ // src/core/plugin/plugin-storage.ts
2568
+ import fs4 from "fs";
2569
+ import path3 from "path";
2570
+ var PluginStorageImpl = class {
2571
+ kvPath;
2572
+ dataDir;
2573
+ writeChain = Promise.resolve();
2574
+ constructor(baseDir) {
2575
+ this.dataDir = path3.join(baseDir, "data");
2576
+ this.kvPath = path3.join(baseDir, "kv.json");
2577
+ }
2578
+ readKv() {
2579
+ try {
2580
+ const raw = fs4.readFileSync(this.kvPath, "utf-8");
2581
+ return JSON.parse(raw);
2582
+ } catch {
2583
+ return {};
2584
+ }
2585
+ }
2586
+ writeKv(data) {
2587
+ fs4.writeFileSync(this.kvPath, JSON.stringify(data), "utf-8");
2588
+ }
2589
+ async get(key) {
2590
+ const data = this.readKv();
2591
+ return key in data ? data[key] : void 0;
2592
+ }
2593
+ async set(key, value) {
2594
+ this.writeChain = this.writeChain.then(() => {
2595
+ const data = this.readKv();
2596
+ data[key] = value;
2597
+ this.writeKv(data);
2598
+ });
2599
+ return this.writeChain;
2600
+ }
2601
+ async delete(key) {
2602
+ this.writeChain = this.writeChain.then(() => {
2603
+ const data = this.readKv();
2604
+ delete data[key];
2605
+ this.writeKv(data);
2606
+ });
2607
+ return this.writeChain;
2608
+ }
2609
+ async list() {
2610
+ return Object.keys(this.readKv());
2611
+ }
2612
+ getDataDir() {
2613
+ fs4.mkdirSync(this.dataDir, { recursive: true });
2614
+ return this.dataDir;
2615
+ }
2616
+ };
2617
+
2618
+ // src/core/plugin/plugin-context.ts
2619
+ function requirePermission(permissions, required, action) {
2620
+ if (!permissions.includes(required)) {
2621
+ throw new Error(`Plugin does not have '${required}' permission required for ${action}`);
2622
+ }
2623
+ }
2624
+ function createPluginContext(opts) {
2625
+ const {
2626
+ pluginName,
2627
+ pluginConfig,
2628
+ permissions,
2629
+ serviceRegistry,
2630
+ middlewareChain,
2631
+ eventBus,
2632
+ storagePath,
2633
+ sessions,
2634
+ config,
2635
+ core
2636
+ } = opts;
2637
+ const registeredListeners = [];
2638
+ const registeredCommands = [];
2639
+ const log7 = opts.log ?? {
2640
+ trace() {
2641
+ },
2642
+ debug() {
2643
+ },
2644
+ info() {
2645
+ },
2646
+ warn() {
2647
+ },
2648
+ error() {
2649
+ },
2650
+ fatal() {
2651
+ },
2652
+ child() {
2653
+ return log7;
2654
+ }
2655
+ };
2656
+ const storageImpl = new PluginStorageImpl(storagePath);
2657
+ const storage = {
2658
+ async get(key) {
2659
+ requirePermission(permissions, "storage:read", "storage.get");
2660
+ return storageImpl.get(key);
2661
+ },
2662
+ async set(key, value) {
2663
+ requirePermission(permissions, "storage:write", "storage.set");
2664
+ return storageImpl.set(key, value);
2665
+ },
2666
+ async delete(key) {
2667
+ requirePermission(permissions, "storage:write", "storage.delete");
2668
+ return storageImpl.delete(key);
2669
+ },
2670
+ async list() {
2671
+ requirePermission(permissions, "storage:read", "storage.list");
2672
+ return storageImpl.list();
2673
+ },
2674
+ getDataDir() {
2675
+ requirePermission(permissions, "storage:read", "storage.getDataDir");
2676
+ return storageImpl.getDataDir();
2677
+ }
2678
+ };
2679
+ const ctx = {
2680
+ pluginName,
2681
+ pluginConfig,
2682
+ log: log7,
2683
+ storage,
2684
+ on(event, handler) {
2685
+ requirePermission(permissions, "events:read", "on()");
2686
+ eventBus.on(event, handler);
2687
+ registeredListeners.push({ event, handler });
2688
+ },
2689
+ off(event, handler) {
2690
+ requirePermission(permissions, "events:read", "off()");
2691
+ eventBus.off(event, handler);
2692
+ const idx = registeredListeners.findIndex((l) => l.event === event && l.handler === handler);
2693
+ if (idx >= 0) registeredListeners.splice(idx, 1);
2694
+ },
2695
+ emit(event, payload) {
2696
+ requirePermission(permissions, "events:emit", "emit()");
2697
+ eventBus.emit(event, payload);
2698
+ },
2699
+ registerMiddleware(hook, middlewareOpts) {
2700
+ requirePermission(permissions, "middleware:register", "registerMiddleware()");
2701
+ middlewareChain.add(hook, pluginName, middlewareOpts);
2702
+ },
2703
+ registerService(name, implementation) {
2704
+ requirePermission(permissions, "services:register", "registerService()");
2705
+ serviceRegistry.register(name, implementation, pluginName);
2706
+ },
2707
+ getService(name) {
2708
+ requirePermission(permissions, "services:use", "getService()");
2709
+ return serviceRegistry.get(name);
2710
+ },
2711
+ registerCommand(def) {
2712
+ requirePermission(permissions, "commands:register", "registerCommand()");
2713
+ registeredCommands.push(def);
2714
+ const registry = serviceRegistry.get("command-registry");
2715
+ if (registry && typeof registry.register === "function") {
2716
+ registry.register(def, pluginName);
2717
+ }
2718
+ },
2719
+ async sendMessage(_sessionId, _content) {
2720
+ requirePermission(permissions, "services:use", "sendMessage()");
2721
+ const router = serviceRegistry.get("message-router");
2722
+ if (router) {
2723
+ await router.send(_sessionId, _content);
2724
+ }
2725
+ },
2726
+ get sessions() {
2727
+ requirePermission(permissions, "kernel:access", "sessions");
2728
+ return sessions;
2729
+ },
2730
+ get config() {
2731
+ requirePermission(permissions, "kernel:access", "config");
2732
+ return config;
2733
+ },
2734
+ get eventBus() {
2735
+ requirePermission(permissions, "kernel:access", "eventBus");
2736
+ return eventBus;
2737
+ },
2738
+ get core() {
2739
+ requirePermission(permissions, "kernel:access", "core");
2740
+ return core;
2741
+ },
2742
+ cleanup() {
2743
+ for (const { event, handler } of registeredListeners) {
2744
+ eventBus.off(event, handler);
2745
+ }
2746
+ registeredListeners.length = 0;
2747
+ middlewareChain.removeAll(pluginName);
2748
+ serviceRegistry.unregisterByPlugin(pluginName);
2749
+ const cmdRegistry = serviceRegistry.get("command-registry");
2750
+ if (cmdRegistry && typeof cmdRegistry.unregisterByPlugin === "function") {
2751
+ cmdRegistry.unregisterByPlugin(pluginName);
2752
+ }
2753
+ registeredCommands.length = 0;
2754
+ }
2755
+ };
2756
+ return ctx;
2757
+ }
2758
+
2759
+ // src/core/plugin/lifecycle-manager.ts
2760
+ var SETUP_TIMEOUT_MS = 3e4;
2761
+ var TEARDOWN_TIMEOUT_MS = 1e4;
2762
+ function withTimeout(promise, ms, label) {
2763
+ return new Promise((resolve, reject) => {
2764
+ const timer = setTimeout(() => reject(new Error(`Timeout: ${label} exceeded ${ms}ms`)), ms);
2765
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
2766
+ ;
2767
+ timer.unref();
2768
+ }
2769
+ promise.then(resolve, reject).finally(() => clearTimeout(timer));
2770
+ });
2771
+ }
2772
+ function resolvePluginConfig(pluginName, configManager) {
2773
+ try {
2774
+ const allConfig = configManager?.get?.() ?? {};
2775
+ const pluginEntry = allConfig.plugins?.builtin?.[pluginName];
2776
+ if (pluginEntry?.config && Object.keys(pluginEntry.config).length > 0) {
2777
+ return pluginEntry.config;
2778
+ }
2779
+ const legacyMap = {
2780
+ "@openacp/security": "security",
2781
+ "@openacp/speech": "speech",
2782
+ "@openacp/tunnel": "tunnel",
2783
+ "@openacp/usage": "usage",
2784
+ "@openacp/file-service": "files",
2785
+ "@openacp/api-server": "api",
2786
+ "@openacp/telegram": "channels.telegram",
2787
+ "@openacp/discord": "channels.discord",
2788
+ "@openacp/slack": "channels.slack"
2789
+ };
2790
+ const legacyKey = legacyMap[pluginName];
2791
+ if (legacyKey) {
2792
+ const parts = legacyKey.split(".");
2793
+ let obj = allConfig;
2794
+ for (const p of parts) obj = obj?.[p];
2795
+ if (obj && typeof obj === "object") return { ...obj };
2796
+ }
2797
+ } catch {
2798
+ }
2799
+ return {};
2800
+ }
2801
+ var LifecycleManager = class {
2802
+ serviceRegistry;
2803
+ middlewareChain;
2804
+ errorTracker;
2805
+ eventBus;
2806
+ storagePath;
2807
+ sessions;
2808
+ config;
2809
+ core;
2810
+ log;
2811
+ settingsManager;
2812
+ pluginRegistry;
2813
+ contexts = /* @__PURE__ */ new Map();
2814
+ loadOrder = [];
2815
+ _loaded = /* @__PURE__ */ new Set();
2816
+ _failed = /* @__PURE__ */ new Set();
2817
+ get loadedPlugins() {
2818
+ return [...this._loaded];
2819
+ }
2820
+ get failedPlugins() {
2821
+ return [...this._failed];
2822
+ }
2823
+ constructor(opts) {
2824
+ this.serviceRegistry = opts?.serviceRegistry ?? new ServiceRegistry();
2825
+ this.middlewareChain = opts?.middlewareChain ?? new MiddlewareChain();
2826
+ this.errorTracker = opts?.errorTracker ?? new ErrorTracker();
2827
+ this.eventBus = opts?.eventBus ?? {
2828
+ on() {
2829
+ },
2830
+ off() {
2831
+ },
2832
+ emit() {
2833
+ }
2834
+ };
2835
+ this.storagePath = opts?.storagePath ?? "/tmp/openacp-plugins";
2836
+ this.sessions = opts?.sessions ?? {};
2837
+ this.config = opts?.config ?? {};
2838
+ this.core = opts?.core;
2839
+ this.log = opts?.log;
2840
+ this.settingsManager = opts?.settingsManager;
2841
+ this.pluginRegistry = opts?.pluginRegistry;
2842
+ }
2843
+ async boot(plugins) {
2844
+ let sorted;
2845
+ try {
2846
+ sorted = resolveLoadOrder(plugins);
2847
+ } catch (err) {
2848
+ for (const p of plugins) {
2849
+ this._failed.add(p.name);
2850
+ }
2851
+ return;
2852
+ }
2853
+ this.loadOrder = sorted;
2854
+ for (const plugin of sorted) {
2855
+ if (plugin.pluginDependencies) {
2856
+ const depFailed = Object.keys(plugin.pluginDependencies).some(
2857
+ (dep) => this._failed.has(dep)
2858
+ );
2859
+ if (depFailed) {
2860
+ this._failed.add(plugin.name);
2861
+ continue;
2862
+ }
2863
+ }
2864
+ const registryEntry = this.pluginRegistry?.get(plugin.name);
2865
+ if (registryEntry && registryEntry.enabled === false) {
2866
+ this.eventBus?.emit("plugin:disabled", { name: plugin.name });
2867
+ continue;
2868
+ }
2869
+ if (registryEntry && plugin.migrate && registryEntry.version !== plugin.version && this.settingsManager) {
2870
+ try {
2871
+ const oldSettings = await this.settingsManager.loadSettings(plugin.name);
2872
+ const migrateCtx = {
2873
+ pluginName: plugin.name,
2874
+ settings: this.settingsManager.createAPI(plugin.name),
2875
+ log: this.log?.child?.({ plugin: plugin.name }) ?? this.log ?? console
2876
+ };
2877
+ const newSettings = await plugin.migrate(migrateCtx, oldSettings, registryEntry.version);
2878
+ if (newSettings && typeof newSettings === "object") {
2879
+ await migrateCtx.settings.setAll(newSettings);
2880
+ }
2881
+ this.pluginRegistry.updateVersion(plugin.name, plugin.version);
2882
+ await this.pluginRegistry.save();
2883
+ } catch (err) {
2884
+ const childLog = this.log?.child?.({ plugin: plugin.name });
2885
+ (childLog ?? this.log ?? console).warn?.({ err }, "Migration failed, continuing with old settings");
2886
+ }
2887
+ }
2888
+ let pluginConfig;
2889
+ if (this.settingsManager) {
2890
+ pluginConfig = await this.settingsManager.loadSettings(plugin.name);
2891
+ if (Object.keys(pluginConfig).length === 0) {
2892
+ pluginConfig = resolvePluginConfig(plugin.name, this.config);
2893
+ }
2894
+ } else {
2895
+ pluginConfig = resolvePluginConfig(plugin.name, this.config);
2896
+ }
2897
+ const ctx = createPluginContext({
2898
+ pluginName: plugin.name,
2899
+ pluginConfig,
2900
+ permissions: plugin.permissions ?? [],
2901
+ serviceRegistry: this.serviceRegistry,
2902
+ middlewareChain: this.middlewareChain,
2903
+ errorTracker: this.errorTracker,
2904
+ eventBus: this.eventBus,
2905
+ storagePath: `${this.storagePath}/${plugin.name}`,
2906
+ sessions: this.sessions,
2907
+ config: this.config,
2908
+ core: this.core,
2909
+ log: this.log
2910
+ });
2911
+ try {
2912
+ await withTimeout(plugin.setup(ctx), SETUP_TIMEOUT_MS, `${plugin.name}.setup()`);
2913
+ this.contexts.set(plugin.name, ctx);
2914
+ this._loaded.add(plugin.name);
2915
+ this.eventBus?.emit("plugin:loaded", { name: plugin.name, version: plugin.version });
2916
+ } catch (err) {
2917
+ this._failed.add(plugin.name);
2918
+ ctx.cleanup();
2919
+ this.eventBus?.emit("plugin:failed", { name: plugin.name, error: String(err) });
2920
+ }
2921
+ }
2922
+ }
2923
+ async unloadPlugin(name) {
2924
+ if (!this._loaded.has(name)) return;
2925
+ const plugin = this.loadOrder.find((p) => p.name === name);
2926
+ if (plugin?.teardown) {
2927
+ try {
2928
+ await withTimeout(plugin.teardown(), TEARDOWN_TIMEOUT_MS, `${name}.teardown()`);
2929
+ } catch {
2930
+ }
2931
+ }
2932
+ const ctx = this.contexts.get(name);
2933
+ if (ctx) {
2934
+ ctx.cleanup();
2935
+ this.contexts.delete(name);
2936
+ }
2937
+ this._loaded.delete(name);
2938
+ this._failed.delete(name);
2939
+ this.loadOrder = this.loadOrder.filter((p) => p.name !== name);
2940
+ this.eventBus?.emit("plugin:unloaded", { name });
2941
+ }
2942
+ async shutdown() {
2943
+ const reversed = [...this.loadOrder].reverse();
2944
+ for (const plugin of reversed) {
2945
+ if (!this._loaded.has(plugin.name)) continue;
2946
+ if (plugin.teardown) {
2947
+ try {
2948
+ await withTimeout(plugin.teardown(), TEARDOWN_TIMEOUT_MS, `${plugin.name}.teardown()`);
2949
+ } catch {
2950
+ }
2951
+ }
2952
+ const ctx = this.contexts.get(plugin.name);
2953
+ if (ctx) {
2954
+ ctx.cleanup();
2955
+ this.contexts.delete(plugin.name);
2956
+ }
2957
+ this.eventBus?.emit("plugin:unloaded", { name: plugin.name });
2958
+ }
2959
+ this._loaded.clear();
2960
+ this.loadOrder = [];
2961
+ }
2962
+ };
2963
+
2964
+ // src/core/core.ts
2965
+ var log6 = createChildLogger({ module: "core" });
2966
+ var OpenACPCore = class {
2967
+ configManager;
2968
+ agentCatalog;
2969
+ agentManager;
2970
+ sessionManager;
2971
+ messageTransformer;
2972
+ adapters = /* @__PURE__ */ new Map();
2973
+ /** Set by main.ts — triggers graceful shutdown with restart exit code */
2974
+ requestRestart = null;
2975
+ _tunnelService;
2976
+ sessionStore = null;
2977
+ resumeLocks = /* @__PURE__ */ new Map();
2978
+ eventBus;
2979
+ sessionFactory;
2980
+ lifecycleManager;
2981
+ // --- Lazy getters: resolve from ServiceRegistry (populated by plugins during boot) ---
2982
+ get securityGuard() {
2983
+ return this.lifecycleManager.serviceRegistry.get("security");
2984
+ }
2985
+ get notificationManager() {
2986
+ return this.lifecycleManager.serviceRegistry.get("notifications");
2987
+ }
2988
+ get fileService() {
2989
+ return this.lifecycleManager.serviceRegistry.get("file-service");
2990
+ }
2991
+ get speechService() {
2992
+ return this.lifecycleManager.serviceRegistry.get("speech");
2993
+ }
2994
+ get contextManager() {
2995
+ return this.lifecycleManager.serviceRegistry.get("context");
2996
+ }
2997
+ get usageStore() {
2998
+ const usage = this.lifecycleManager.serviceRegistry.get("usage");
2999
+ return usage?.store ?? null;
3000
+ }
3001
+ get usageBudget() {
3002
+ const usage = this.lifecycleManager.serviceRegistry.get("usage");
3003
+ return usage?.budget ?? null;
3004
+ }
3005
+ constructor(configManager) {
3006
+ this.configManager = configManager;
3007
+ const config = configManager.get();
3008
+ this.agentCatalog = new AgentCatalog();
3009
+ this.agentCatalog.load();
3010
+ this.agentManager = new AgentManager(this.agentCatalog);
3011
+ const storePath = path4.join(os.homedir(), ".openacp", "sessions.json");
3012
+ this.sessionStore = new JsonFileSessionStore(
3013
+ storePath,
3014
+ config.sessionStore.ttlDays
3015
+ );
3016
+ this.sessionManager = new SessionManager(this.sessionStore);
3017
+ this.messageTransformer = new MessageTransformer();
3018
+ this.eventBus = new EventBus();
3019
+ this.sessionManager.setEventBus(this.eventBus);
3020
+ this.sessionFactory = new SessionFactory(
3021
+ this.agentManager,
3022
+ this.sessionManager,
3023
+ () => this.speechService,
3024
+ this.eventBus
3025
+ );
3026
+ this.lifecycleManager = new LifecycleManager({
3027
+ serviceRegistry: new ServiceRegistry(),
3028
+ middlewareChain: new MiddlewareChain(),
3029
+ errorTracker: new ErrorTracker(),
3030
+ eventBus: this.eventBus,
3031
+ sessions: this.sessionManager,
3032
+ config: this.configManager,
3033
+ core: this,
3034
+ storagePath: path4.join(os.homedir(), ".openacp", "plugins", "data")
3035
+ });
3036
+ this.sessionFactory.middlewareChain = this.lifecycleManager.middlewareChain;
3037
+ this.sessionManager.middlewareChain = this.lifecycleManager.middlewareChain;
3038
+ this.configManager.on(
3039
+ "config:changed",
3040
+ async ({ path: configPath, value }) => {
3041
+ if (configPath === "logging.level" && typeof value === "string") {
3042
+ const { setLogLevel } = await import("./log-LZ7FTRKG.js");
3043
+ setLogLevel(value);
3044
+ log6.info({ level: value }, "Log level changed at runtime");
3045
+ }
3046
+ if (configPath.startsWith("speech.")) {
3047
+ const speechSvc = this.speechService;
3048
+ if (speechSvc) {
3049
+ const newConfig = this.configManager.get();
3050
+ const newSpeechConfig = newConfig.speech ?? {
3051
+ stt: { provider: null, providers: {} },
3052
+ tts: { provider: null, providers: {} }
3053
+ };
3054
+ speechSvc.refreshProviders(newSpeechConfig);
3055
+ log6.info("Speech service config updated at runtime");
3056
+ }
3057
+ }
3058
+ }
3059
+ );
3060
+ }
3061
+ get tunnelService() {
3062
+ return this._tunnelService;
3063
+ }
3064
+ set tunnelService(service) {
3065
+ this._tunnelService = service;
3066
+ this.messageTransformer = new MessageTransformer(service);
3067
+ }
3068
+ registerAdapter(name, adapter) {
3069
+ this.adapters.set(name, adapter);
3070
+ }
3071
+ async start() {
3072
+ this.agentCatalog.refreshRegistryIfStale().catch((err) => {
3073
+ log6.warn({ err }, "Background registry refresh failed");
3074
+ });
3075
+ for (const adapter of this.adapters.values()) {
3076
+ await adapter.start();
3077
+ }
3078
+ }
3079
+ async stop() {
3080
+ try {
3081
+ await this.notificationManager.notifyAll({
3082
+ sessionId: "system",
3083
+ type: "error",
3084
+ summary: "OpenACP is shutting down"
3085
+ });
3086
+ } catch {
3087
+ }
3088
+ await this.sessionManager.destroyAll();
3089
+ for (const adapter of this.adapters.values()) {
3090
+ await adapter.stop();
3091
+ }
3092
+ if (this.usageStore) {
3093
+ this.usageStore.destroy();
3094
+ }
3095
+ }
3096
+ // --- Summary ---
3097
+ async summarizeSession(sessionId) {
3098
+ const session = this.sessionManager.getSession(sessionId);
3099
+ if (session && session.status === "active") {
3100
+ try {
3101
+ const summary = await session.generateSummary();
3102
+ if (!summary) return { ok: false, error: "Agent could not generate summary" };
3103
+ return { ok: true, summary };
3104
+ } catch (err) {
3105
+ return { ok: false, error: err.message };
3106
+ }
3107
+ }
3108
+ const record = this.sessionManager.getSessionRecord(sessionId);
3109
+ if (!record?.agentSessionId) {
3110
+ return { ok: false, error: "Session not found or has no agent history" };
3111
+ }
3112
+ const caps = getAgentCapabilities(record.agentName);
3113
+ if (!caps.supportsResume) {
3114
+ return { ok: false, error: `Agent "${record.agentName}" does not support resume \u2014 cannot summarize ended session` };
3115
+ }
3116
+ let tempSession;
3117
+ try {
3118
+ const agentInstance = await this.agentManager.resume(
3119
+ record.agentName,
3120
+ record.workingDir,
3121
+ record.agentSessionId
3122
+ );
3123
+ tempSession = new Session({
3124
+ id: `summary-${sessionId}`,
3125
+ channelId: record.channelId,
3126
+ agentName: record.agentName,
3127
+ workingDirectory: record.workingDir,
3128
+ agentInstance
3129
+ });
3130
+ tempSession.activate();
3131
+ const summary = await tempSession.generateSummary();
3132
+ if (!summary) return { ok: false, error: "Agent could not generate summary" };
3133
+ return { ok: true, summary };
3134
+ } catch (err) {
3135
+ return { ok: false, error: err.message };
3136
+ } finally {
3137
+ if (tempSession) {
3138
+ try {
3139
+ await tempSession.destroy();
3140
+ } catch {
3141
+ }
3142
+ }
3143
+ }
3144
+ }
3145
+ // --- Archive ---
3146
+ async archiveSession(sessionId) {
3147
+ const session = this.sessionManager.getSession(sessionId);
3148
+ const record = this.sessionManager.getSessionRecord(sessionId);
3149
+ if (!session && !record) return { ok: false, error: "Session not found" };
3150
+ const channelId = session?.channelId ?? record?.channelId;
3151
+ if (!channelId) return { ok: false, error: "No channel for session" };
3152
+ const adapter = this.adapters.get(channelId);
3153
+ if (!adapter) return { ok: false, error: "Adapter not found for session" };
3154
+ try {
3155
+ if (session) {
3156
+ await adapter.archiveSessionTopic?.(session.id);
3157
+ } else {
3158
+ await adapter.deleteSessionThread?.(sessionId);
3159
+ }
3160
+ if (session) {
3161
+ try {
3162
+ await this.sessionManager.cancelSession(sessionId);
3163
+ } catch {
3164
+ } finally {
3165
+ session.archiving = false;
3166
+ }
3167
+ }
3168
+ await this.sessionManager.removeRecord(sessionId);
3169
+ return { ok: true };
3170
+ } catch (err) {
3171
+ if (session) session.archiving = false;
3172
+ return { ok: false, error: err.message };
3173
+ }
3174
+ }
3175
+ // --- Message Routing ---
3176
+ async handleMessage(message) {
3177
+ log6.debug(
3178
+ {
3179
+ channelId: message.channelId,
3180
+ threadId: message.threadId,
3181
+ userId: message.userId
3182
+ },
3183
+ "Incoming message"
3184
+ );
3185
+ if (this.lifecycleManager?.middlewareChain) {
3186
+ const result = await this.lifecycleManager.middlewareChain.execute(
3187
+ "message:incoming",
3188
+ message,
3189
+ async (msg) => msg
3190
+ );
3191
+ if (!result) return;
3192
+ message = result;
3193
+ }
3194
+ const access = this.securityGuard.checkAccess(message);
3195
+ if (!access.allowed) {
3196
+ log6.warn({ userId: message.userId, reason: access.reason }, "Access denied");
3197
+ if (access.reason.includes("Session limit")) {
3198
+ const adapter = this.adapters.get(message.channelId);
3199
+ if (adapter) {
3200
+ await adapter.sendMessage(message.threadId, {
3201
+ type: "error",
3202
+ text: `\u26A0\uFE0F ${access.reason}. Please cancel existing sessions with /cancel before starting new ones.`
3203
+ });
3204
+ }
3205
+ }
3206
+ return;
3207
+ }
3208
+ let session = this.sessionManager.getSessionByThread(
3209
+ message.channelId,
3210
+ message.threadId
3211
+ );
3212
+ if (!session) {
3213
+ session = await this.lazyResume(message) ?? void 0;
3214
+ }
3215
+ if (!session) {
3216
+ log6.warn(
3217
+ { channelId: message.channelId, threadId: message.threadId },
3218
+ "No session found for thread (in-memory miss + lazy resume returned null)"
3219
+ );
3220
+ return;
3221
+ }
3222
+ this.sessionManager.patchRecord(session.id, {
3223
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
3224
+ });
3225
+ await session.enqueuePrompt(message.text, message.attachments);
3226
+ }
3227
+ // --- Unified Session Creation Pipeline ---
3228
+ async createSession(params) {
3229
+ const session = await this.sessionFactory.create(params);
3230
+ const adapter = this.adapters.get(params.channelId);
3231
+ if (params.createThread && adapter) {
3232
+ const threadId = await adapter.createSessionThread(
3233
+ session.id,
3234
+ params.initialName ?? `\u{1F504} ${params.agentName} \u2014 New Session`
3235
+ );
3236
+ session.threadId = threadId;
3237
+ }
3238
+ if (adapter) {
3239
+ const bridge = this.createBridge(session, adapter);
3240
+ bridge.connect();
3241
+ }
3242
+ this.sessionFactory.wireSideEffects(session, {
3243
+ usageStore: this.usageStore,
3244
+ usageBudget: this.usageBudget,
3245
+ notificationManager: this.notificationManager,
3246
+ tunnelService: this._tunnelService
3247
+ });
3248
+ const existingRecord = this.sessionStore?.get(session.id);
3249
+ const platform = {
3250
+ ...existingRecord?.platform ?? {}
3251
+ };
3252
+ if (session.threadId) {
3253
+ if (params.channelId === "telegram") {
3254
+ platform.topicId = Number(session.threadId);
3255
+ } else {
3256
+ platform.threadId = session.threadId;
3257
+ }
3258
+ }
3259
+ await this.sessionManager.patchRecord(session.id, {
3260
+ sessionId: session.id,
3261
+ agentSessionId: session.agentSessionId,
3262
+ agentName: params.agentName,
3263
+ workingDir: params.workingDirectory,
3264
+ channelId: params.channelId,
3265
+ status: session.status,
3266
+ createdAt: session.createdAt.toISOString(),
3267
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString(),
3268
+ name: session.name,
3269
+ platform
3270
+ });
3271
+ log6.info(
3272
+ { sessionId: session.id, agentName: params.agentName },
3273
+ "Session created via pipeline"
3274
+ );
3275
+ return session;
3276
+ }
3277
+ async handleNewSession(channelId, agentName, workspacePath, options) {
3278
+ const config = this.configManager.get();
3279
+ const resolvedAgent = agentName || config.defaultAgent;
3280
+ log6.info({ channelId, agentName: resolvedAgent }, "New session request");
3281
+ const agentDef = this.agentCatalog.resolve(resolvedAgent);
3282
+ const resolvedWorkspace = this.configManager.resolveWorkspace(
3283
+ workspacePath || agentDef?.workingDirectory
3284
+ );
3285
+ return this.createSession({
3286
+ channelId,
3287
+ agentName: resolvedAgent,
3288
+ workingDirectory: resolvedWorkspace,
3289
+ createThread: options?.createThread
3290
+ });
3291
+ }
3292
+ async adoptSession(agentName, agentSessionId, cwd, channelId) {
3293
+ const caps = getAgentCapabilities(agentName);
3294
+ if (!caps.supportsResume) {
3295
+ return {
3296
+ ok: false,
3297
+ error: "agent_not_supported",
3298
+ message: `Agent '${agentName}' does not support session resume`
3299
+ };
3300
+ }
3301
+ const agentDef = this.agentManager.getAgent(agentName);
3302
+ if (!agentDef) {
3303
+ return {
3304
+ ok: false,
3305
+ error: "agent_not_supported",
3306
+ message: `Agent '${agentName}' not found`
3307
+ };
3308
+ }
3309
+ const { existsSync } = await import("fs");
3310
+ if (!existsSync(cwd)) {
3311
+ return {
3312
+ ok: false,
3313
+ error: "invalid_cwd",
3314
+ message: `Directory does not exist: ${cwd}`
3315
+ };
3316
+ }
3317
+ const maxSessions = this.configManager.get().security.maxConcurrentSessions;
3318
+ if (this.sessionManager.listSessions().length >= maxSessions) {
3319
+ return {
3320
+ ok: false,
3321
+ error: "session_limit",
3322
+ message: "Maximum concurrent sessions reached"
3323
+ };
3324
+ }
3325
+ const existingRecord = this.sessionManager.getRecordByAgentSessionId(agentSessionId);
3326
+ if (existingRecord) {
3327
+ const sameChannel = !channelId || existingRecord.channelId === channelId;
3328
+ const platform = existingRecord.platform;
3329
+ const existingThreadId = platform?.topicId ? String(platform.topicId) : platform?.threadId;
3330
+ if (existingThreadId && sameChannel) {
3331
+ const adapter = this.adapters.get(existingRecord.channelId) ?? this.adapters.values().next().value;
3332
+ if (adapter) {
3333
+ try {
3334
+ await adapter.sendMessage(existingRecord.sessionId, {
3335
+ type: "text",
3336
+ text: "Session resumed from CLI."
3337
+ });
3338
+ } catch {
3339
+ }
3340
+ }
3341
+ return {
3342
+ ok: true,
3343
+ sessionId: existingRecord.sessionId,
3344
+ threadId: existingThreadId,
3345
+ status: "existing"
3346
+ };
3347
+ }
3348
+ }
3349
+ let adapterChannelId;
3350
+ if (channelId) {
3351
+ if (!this.adapters.has(channelId)) {
3352
+ const available = Array.from(this.adapters.keys()).join(", ") || "none";
3353
+ return { ok: false, error: "adapter_not_found", message: `Adapter '${channelId}' is not connected. Available: ${available}` };
3354
+ }
3355
+ adapterChannelId = channelId;
3356
+ } else {
3357
+ const firstEntry = this.adapters.entries().next().value;
3358
+ if (!firstEntry) {
3359
+ return { ok: false, error: "no_adapter", message: "No channel adapter registered" };
3360
+ }
3361
+ adapterChannelId = firstEntry[0];
3362
+ }
3363
+ let session;
3364
+ try {
3365
+ session = await this.createSession({
3366
+ channelId: adapterChannelId,
3367
+ agentName,
3368
+ workingDirectory: cwd,
3369
+ resumeAgentSessionId: agentSessionId,
3370
+ createThread: true,
3371
+ initialName: "Adopted session"
3372
+ });
3373
+ } catch (err) {
3374
+ return {
3375
+ ok: false,
3376
+ error: "resume_failed",
3377
+ message: `Failed to resume session: ${err instanceof Error ? err.message : String(err)}`
3378
+ };
3379
+ }
3380
+ const adoptPlatform = {};
3381
+ if (adapterChannelId === "telegram") {
3382
+ adoptPlatform.topicId = Number(session.threadId);
3383
+ } else {
3384
+ adoptPlatform.threadId = session.threadId;
3385
+ }
3386
+ await this.sessionManager.patchRecord(session.id, {
3387
+ originalAgentSessionId: agentSessionId,
3388
+ platform: adoptPlatform
3389
+ });
3390
+ return {
3391
+ ok: true,
3392
+ sessionId: session.id,
3393
+ threadId: session.threadId,
3394
+ status: "adopted"
3395
+ };
3396
+ }
3397
+ async handleNewChat(channelId, currentThreadId) {
3398
+ const currentSession = this.sessionManager.getSessionByThread(
3399
+ channelId,
3400
+ currentThreadId
3401
+ );
3402
+ if (currentSession) {
3403
+ return this.handleNewSession(
3404
+ channelId,
3405
+ currentSession.agentName,
3406
+ currentSession.workingDirectory
3407
+ );
3408
+ }
3409
+ const record = this.sessionManager.getRecordByThread(
3410
+ channelId,
3411
+ currentThreadId
3412
+ );
3413
+ if (!record || record.status === "cancelled" || record.status === "error")
3414
+ return null;
3415
+ return this.handleNewSession(
3416
+ channelId,
3417
+ record.agentName,
3418
+ record.workingDir
3419
+ );
3420
+ }
3421
+ async createSessionWithContext(params) {
3422
+ let contextResult = null;
3423
+ try {
3424
+ contextResult = await this.contextManager.buildContext(
3425
+ params.contextQuery,
3426
+ params.contextOptions
3427
+ );
3428
+ } catch (err) {
3429
+ log6.warn({ err }, "Context building failed, proceeding without context");
3430
+ }
3431
+ const session = await this.createSession({
3432
+ channelId: params.channelId,
3433
+ agentName: params.agentName,
3434
+ workingDirectory: params.workingDirectory,
3435
+ createThread: params.createThread
3436
+ });
3437
+ if (contextResult) {
3438
+ session.setContext(contextResult.markdown);
3439
+ }
3440
+ return { session, contextResult };
3441
+ }
3442
+ // --- Lazy Resume ---
3443
+ /**
3444
+ * Get active session by thread, or attempt lazy resume from store.
3445
+ * Used by adapter command handlers that need a session but don't go through handleMessage().
3446
+ */
3447
+ async getOrResumeSession(channelId, threadId) {
3448
+ const session = this.sessionManager.getSessionByThread(channelId, threadId);
3449
+ if (session) return session;
3450
+ return this.lazyResume({ channelId, threadId, userId: "", text: "" });
3451
+ }
3452
+ async lazyResume(message) {
3453
+ const store = this.sessionStore;
3454
+ if (!store) return null;
3455
+ const lockKey = `${message.channelId}:${message.threadId}`;
3456
+ const existing = this.resumeLocks.get(lockKey);
3457
+ if (existing) return existing;
3458
+ const record = store.findByPlatform(
3459
+ message.channelId,
3460
+ (p) => String(p.topicId) === message.threadId
3461
+ );
3462
+ if (!record) {
3463
+ log6.debug(
3464
+ { threadId: message.threadId, channelId: message.channelId },
3465
+ "No session record found for thread"
3466
+ );
3467
+ return null;
3468
+ }
3469
+ if (record.status === "error") {
3470
+ log6.debug(
3471
+ {
3472
+ threadId: message.threadId,
3473
+ sessionId: record.sessionId,
3474
+ status: record.status
3475
+ },
3476
+ "Skipping resume of error session"
3477
+ );
3478
+ return null;
3479
+ }
3480
+ log6.info(
3481
+ {
3482
+ threadId: message.threadId,
3483
+ sessionId: record.sessionId,
3484
+ status: record.status
3485
+ },
3486
+ "Lazy resume: found record, attempting resume"
3487
+ );
3488
+ const resumePromise = (async () => {
3489
+ try {
3490
+ const session = await this.createSession({
3491
+ channelId: record.channelId,
3492
+ agentName: record.agentName,
3493
+ workingDirectory: record.workingDir,
3494
+ resumeAgentSessionId: record.agentSessionId,
3495
+ existingSessionId: record.sessionId,
3496
+ initialName: record.name
3497
+ });
3498
+ session.threadId = message.threadId;
3499
+ session.activate();
3500
+ session.dangerousMode = record.dangerousMode ?? false;
3501
+ log6.info(
3502
+ { sessionId: session.id, threadId: message.threadId },
3503
+ "Lazy resume successful"
3504
+ );
3505
+ return session;
3506
+ } catch (err) {
3507
+ log6.error({ err, record }, "Lazy resume failed");
3508
+ const adapter = this.adapters.get(message.channelId);
3509
+ if (adapter) {
3510
+ try {
3511
+ await adapter.sendMessage(message.threadId, {
3512
+ type: "error",
3513
+ text: `\u26A0\uFE0F Failed to resume session: ${err instanceof Error ? err.message : String(err)}`
3514
+ });
3515
+ } catch {
3516
+ }
3517
+ }
3518
+ return null;
3519
+ } finally {
3520
+ this.resumeLocks.delete(lockKey);
3521
+ }
3522
+ })();
3523
+ this.resumeLocks.set(lockKey, resumePromise);
3524
+ return resumePromise;
3525
+ }
3526
+ // --- Event Wiring ---
3527
+ /** Create a SessionBridge for the given session and adapter */
3528
+ createBridge(session, adapter) {
3529
+ return new SessionBridge(session, adapter, {
3530
+ messageTransformer: this.messageTransformer,
3531
+ notificationManager: this.notificationManager,
3532
+ sessionManager: this.sessionManager,
3533
+ eventBus: this.eventBus,
3534
+ fileService: this.fileService,
3535
+ middlewareChain: this.lifecycleManager?.middlewareChain
3536
+ });
3537
+ }
3538
+ };
3539
+
3540
+ export {
3541
+ nodeToWebWritable,
3542
+ nodeToWebReadable,
3543
+ StderrCapture,
3544
+ TypedEmitter,
3545
+ AgentInstance,
3546
+ AgentManager,
3547
+ PromptQueue,
3548
+ PermissionGate,
3549
+ Session,
3550
+ SessionManager,
3551
+ SessionBridge,
3552
+ MessageTransformer,
3553
+ SessionFactory,
3554
+ EventBus,
3555
+ OpenACPCore
3556
+ };
3557
+ //# sourceMappingURL=chunk-FQEBWOZR.js.map