abtars 0.1.0-alpha.1

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 (312) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +84 -0
  3. package/bundle/_registry.generated-M4WY2MMI.js +35 -0
  4. package/bundle/_registry.generated-M4WY2MMI.js.map +7 -0
  5. package/bundle/abtars-browser.js +162 -0
  6. package/bundle/abtars-browser.js.map +7 -0
  7. package/bundle/abtars-cli.js +1438 -0
  8. package/bundle/abtars-cli.js.map +7 -0
  9. package/bundle/abtars-restart.js +12 -0
  10. package/bundle/abtars-restart.js.map +7 -0
  11. package/bundle/abtars-rss.js +165 -0
  12. package/bundle/abtars-rss.js.map +7 -0
  13. package/bundle/abtars-task.js +258 -0
  14. package/bundle/abtars-task.js.map +7 -0
  15. package/bundle/abtars.js +4072 -0
  16. package/bundle/abtars.js.map +7 -0
  17. package/bundle/agent-api-rate-limit-OQNFMXTZ.js +38 -0
  18. package/bundle/agent-api-rate-limit-OQNFMXTZ.js.map +7 -0
  19. package/bundle/agent-registry-LT4JNQH6.js +18 -0
  20. package/bundle/agent-registry-LT4JNQH6.js.map +7 -0
  21. package/bundle/agents/default.md +29 -0
  22. package/bundle/anthropic-adapter-2APTH3LA.js +40 -0
  23. package/bundle/anthropic-adapter-2APTH3LA.js.map +7 -0
  24. package/bundle/bridge-lock-transport-4AC2G5G6.js +39 -0
  25. package/bundle/bridge-lock-transport-4AC2G5G6.js.map +7 -0
  26. package/bundle/browse-delivery-JXBY36GK.js +17 -0
  27. package/bundle/browse-delivery-JXBY36GK.js.map +7 -0
  28. package/bundle/browser-ELNDVPLC.js +18 -0
  29. package/bundle/browser-ELNDVPLC.js.map +7 -0
  30. package/bundle/capability-CIL3G4FI.js +17 -0
  31. package/bundle/capability-CIL3G4FI.js.map +7 -0
  32. package/bundle/chunk-265TPOPC.js +289 -0
  33. package/bundle/chunk-265TPOPC.js.map +7 -0
  34. package/bundle/chunk-2UENBO6M.js +223 -0
  35. package/bundle/chunk-2UENBO6M.js.map +7 -0
  36. package/bundle/chunk-2UPU3OW6.js +67 -0
  37. package/bundle/chunk-2UPU3OW6.js.map +7 -0
  38. package/bundle/chunk-2XU2X4OI.js +125 -0
  39. package/bundle/chunk-2XU2X4OI.js.map +7 -0
  40. package/bundle/chunk-3B7BBE4F.js +758 -0
  41. package/bundle/chunk-3B7BBE4F.js.map +7 -0
  42. package/bundle/chunk-3E545J66.js +69 -0
  43. package/bundle/chunk-3E545J66.js.map +7 -0
  44. package/bundle/chunk-5R2ANXQ7.js +510 -0
  45. package/bundle/chunk-5R2ANXQ7.js.map +7 -0
  46. package/bundle/chunk-6CPN4IGS.js +507 -0
  47. package/bundle/chunk-6CPN4IGS.js.map +7 -0
  48. package/bundle/chunk-6NR3OHEW.js +88 -0
  49. package/bundle/chunk-6NR3OHEW.js.map +7 -0
  50. package/bundle/chunk-6SETMHNN.js +206 -0
  51. package/bundle/chunk-6SETMHNN.js.map +7 -0
  52. package/bundle/chunk-6UCRKRWR.js +644 -0
  53. package/bundle/chunk-6UCRKRWR.js.map +7 -0
  54. package/bundle/chunk-AR6GO6YC.js +83 -0
  55. package/bundle/chunk-AR6GO6YC.js.map +7 -0
  56. package/bundle/chunk-AZJIODTQ.js +54 -0
  57. package/bundle/chunk-AZJIODTQ.js.map +7 -0
  58. package/bundle/chunk-BHMZ4RCC.js +3706 -0
  59. package/bundle/chunk-BHMZ4RCC.js.map +7 -0
  60. package/bundle/chunk-BQ2L4GMG.js +9175 -0
  61. package/bundle/chunk-BQ2L4GMG.js.map +7 -0
  62. package/bundle/chunk-BSSBCSCL.js +159 -0
  63. package/bundle/chunk-BSSBCSCL.js.map +7 -0
  64. package/bundle/chunk-BUUVFUPO.js +157 -0
  65. package/bundle/chunk-BUUVFUPO.js.map +7 -0
  66. package/bundle/chunk-CEVRHKJY.js +131 -0
  67. package/bundle/chunk-CEVRHKJY.js.map +7 -0
  68. package/bundle/chunk-CWOHNFUV.js +39 -0
  69. package/bundle/chunk-CWOHNFUV.js.map +7 -0
  70. package/bundle/chunk-D2DCBO6M.js +228 -0
  71. package/bundle/chunk-D2DCBO6M.js.map +7 -0
  72. package/bundle/chunk-FMWKEPM7.js +31 -0
  73. package/bundle/chunk-FMWKEPM7.js.map +7 -0
  74. package/bundle/chunk-GRNENTPA.js +145 -0
  75. package/bundle/chunk-GRNENTPA.js.map +7 -0
  76. package/bundle/chunk-GST5T3WZ.js +93 -0
  77. package/bundle/chunk-GST5T3WZ.js.map +7 -0
  78. package/bundle/chunk-GUQVJC3U.js +299 -0
  79. package/bundle/chunk-GUQVJC3U.js.map +7 -0
  80. package/bundle/chunk-HX7Y7EYP.js +3659 -0
  81. package/bundle/chunk-HX7Y7EYP.js.map +7 -0
  82. package/bundle/chunk-JCJS4ZIB.js +296 -0
  83. package/bundle/chunk-JCJS4ZIB.js.map +7 -0
  84. package/bundle/chunk-JW6RU47G.js +184 -0
  85. package/bundle/chunk-JW6RU47G.js.map +7 -0
  86. package/bundle/chunk-LSPKJQCI.js +24 -0
  87. package/bundle/chunk-LSPKJQCI.js.map +7 -0
  88. package/bundle/chunk-M6VBAPNT.js +16 -0
  89. package/bundle/chunk-M6VBAPNT.js.map +7 -0
  90. package/bundle/chunk-MPX525QO.js +129 -0
  91. package/bundle/chunk-MPX525QO.js.map +7 -0
  92. package/bundle/chunk-MW6WDLU7.js +130 -0
  93. package/bundle/chunk-MW6WDLU7.js.map +7 -0
  94. package/bundle/chunk-NT3OBORC.js +215 -0
  95. package/bundle/chunk-NT3OBORC.js.map +7 -0
  96. package/bundle/chunk-NWDBD4PA.js +50 -0
  97. package/bundle/chunk-NWDBD4PA.js.map +7 -0
  98. package/bundle/chunk-OP7BTAWY.js +29 -0
  99. package/bundle/chunk-OP7BTAWY.js.map +7 -0
  100. package/bundle/chunk-PLCY3GFH.js +77 -0
  101. package/bundle/chunk-PLCY3GFH.js.map +7 -0
  102. package/bundle/chunk-PNEDC45Y.js +97 -0
  103. package/bundle/chunk-PNEDC45Y.js.map +7 -0
  104. package/bundle/chunk-QBGBT5QS.js +81 -0
  105. package/bundle/chunk-QBGBT5QS.js.map +7 -0
  106. package/bundle/chunk-RVE2N7FA.js +70 -0
  107. package/bundle/chunk-RVE2N7FA.js.map +7 -0
  108. package/bundle/chunk-TZHIDLDS.js +71910 -0
  109. package/bundle/chunk-TZHIDLDS.js.map +7 -0
  110. package/bundle/chunk-UCQ2WC3B.js +126 -0
  111. package/bundle/chunk-UCQ2WC3B.js.map +7 -0
  112. package/bundle/chunk-UHRP745J.js +214 -0
  113. package/bundle/chunk-UHRP745J.js.map +7 -0
  114. package/bundle/chunk-V76TVMCM.js +58 -0
  115. package/bundle/chunk-V76TVMCM.js.map +7 -0
  116. package/bundle/chunk-VVEDVGCR.js +981 -0
  117. package/bundle/chunk-VVEDVGCR.js.map +7 -0
  118. package/bundle/chunk-W6FAL35D.js +102 -0
  119. package/bundle/chunk-W6FAL35D.js.map +7 -0
  120. package/bundle/chunk-X6TERNVJ.js +15902 -0
  121. package/bundle/chunk-X6TERNVJ.js.map +7 -0
  122. package/bundle/chunk-X76UX47U.js +47 -0
  123. package/bundle/chunk-X76UX47U.js.map +7 -0
  124. package/bundle/chunk-XREWVCUO.js +518 -0
  125. package/bundle/chunk-XREWVCUO.js.map +7 -0
  126. package/bundle/chunk-Y6XAEX2Q.js +408 -0
  127. package/bundle/chunk-Y6XAEX2Q.js.map +7 -0
  128. package/bundle/chunk-YOCTDKKL.js +28 -0
  129. package/bundle/chunk-YOCTDKKL.js.map +7 -0
  130. package/bundle/chunk-ZXPXCDA6.js +160 -0
  131. package/bundle/chunk-ZXPXCDA6.js.map +7 -0
  132. package/bundle/commands-BHVUOU3V.js +31 -0
  133. package/bundle/commands-BHVUOU3V.js.map +7 -0
  134. package/bundle/completion-buffer-P253ONKF.js +13 -0
  135. package/bundle/completion-buffer-P253ONKF.js.map +7 -0
  136. package/bundle/config-RGSDAPZN.js +19 -0
  137. package/bundle/config-RGSDAPZN.js.map +7 -0
  138. package/bundle/config-show-ERTATR6E.js +40 -0
  139. package/bundle/config-show-ERTATR6E.js.map +7 -0
  140. package/bundle/context-HCEGZNDC.js +72 -0
  141. package/bundle/context-HCEGZNDC.js.map +7 -0
  142. package/bundle/delegation-tools-GYTS2D6A.js +27 -0
  143. package/bundle/delegation-tools-GYTS2D6A.js.map +7 -0
  144. package/bundle/deploy-lib-import-32ZFKHWP.js +49 -0
  145. package/bundle/deploy-lib-import-32ZFKHWP.js.map +7 -0
  146. package/bundle/digital-signature-OFCGSHWO.js +13 -0
  147. package/bundle/digital-signature-OFCGSHWO.js.map +7 -0
  148. package/bundle/direct-api-transport-YR7SXXNN.js +860 -0
  149. package/bundle/direct-api-transport-YR7SXXNN.js.map +7 -0
  150. package/bundle/discord-adapter-YYWVMPPU.js +584 -0
  151. package/bundle/discord-adapter-YYWVMPPU.js.map +7 -0
  152. package/bundle/dist-MTMKARCP.js +1969 -0
  153. package/bundle/dist-MTMKARCP.js.map +7 -0
  154. package/bundle/dns-wakeup-27M7D2MR.js +107 -0
  155. package/bundle/dns-wakeup-27M7D2MR.js.map +7 -0
  156. package/bundle/doctor-QNUSDY73.js +248 -0
  157. package/bundle/doctor-QNUSDY73.js.map +7 -0
  158. package/bundle/ensure-invariants-NMXNS476.js +49 -0
  159. package/bundle/ensure-invariants-NMXNS476.js.map +7 -0
  160. package/bundle/env-schema-2KBHBDGN.js +19 -0
  161. package/bundle/env-schema-2KBHBDGN.js.map +7 -0
  162. package/bundle/esm-DDP6NCZG.js +100663 -0
  163. package/bundle/esm-DDP6NCZG.js.map +7 -0
  164. package/bundle/fallback-policy-L4QV2PEJ.js +46 -0
  165. package/bundle/fallback-policy-L4QV2PEJ.js.map +7 -0
  166. package/bundle/health-check-SPA7NT6N.js +56 -0
  167. package/bundle/health-check-SPA7NT6N.js.map +7 -0
  168. package/bundle/hook-system-6Q5YTR53.js +17 -0
  169. package/bundle/hook-system-6Q5YTR53.js.map +7 -0
  170. package/bundle/hotskills-K7BM4YLB.js +12 -0
  171. package/bundle/hotskills-K7BM4YLB.js.map +7 -0
  172. package/bundle/install-6HRZVKUM.js +15 -0
  173. package/bundle/install-6HRZVKUM.js.map +7 -0
  174. package/bundle/install-log-IAPHYKD4.js +28 -0
  175. package/bundle/install-log-IAPHYKD4.js.map +7 -0
  176. package/bundle/install-manifest-SPQRUNXL.js +102 -0
  177. package/bundle/install-manifest-SPQRUNXL.js.map +7 -0
  178. package/bundle/install-validate-PVLZXYLQ.js +53 -0
  179. package/bundle/install-validate-PVLZXYLQ.js.map +7 -0
  180. package/bundle/irc-adapter-OI5UZSQF.js +293 -0
  181. package/bundle/irc-adapter-OI5UZSQF.js.map +7 -0
  182. package/bundle/irc-config-55YO6EGB.js +88 -0
  183. package/bundle/irc-config-55YO6EGB.js.map +7 -0
  184. package/bundle/logs-ZNYXX5PA.js +19 -0
  185. package/bundle/logs-ZNYXX5PA.js.map +7 -0
  186. package/bundle/media-utils-XNNDTYFI.js +4662 -0
  187. package/bundle/media-utils-XNNDTYFI.js.map +7 -0
  188. package/bundle/message-pipeline-LLH5SYMO.js +33 -0
  189. package/bundle/message-pipeline-LLH5SYMO.js.map +7 -0
  190. package/bundle/meta.json +41304 -0
  191. package/bundle/model-health-registry-35LQNVQR.js +11 -0
  192. package/bundle/model-health-registry-35LQNVQR.js.map +7 -0
  193. package/bundle/notification-Y5S5MMLV.js +13 -0
  194. package/bundle/notification-Y5S5MMLV.js.map +7 -0
  195. package/bundle/openrouter-credits-EDY7ETAU.js +32 -0
  196. package/bundle/openrouter-credits-EDY7ETAU.js.map +7 -0
  197. package/bundle/passwd-RRFV4CC5.js +133 -0
  198. package/bundle/passwd-RRFV4CC5.js.map +7 -0
  199. package/bundle/paths-G33RZWZ7.js +17 -0
  200. package/bundle/paths-G33RZWZ7.js.map +7 -0
  201. package/bundle/peer-client-52XYMNI7.js +156 -0
  202. package/bundle/peer-client-52XYMNI7.js.map +7 -0
  203. package/bundle/peer-config-VK6EDLN5.js +16 -0
  204. package/bundle/peer-config-VK6EDLN5.js.map +7 -0
  205. package/bundle/peer-sessions-EAXTNQ36.js +49 -0
  206. package/bundle/peer-sessions-EAXTNQ36.js.map +7 -0
  207. package/bundle/pending-callback-RIMQZ7FJ.js +40 -0
  208. package/bundle/pending-callback-RIMQZ7FJ.js.map +7 -0
  209. package/bundle/phase-transport-KYERDL2O.js +22 -0
  210. package/bundle/phase-transport-KYERDL2O.js.map +7 -0
  211. package/bundle/public/css/dashboard.css +542 -0
  212. package/bundle/public/index.html +180 -0
  213. package/bundle/public/js/app.js +437 -0
  214. package/bundle/public/memory-universe.js +384 -0
  215. package/bundle/responses-adapter-AAQTY3K4.js +30 -0
  216. package/bundle/responses-adapter-AAQTY3K4.js.map +7 -0
  217. package/bundle/restore-ZE3SEPSS.js +46 -0
  218. package/bundle/restore-ZE3SEPSS.js.map +7 -0
  219. package/bundle/self-healer-utils-DMUUXC47.js +43 -0
  220. package/bundle/self-healer-utils-DMUUXC47.js.map +7 -0
  221. package/bundle/skill-stats-LLEXEXLR.js +22 -0
  222. package/bundle/skill-stats-LLEXEXLR.js.map +7 -0
  223. package/bundle/sleep-OYIUOVQD.js +19 -0
  224. package/bundle/sleep-OYIUOVQD.js.map +7 -0
  225. package/bundle/soul-loader-54WCVNLJ.js +16 -0
  226. package/bundle/soul-loader-54WCVNLJ.js.map +7 -0
  227. package/bundle/src-JL4PVO23.js +8 -0
  228. package/bundle/src-JL4PVO23.js.map +7 -0
  229. package/bundle/sse-parser-anthropic-P7CE2MH2.js +72 -0
  230. package/bundle/sse-parser-anthropic-P7CE2MH2.js.map +7 -0
  231. package/bundle/sse-parser-responses-EQQA5FWN.js +63 -0
  232. package/bundle/sse-parser-responses-EQQA5FWN.js.map +7 -0
  233. package/bundle/ssrf-guard-FZCBYIVW.js +64 -0
  234. package/bundle/ssrf-guard-FZCBYIVW.js.map +7 -0
  235. package/bundle/start-FH3GRMJ4.js +35 -0
  236. package/bundle/start-FH3GRMJ4.js.map +7 -0
  237. package/bundle/stream-single-WSG4D53C.js +33 -0
  238. package/bundle/stream-single-WSG4D53C.js.map +7 -0
  239. package/bundle/stt-2UH3RITX.js +14 -0
  240. package/bundle/stt-2UH3RITX.js.map +7 -0
  241. package/bundle/subagent-runtime-LE2ZXH3G.js +12 -0
  242. package/bundle/subagent-runtime-LE2ZXH3G.js.map +7 -0
  243. package/bundle/system-message-T5R3EYYN.js +30 -0
  244. package/bundle/system-message-T5R3EYYN.js.map +7 -0
  245. package/bundle/system-status-KQ6KHFJ6.js +189 -0
  246. package/bundle/system-status-KQ6KHFJ6.js.map +7 -0
  247. package/bundle/task-store-K7CQDEPI.js +22 -0
  248. package/bundle/task-store-K7CQDEPI.js.map +7 -0
  249. package/bundle/telegram-adapter-2V3XUMT5.js +1060 -0
  250. package/bundle/telegram-adapter-2V3XUMT5.js.map +7 -0
  251. package/bundle/tool-registry-MU3OX4UI.js +38 -0
  252. package/bundle/tool-registry-MU3OX4UI.js.map +7 -0
  253. package/bundle/tool-sandbox-VYOK4ZOA.js +20 -0
  254. package/bundle/tool-sandbox-VYOK4ZOA.js.map +7 -0
  255. package/bundle/transport-config-YLXU33RO.js +57 -0
  256. package/bundle/transport-config-YLXU33RO.js.map +7 -0
  257. package/bundle/update-QCW5LXRN.js +13 -0
  258. package/bundle/update-QCW5LXRN.js.map +7 -0
  259. package/bundle/update-check-27KZSAP6.js +12 -0
  260. package/bundle/update-check-27KZSAP6.js.map +7 -0
  261. package/bundle/usage-tracker-OVVEVMOY.js +17 -0
  262. package/bundle/usage-tracker-OVVEVMOY.js.map +7 -0
  263. package/bundle/user-registry-D4SD73UV.js +16 -0
  264. package/bundle/user-registry-D4SD73UV.js.map +7 -0
  265. package/core/professor.json +14 -0
  266. package/core/prompts/browsing_prompt.md +39 -0
  267. package/core/prompts/compaction.md +32 -0
  268. package/core/skills/memory/classification/SKILL.md +37 -0
  269. package/core/skills/memory/memory-anomalies/SKILL.md +39 -0
  270. package/core/skills/memory/memory-search/SKILL.md +48 -0
  271. package/core/skills/memory/topic-save/SKILL.md +44 -0
  272. package/core/skills/ops/cron/SKILL.md +51 -0
  273. package/core/skills/ops/gdrive-backup/SKILL.md +15 -0
  274. package/core/skills/ops/session-start/SKILL.md +11 -0
  275. package/core/skills/ops/skill-authoring/SKILL.md +54 -0
  276. package/core/skills/ops/system-health/SKILL.md +104 -0
  277. package/core/skills/ops/troubleshooting/SKILL.md +48 -0
  278. package/core/skills/ops/trust-gating/SKILL.md +30 -0
  279. package/core/skills/tools/a2a-communication/SKILL.md +68 -0
  280. package/core/skills/tools/browse-delegate/SKILL.md +27 -0
  281. package/core/skills/tools/browser/SKILL.md +36 -0
  282. package/core/skills/tools/clawhub/SKILL.md +44 -0
  283. package/core/skills/tools/delegation/SKILL.md +48 -0
  284. package/core/skills/tools/fxtwitter/SKILL.md +52 -0
  285. package/core/skills/tools/gmail/SKILL.md +44 -0
  286. package/core/skills/tools/irc-chat/SKILL.md +84 -0
  287. package/core/skills/tools/linear/SKILL.md +90 -0
  288. package/core/skills/tools/mcporter/SKILL.md +46 -0
  289. package/core/skills/tools/model-scout/SKILL.md +132 -0
  290. package/core/skills/tools/model-scout/scout-add-model.py +67 -0
  291. package/core/skills/tools/model-scout/scout-ollama.py +116 -0
  292. package/core/skills/tools/model-scout/scout-openrouter.py +85 -0
  293. package/core/skills/tools/nlm/SKILL.md +40 -0
  294. package/core/skills/tools/todo/SKILL.md +30 -0
  295. package/core/skills/tools/twitterX/SKILL.md +52 -0
  296. package/core/skills/tools/twitterX/scripts/abtars-tweet.js +532 -0
  297. package/core/skills/tools/twitterX/scripts/package.json +1 -0
  298. package/core/skills/tools/web-fetch/SKILL.md +29 -0
  299. package/package.json +59 -0
  300. package/scripts/abtars-daemon.service +23 -0
  301. package/scripts/abtars-fetch.sh +42 -0
  302. package/scripts/abtars-watchdog.service +13 -0
  303. package/scripts/abtars.sh +14 -0
  304. package/scripts/abtars@.service +21 -0
  305. package/scripts/browser-patchright.sh +79 -0
  306. package/scripts/com.abtars.daemon.plist +24 -0
  307. package/scripts/com.abtars.watchdog.plist +27 -0
  308. package/scripts/daily-backup.sh +62 -0
  309. package/scripts/doctor.sh +553 -0
  310. package/scripts/hooks/audit-logger.sh +22 -0
  311. package/scripts/upgrade-deps.sh +64 -0
  312. package/scripts/watchdog.sh +309 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/boot/phase-transport.ts", "../src/components/transport/tmux-client.ts", "../src/boot/ctx-start.ts"],
4
+ "sourcesContent": ["import { logAndSwallow } from \"../components/log-and-swallow.js\";\nimport { getEnv } from \"../components/env-schema.js\";\n/**\n * phase-transport \u2014 boot phase 3: select, initialize, and wrap the agent transport.\n *\n * Also exports buildTransport/rebuildTransport for /reset to pick up transport.json changes\n * (including provider switches that can't be live-patched).\n */\n\nimport { execSync } from \"node:child_process\";\nimport { TmuxClient } from \"../components/transport/tmux-client.js\";\nimport { createAgentTransport } from \"../components/agent-registry.js\";\nimport { logInfo, logWarn, logError, isLogLevel } from \"../components/logger.js\";\nimport { loadUsers } from \"../components/user-registry.js\";\nimport { updateCtxStart } from \"./ctx-start.js\";\nimport type { BootCtx, PhaseResult } from \"./context.js\";\nimport type { IKiroTransport } from \"../components/transport/kiro-transport.js\";\n\nconst TAG = \"transport\";\n\nexport async function phaseTransport(ctx: BootCtx): Promise<PhaseResult> {\n const { memoryConfig } = ctx;\n\n await buildTransport(ctx);\n\n // Initialize context-window-start for all known users\n if (memoryConfig.memoryEnabled) {\n const reg = loadUsers();\n for (const user of reg.users) updateCtxStart(memoryConfig.memoryDir, user.userId, ctx.startedAt);\n }\n return \"ran\";\n}\n\n/**\n * Construct professor transport from current transport.json + env and attach to ctx.transport.\n * Idempotent: destroys any existing ctx.transport first.\n *\n * #367 \u2014 Validates the resolved provider BEFORE destroying the old transport.\n * If validation fails:\n * - During `/reset` (old transport exists): logs ERROR, keeps the old transport up\n * - At boot (no old transport): falls back to .env config if possible, or throws\n * - In either case: bridge stays alive in degraded mode rather than crash-looping\n */\nexport async function buildTransport(ctx: BootCtx): Promise<PhaseResult> {\n const { config, memoryConfig } = ctx;\n\n let transport: IKiroTransport;\n\n const { resolveAgent, getEnvFallback, loadTransport, resolveHailMary, clearTransportCache, validateProviderReady } = await import(\"../components/transport-config.js\");\n clearTransportCache(); // always re-read (picks up /models change writes)\n const tc = loadTransport();\n const prof = tc ? resolveAgent(\"professor\", tc) : null;\n\n const hm = resolveHailMary(tc);\n if (hm) {\n ctx.hailMary = {\n model: hm.model,\n endpoint: hm.endpoint,\n apiKey: hm.apiKeyEnv ? getEnv().getApiKey(hm.apiKeyEnv) : undefined,\n };\n logInfo(\"main\", `\uD83D\uDEA8 hailMary configured: ${hm.model} (manual /model emergency only)`);\n } else {\n ctx.hailMary = null;\n }\n\n let resolved = prof ?? (() => {\n const fb = getEnvFallback();\n logWarn(\"main\", `\u26A0\uFE0F Using .env fallback: ${fb.model} via ${fb.providerName}`);\n return { model: fb.model, provider: fb.provider, providerName: fb.providerName, contextWindow: fb.contextWindow, maxOutput: fb.maxOutput, fallbacks: [] };\n })();\n\n // #367 \u2014 validate the resolved provider BEFORE destroying the existing transport.\n // If validation fails and an old transport is up, keep it; surface the error.\n // If no old transport (boot time), try .env fallback.\n const validation = validateProviderReady(resolved.providerName, resolved.provider, getEnv());\n if (!validation.ok) {\n const errMsg = `transport.json configures '${resolved.providerName}' but ${validation.reason}. Fix: ${validation.fix}`;\n if (ctx.transport) {\n // Existing transport still good \u2014 keep it. Don't destroy.\n logError(\"main\", `${errMsg} \u2014 keeping existing transport up (skipping rebuild)`);\n return \"ran\";\n }\n // Boot-time: try falling back to .env if we weren't already using it\n if (prof) {\n const fb = getEnvFallback();\n logError(\"main\", `${errMsg} \u2014 falling back to .env config (${fb.model} via ${fb.providerName})`);\n resolved = { model: fb.model, provider: fb.provider, providerName: fb.providerName, contextWindow: fb.contextWindow, maxOutput: fb.maxOutput, fallbacks: [] };\n // Validate fallback too \u2014 if even .env is broken, let the original error bubble\n const fbValidation = validateProviderReady(resolved.providerName, resolved.provider, getEnv());\n if (!fbValidation.ok) {\n logError(\"main\", `.env fallback '${resolved.providerName}' also invalid: ${fbValidation.reason}`);\n throw new Error(`${errMsg} (and .env fallback is also invalid: ${fbValidation.reason})`);\n }\n } else {\n // Already on .env fallback path and it's invalid \u2014 hard error\n throw new Error(errMsg);\n }\n }\n\n // Destroy old (if any) \u2014 now that we know the new config is valid\n if (ctx.transport) {\n try { await ctx.transport.destroy(); } catch (err) {\n logWarn(\"main\", `Old transport destroy failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n ctx.transport = null;\n }\n\n if (resolved.provider.transport === \"tmux\") {\n const defaults = tc?.transportDefaults?.tmux;\n logInfo(\"main\", `\uD83D\uDDA5\uFE0F tmux transport (${resolved.providerName})`);\n transport = new TmuxClient(\n defaults?.session ?? config.transport.tmuxSession,\n defaults?.captureDelaySec ?? config.transport.tmuxCaptureDelaySec,\n defaults?.maxWaitSec ?? config.transport.tmuxMaxWaitSec,\n );\n } else if (resolved.provider.transport === \"api\") {\n const { DirectApiTransport } = await import(\"../components/transport/direct-api-transport.js\");\n const { ModelHealthRegistry } = await import(\"../components/transport/model-health-registry.js\");\n const { FallbackPolicy } = await import(\"../components/transport/fallback-policy.js\");\n const apiKey = getEnv().getApiKey(resolved.provider.apiKeyEnv ?? \"API_KEY\");\n\n const candidates: Array<{ model: string; endpoint: string; apiKey?: string; maxContext: number }> = [\n { endpoint: resolved.provider.endpoint ?? \"http://localhost:11434/v1\", apiKey, model: resolved.model, maxContext: resolved.contextWindow },\n ];\n for (const fb of resolved.fallbacks) {\n const fbResolved = tc ? resolveAgent(\"_fallback\", { ...tc, agents: { ...tc.agents, _fallback: { model: fb.model, provider: fb.provider } } }) : null;\n candidates.push({\n endpoint: fbResolved?.provider.endpoint ?? resolved.provider.endpoint!,\n apiKey: fbResolved?.provider.apiKeyEnv ? getEnv().getApiKey(fbResolved.provider.apiKeyEnv) : apiKey,\n model: fb.model,\n maxContext: fbResolved?.contextWindow ?? resolved.contextWindow,\n });\n }\n\n if (!ctx.modelHealthRegistry) {\n ctx.modelHealthRegistry = new ModelHealthRegistry(tc?.healthPolicy);\n }\n // Wire auto-demotion\n if (!ctx.modelHealthRegistry.onDemote) {\n ctx.modelHealthRegistry.onDemote = (model, _endpoint, reason) => {\n import(\"../components/transport-config.js\").then(({ demoteModel }) => demoteModel(model, reason));\n import(\"../components/notification.js\").then(({ sendNotification }) =>\n sendNotification(ctx, `\u26A0\uFE0F ${model} demoted (${reason}). Next healthy model promoted.`)).catch(err => logAndSwallow(TAG, \"sendNotification model-demote\", err));\n };\n }\n const policy = new FallbackPolicy(candidates, ctx.modelHealthRegistry);\n\n transport = new DirectApiTransport({\n endpoint: resolved.provider.endpoint ?? \"http://localhost:11434/v1\",\n apiKey,\n model: resolved.model,\n maxContext: resolved.contextWindow,\n maxOutput: resolved.maxOutput,\n maxTurns: tc?.maxTurns ?? 50,\n apiFormat: resolved.provider.apiFormat,\n thinking: resolved.provider.thinking,\n }, policy);\n logInfo(\"main\", `\uD83D\uDD0C Direct API transport (${resolved.providerName}, model=${resolved.model}, ${candidates.length} candidates)`);\n } else {\n try { execSync(\"pkill -f 'kiro-cli.*acp.*professor' 2>/dev/null || true\", { timeout: 3000 }); } catch (err) { logAndSwallow(\"phase_transport\", \"op\", err); }\n logInfo(\"main\", `\uD83D\uDD0C ACP transport (${resolved.provider.cli ?? \"kiro-cli\"}, model=${resolved.model})`);\n transport = createAgentTransport(\"professor\", {\n cliPath: resolved.provider.cli ?? config.transport.agentCliPath,\n workingDir: config.transport.workingDir,\n agentCli: resolved.provider.cli ?? \"kiro-cli\",\n model: resolved.model,\n });\n }\n\n await transport.initialize();\n\n if (\"setSystemPrompt\" in transport && typeof (transport as { setSystemPrompt: unknown }).setSystemPrompt === \"function\") {\n const { loadSoulBundle } = await import(\"../components/soul-loader.js\");\n const soul = loadSoulBundle();\n if (soul) (transport as { setSystemPrompt: (p: string) => void }).setSystemPrompt(soul);\n }\n\n if (resolved.fallbacks.length > 0 && resolved.provider.transport !== \"api\") {\n logWarn(\"main\", `\u26A0\uFE0F Fallbacks configured for ${resolved.provider.transport} transport \u2014 only API transport supports model fallback`);\n }\n\n ctx.transport = transport;\n ctx.modelName = resolved.model;\n ctx.modelProvider = resolved.providerName;\n ctx.fallbackChain = resolved.fallbacks.map((f: { model: string }) => f.model);\n\n if (ctx.modelHealthRegistry) {\n ctx.runtime.setRegistry(ctx.modelHealthRegistry);\n }\n ctx.runtime.setMainTransport(transport);\n ctx.runtime.setSessionManager(ctx.sessionManager);\n\n // Wire async delegation tools (#570)\n if (getEnv().enableAsyncDelegation) {\n const { setDelegationDeps } = await import(\"../components/transport/delegation-tools.js\");\n setDelegationDeps(ctx.runtime, ctx.sessionManager);\n }\n\n logInfo(\"main\", \"\u2705 Transport ready\");\n\n if (resolved.provider.transport === \"api\" && ctx.memory) {\n const { setMemoryBackend } = await import(\"../components/transport/tool-registry.js\");\n const { SqliteBackend } = await import(\"abmind\");\n const backend = new SqliteBackend(memoryConfig);\n await backend.initialize();\n setMemoryBackend(backend);\n logInfo(\"main\", \"\uD83E\uDDE0 In-process memory wired to tool registry\");\n\n // Wire context engine for automatic compaction\n const db = ctx.memory.getDb?.() ?? ctx.memory.getDatabase?.();\n if (db && resolved.contextWindow >= 128000) {\n const { ContextEngine } = await import(\"abmind\");\n const { createContextOrchestrator } = await import(\"../components/context/index.js\");\n const contextEngine = new ContextEngine(db);\n const orchestrator = createContextOrchestrator(\n contextEngine,\n async (systemPrompt: string, userPrompt: string) => {\n // Use the transport itself for summarization (same model, same endpoint)\n const { streamSingleCompletion } = await import(\"../components/transport/stream-single.js\");\n return streamSingleCompletion({\n endpoint: resolved.provider.endpoint ?? \"http://localhost:11434/v1\",\n apiKey: getEnv().getApiKey(resolved.provider.apiKeyEnv ?? \"API_KEY\") ?? undefined,\n model: resolved.model,\n systemPrompt,\n userPrompt,\n maxTokens: 4096,\n });\n },\n (_chatId: string) => {\n try { return ctx.memory?.getLastMessageTimestamp(true) ?? null; } catch (err) { logAndSwallow(TAG, \"getLastMessageTimestamp\", err); return null; }\n },\n );\n (transport as import(\"../components/transport/direct-api-transport.js\").DirectApiTransport).contextOrchestrator = orchestrator;\n logInfo(\"main\", \"\uD83D\uDCE6 Context engine wired (auto-compaction active)\");\n }\n }\n\n if (\"onFallback\" in transport) {\n let lastNotifiedModel: string | null = null;\n (transport as unknown as { onFallback: (model: string, ctxPct: number, reason?: string) => void }).onFallback = (model, ctxPct, reason) => {\n const reasonTag = reason ? ` (${reason})` : \"\";\n const msg = `\u26A1 Fallback${reasonTag}: ${model}${ctxPct >= 0 ? ` (ctx: ~${ctxPct}%)` : \"\"}`;\n logInfo(\"main\", msg);\n if (model !== lastNotifiedModel || isLogLevel(\"debug\")) {\n lastNotifiedModel = model;\n import(\"../components/notification.js\").then(({ sendNotification }) => sendNotification(ctx, msg)).catch(err => logAndSwallow(TAG, \"sendNotification fallback\", err));\n }\n };\n }\n return \"ran\";\n}\n\n/**\n * Rebuild professor transport in place (picks up transport.json changes).\n * Patches downstream references that captured the old transport (pipelineDeps, idleSave).\n */\nexport async function rebuildTransport(ctx: BootCtx): Promise<PhaseResult> {\n logInfo(\"main\", \"\uD83D\uDD04 Rebuilding transport...\");\n await buildTransport(ctx);\n if (ctx.pipelineDeps && ctx.transport) {\n (ctx.pipelineDeps as { transport: IKiroTransport }).transport = ctx.transport;\n }\n if (ctx.idleSave && ctx.transport) {\n (ctx.idleSave as unknown as { transport: IKiroTransport }).transport = ctx.transport;\n }\n logInfo(\"main\", \"\u2705 Transport rebuilt\");\n return \"ran\";\n}\n", "import { execSync } from \"node:child_process\";\nimport { writeFileSync, unlinkSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { IKiroTransport } from \"./kiro-transport.js\";\nimport { logInfo, logDebug, logWarn } from \"../logger.js\";\nimport { logAndSwallow } from \"../log-and-swallow.js\";\nimport { abtarsHome } from \"../../paths.js\";\n\nconst TAG = \"tmux\";\n\n// Kiro CLI prompt pattern: \"N% >\" or \"N% !>\" where N is a number (context usage percentage)\n// The \"!\" appears in trust-all-tools mode\nconst KIRO_PROMPT_RE = /^\\d+%\\s*!?>/;\n\n// Also match common shell prompts as fallback\nconst SHELL_PROMPT_RE = /[$\u276F%#]\\s*$/;\n\n/**\n * Communicates with kiro-cli running inside a tmux session.\n * Uses `tmux send-keys` to send prompts and `tmux capture-pane`\n * to read responses.\n */\nexport class TmuxClient implements IKiroTransport {\n private readonly sessionName: string;\n private readonly captureDelaySec: number;\n private readonly maxWaitSec: number;\n private ready = false;\n\n /** Optional callback for streaming intermediate responses before final prompt. */\n onIntermediateResponse?: (text: string) => void;\n\n /** Tracks the cumulative text delivered via intermediate chunks (for tail detection). */\n private lastIntermediateDelivered = \"\";\n\n constructor(sessionName: string, captureDelaySec: number, maxWaitSec: number) {\n this.sessionName = sessionName;\n this.captureDelaySec = captureDelaySec;\n this.maxWaitSec = maxWaitSec;\n }\n\n async initialize(): Promise<void> {\n if (!this.sessionExists()) {\n throw new Error(\n `tmux session \"${this.sessionName}\" not found. ` +\n `Run: scripts/tmux-session.sh to start it.`,\n );\n }\n this.ready = true;\n logInfo(\"tmux\", `Session \"${this.sessionName}\" found`);\n }\n\n get isReady(): boolean {\n return this.ready && this.sessionExists();\n }\n\n readonly transportCommands: string[] = [];\n\n async sendPrompt(_sessionKey: string, message: string): Promise<string> {\n if (!this.isReady) {\n throw new Error(\"tmux session not available\");\n }\n\n this.lastIntermediateDelivered = \"\";\n const maxAttempts = 2;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Snapshot pane content before sending\n const before = this.capturePaneRaw();\n if (attempt === 1) {\n logDebug(\"tmux\", `Sending: \"${message.slice(0, 80)}\"`);\n } else {\n logInfo(\"tmux\", `Retry #${attempt}: resending prompt`);\n }\n\n // Send the message \u2014 use temp file for long prompts to avoid tmux command length limit\n try {\n if (message.length > 4000) {\n const tmpDir = join(abtarsHome(), \"tmp\");\n mkdirSync(tmpDir, { recursive: true });\n const tmpFile = join(tmpDir, `prompt-${Date.now()}.txt`);\n writeFileSync(tmpFile, message);\n const readCmd = `My full message is in ${tmpFile} \u2014 please read it and respond.`;\n const escaped = readCmd.replace(/'/g, \"'\\\\''\");\n this.exec(`tmux send-keys -t ${this.sessionName} '${escaped}' Enter`);\n setTimeout(() => { try { unlinkSync(tmpFile); } catch (err) { logAndSwallow(TAG, \"unlink tmpFile\", err); } }, 120_000);\n } else {\n const escaped = message.replace(/'/g, \"'\\\\''\");\n this.exec(`tmux send-keys -t ${this.sessionName} '${escaped}' Enter`);\n }\n } catch (err) {\n logWarn(\"tmux\", `send-keys failed: ${err instanceof Error ? err.message : String(err)}`);\n return \"\u26A0\uFE0F Failed to send message to Kiro session. The tmux session may be in copy mode or unresponsive. Try /reset.\";\n }\n\n // Wait for initial processing\n await sleep(this.captureDelaySec * 1000);\n\n // Poll until Kiro finishes\n const response = await this.pollForResponse(before);\n\n // Check for Kiro transient error \u2014 retry once\n if (response.startsWith(\"Kiro is having trouble\") && attempt < maxAttempts) {\n logInfo(\"tmux\", `Kiro trouble detected, will retry in 5s...`);\n await sleep(5000);\n continue;\n }\n\n logDebug(\"tmux\", `Got response (${response.length} chars)`);\n return response;\n }\n\n // Should not reach here, but just in case\n return \"\u26A0\uFE0F Kiro is having trouble responding. Try again or /reset.\";\n }\n\n async resetSession(_sessionKey: string): Promise<void> {\n if (!this.sessionExists()) return;\n this.exec(`tmux send-keys -t ${this.sessionName} C-c`);\n await sleep(1000);\n this.exec(`tmux send-keys -t ${this.sessionName} '/clear' Enter`);\n await sleep(2000);\n // Kiro asks \"Are you sure? [y/n]:\" \u2014 confirm with 'y'\n this.exec(`tmux send-keys -t ${this.sessionName} 'y' Enter`);\n await sleep(1000);\n }\n\n async restartSession(workingDir: string, kiroModel?: string): Promise<void> {\n // Kill existing tmux session and start fresh\n if (this.sessionExists()) {\n this.exec(`tmux kill-session -t ${this.sessionName}`);\n await sleep(1000);\n }\n let cmd = `kiro-cli chat --trust-all-tools`;\n if (kiroModel) cmd += ` --model ${kiroModel}`;\n this.exec(`tmux new-session -d -s ${this.sessionName} -c '${workingDir}' '${cmd}'`);\n this.exec(`tmux set-option -t ${this.sessionName} history-limit 5000`);\n await sleep(3000);\n // Enable thinking tool\n this.exec(`tmux send-keys -t ${this.sessionName} '/settings chat.enableThinking true' Enter`);\n await sleep(2000);\n this.ready = this.sessionExists();\n logInfo(\"tmux\", `Session restarted (ready=${this.ready})`);\n }\n\n async sendInterrupt(): Promise<void> {\n if (!this.sessionExists()) return;\n logInfo(\"tmux\", \"Sending Ctrl+C interrupt\");\n this.exec(`tmux send-keys -t ${this.sessionName} C-c`);\n }\n\n destroy(): void {\n this.ready = false;\n }\n\n /**\n * Poll capture-pane until Kiro's prompt reappears (N% >).\n * Delivers intermediate purple-line responses via onIntermediateResponse callback\n * so the user sees partial answers while Kiro continues with tools.\n * Only returns when the actual Kiro prompt appears or timeout.\n */\n private async pollForResponse(beforeSnapshot: string): Promise<string> {\n const startTime = Date.now();\n const maxWaitMs = this.maxWaitSec * 1000;\n let lastCapture = \"\";\n let stableCount = 0;\n let lastDeliveredAnswer = \"\";\n\n while (Date.now() - startTime < maxWaitMs) {\n const capture = this.capturePaneRaw();\n\n // Get only the NEW content (diff from before)\n const newContent = this.diffOutput(beforeSnapshot, capture);\n\n if (newContent.length === 0) {\n await sleep(2000);\n continue;\n }\n\n // Check if the last non-empty line is a Kiro prompt (N% >)\n const lines = capture.split(\"\\n\");\n const lastNonEmpty = this.getLastNonEmptyLine(lines);\n const lastClean = this.stripAnsi(lastNonEmpty);\n\n if (KIRO_PROMPT_RE.test(lastClean)) {\n const pctMatch = lastClean.match(/^(\\d+)%/);\n if (pctMatch) {\n this.lastContextPercent = parseInt(pctMatch[1]!, 10);\n logDebug(\"tmux\", `Context window: ${this.lastContextPercent}%`);\n }\n logDebug(\"tmux\", `Detected Kiro prompt: \"${lastClean}\"`);\n return this.extractResponse(newContent);\n }\n\n // Check for shell prompt as fallback\n if (SHELL_PROMPT_RE.test(lastClean) && newContent.length > 10) {\n logDebug(\"tmux\", `Detected shell prompt: \"${lastClean}\"`);\n return this.extractResponse(newContent);\n }\n\n // No prompt yet \u2014 deliver intermediate answer if we have new purple lines\n if (this.onIntermediateResponse && capture !== lastCapture) {\n const intermediateAnswer = this.extractAnswerOnly(newContent);\n if (intermediateAnswer && intermediateAnswer !== lastDeliveredAnswer) {\n const newPart = intermediateAnswer.startsWith(lastDeliveredAnswer)\n ? intermediateAnswer.slice(lastDeliveredAnswer.length).trim()\n : intermediateAnswer;\n if (newPart) {\n logDebug(\"tmux\", `Delivering intermediate chunk (${newPart.length} chars)`);\n this.onIntermediateResponse(newPart);\n lastDeliveredAnswer = intermediateAnswer;\n this.lastIntermediateDelivered = intermediateAnswer;\n }\n }\n }\n\n // Track stabilization but do NOT return on it \u2014 only N% > ends the poll\n if (capture === lastCapture) {\n stableCount++;\n } else {\n stableCount = 0;\n lastCapture = capture;\n }\n\n await sleep(2000);\n }\n\n // Timeout\n const finalCapture = this.capturePaneRaw();\n const finalNew = this.diffOutput(beforeSnapshot, finalCapture);\n if (finalNew.length > 0) {\n return this.extractResponse(finalNew) + \"\\n\\n\u23F1\uFE0F (response may be incomplete \u2014 timed out)\";\n }\n return \"\u23F1\uFE0F Kiro is still processing. Check the tmux session directly.\";\n }\n\n /**\n * Extract the meaningful response from the diff.\n * Removes the echoed user input line and Kiro's prompt lines.\n * Stores the \"answer only\" portion (lines that were \"> \" prefixed)\n * separately for TTS use.\n *\n * Kiro output format:\n * N% > <echoed user input>\n * > <response line 1>\n * > <response line 2>\n * \u25B8 Time: Ns\n * M% >\n */\n private lastAnswerOnly = \"\";\n private lastContextPercent = -1;\n\n /** Get just the Kiro answer lines (\"> \" prefixed) from the last response \u2014 for TTS. */\n get answerOnly(): string {\n return this.lastAnswerOnly;\n }\n get toolCallsSucceeded(): number { return 0; }\n\n /** Get the context window usage percentage from the last Kiro prompt (e.g. 10 for \"10% >\"). Returns -1 if unknown. */\n get contextPercent(): number {\n return this.lastContextPercent;\n }\n /** Get the cumulative text that was delivered via intermediate streaming. */\n get intermediateDeliveredText(): string {\n return this.lastIntermediateDelivered;\n }\n\n /** Extract just the purple \"> \" answer lines from raw tmux output (no side effects). */\n private extractAnswerOnly(raw: string): string {\n const PURPLE_PREFIX = /\\x1b\\[38;5;141m>\\s/;\n const lines = raw.split(\"\\n\");\n\n // Find last contiguous block of purple lines\n let blockStart = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n if (PURPLE_PREFIX.test(lines[i]!)) {\n blockStart = i;\n while (blockStart > 0 && PURPLE_PREFIX.test(lines[blockStart - 1]!)) blockStart--;\n break;\n }\n }\n if (blockStart < 0) return \"\";\n\n const answerLines: string[] = [];\n for (let i = blockStart; i < lines.length; i++) {\n const clean = this.stripAnsi(lines[i]!).trim();\n if (KIRO_PROMPT_RE.test(clean)) break;\n if (clean.startsWith(\"\u25B8 Time:\")) break;\n if (clean.startsWith(\"> \")) answerLines.push(clean.slice(2));\n else if (clean === \">\") answerLines.push(\"\");\n else if (clean === \"\") answerLines.push(\"\");\n else answerLines.push(clean);\n }\n return answerLines.join(\"\\n\").trim();\n }\n\n private extractResponse(raw: string): string {\n // ANSI color 141 (light purple) marks the \"> \" prefix on actual LLM response lines.\n // We detect these BEFORE stripping ANSI to reliably distinguish LLM output from\n // injected context (gray, color 245) and other noise.\n const PURPLE_PREFIX = /\\x1b\\[38;5;141m>\\s/;\n\n const lines = raw.split(\"\\n\");\n\n // First pass: identify lines that are genuine LLM responses (purple \"> \" prefix)\n const answerLines: string[] = [];\n let lastPurpleBlockStart = -1;\n\n for (let i = 0; i < lines.length; i++) {\n if (PURPLE_PREFIX.test(lines[i]!)) {\n if (lastPurpleBlockStart === -1) lastPurpleBlockStart = i;\n }\n }\n\n // Find the LAST contiguous block of purple \"> \" lines \u2014 that's the real answer.\n // Walk backwards to find the start of the last block.\n let blockStart = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n if (PURPLE_PREFIX.test(lines[i]!)) {\n blockStart = i;\n // Keep walking back through contiguous purple lines and continuation lines\n while (blockStart > 0) {\n const prev = lines[blockStart - 1]!;\n if (PURPLE_PREFIX.test(prev) || (!KIRO_PROMPT_RE.test(this.stripAnsi(prev).trim()) && !prev.includes(\"\u25B8 Time:\") && this.stripAnsi(prev).trim() !== \"\" && !PURPLE_PREFIX.test(prev) && blockStart === i)) {\n // Only extend back through purple lines\n if (PURPLE_PREFIX.test(prev)) {\n blockStart--;\n } else {\n break;\n }\n } else {\n break;\n }\n }\n break;\n }\n }\n\n if (blockStart >= 0) {\n // Extract from the last purple block to the end, stripping ANSI and \"> \" prefix\n for (let i = blockStart; i < lines.length; i++) {\n const line = lines[i]!;\n const clean = this.stripAnsi(line).trim();\n // Stop at Kiro prompt or Time summary\n if (KIRO_PROMPT_RE.test(clean)) break;\n if (clean.startsWith(\"\u25B8 Time:\") || clean.startsWith(\"\u25B8 Time:\")) break;\n if (clean === \"\") {\n answerLines.push(\"\");\n continue;\n }\n // Strip \"> \" prefix\n if (clean.startsWith(\"> \")) {\n answerLines.push(clean.slice(2));\n } else if (clean === \">\") {\n answerLines.push(\"\");\n } else {\n answerLines.push(clean);\n }\n }\n this.lastAnswerOnly = answerLines.join(\"\\n\").trim();\n } else {\n this.lastAnswerOnly = \"\";\n }\n\n // Full response: strip ANSI, then remove prompt lines and noise (legacy behavior)\n const cleaned = this.stripAnsi(raw);\n const allLines = cleaned.split(\"\\n\");\n const result: string[] = [];\n\n for (const line of allLines) {\n const trimmed = line.trim();\n if (result.length === 0 && trimmed === \"\") continue;\n if (KIRO_PROMPT_RE.test(trimmed)) continue;\n if (trimmed.startsWith(\"\u25B8 Time:\") || trimmed.startsWith(\"\u25B8 Time:\")) continue;\n if (/^-{4,}$/.test(trimmed)) continue;\n result.push(line);\n }\n\n const stripped = result.map((line) => {\n const trimmed = line.trimStart();\n if (trimmed.startsWith(\"> \")) return trimmed.slice(2);\n if (trimmed === \">\") return \"\";\n return line;\n });\n\n const final = stripped.join(\"\\n\").trim();\n logDebug(\"tmux\", `extractResponse: ${result.length} lines \u2192 \"${final.slice(0, 120)}\"`);\n if (this.lastAnswerOnly) {\n logDebug(\"tmux\", `answerOnly (${this.lastAnswerOnly.length} chars): \"${this.lastAnswerOnly.slice(0, 120)}\"`);\n }\n return final;\n }\n\n /** Get new content by diffing before/after snapshots. */\n private diffOutput(before: string, after: string): string {\n const beforeLines = before.split(\"\\n\");\n const afterLines = after.split(\"\\n\");\n\n // Find where the new content starts\n let commonPrefix = 0;\n while (\n commonPrefix < beforeLines.length &&\n commonPrefix < afterLines.length &&\n beforeLines[commonPrefix] === afterLines[commonPrefix]\n ) {\n commonPrefix++;\n }\n\n return afterLines.slice(commonPrefix).join(\"\\n\").trim();\n }\n\n /** Get the last non-empty line from an array. */\n private getLastNonEmptyLine(lines: string[]): string {\n for (let i = lines.length - 1; i >= 0; i--) {\n const trimmed = lines[i]!.trim();\n if (trimmed.length > 0) return trimmed;\n }\n return \"\";\n }\n\n /** Strip ANSI escape codes. */\n private stripAnsi(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/\\x1B\\[[0-9;]*[a-zA-Z]/g, \"\")\n .replace(/\\x1B\\][^\\x07]*\\x07/g, \"\"); // OSC sequences\n }\n\n private capturePaneRaw(): string {\n try {\n return this.exec(`tmux capture-pane -t ${this.sessionName} -p -e -S -2000`);\n } catch (err) {\n logAndSwallow(TAG, \"capturePaneRaw\", err);\n return \"\";\n }\n }\n\n private sessionExists(): boolean {\n try {\n this.exec(`tmux has-session -t ${this.sessionName}`);\n return true;\n } catch (err) {\n logAndSwallow(TAG, \"sessionExists check\", err);\n return false;\n }\n }\n\n private exec(command: string): string {\n return execSync(command, {\n encoding: \"utf-8\",\n timeout: 15_000,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n", "/**\n * Context-window-start persistence \u2014 per-user timestamps tracking when the\n * current context window began. Used by recall fallback stages.\n *\n * Called from phase-transport (initialize at boot), phase-sleep-cycle (reset\n * after sleep), and message-pipeline (update on session turn).\n */\n\nimport { logAndSwallow } from \"../components/log-and-swallow.js\";\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** Update context-window-start timestamp for a chat. */\nexport function updateCtxStart(memoryDir: string, userId: string, ts = Date.now()): void {\n const p = join(memoryDir, \"context-window-start.json\");\n let data: Record<string, number> = {};\n try { data = JSON.parse(readFileSync(p, \"utf-8\")); } catch (err) { logAndSwallow(\"ctx_start\", \"op\", err); }\n data[userId] = ts;\n writeFileSync(p, JSON.stringify(data), \"utf-8\");\n}\n\n/** Set all context-window-start entries to now (called after sleep). */\nexport function resetAllCtxStarts(memoryDir: string): void {\n const p = join(memoryDir, \"context-window-start.json\");\n let data: Record<string, number> = {};\n try { data = JSON.parse(readFileSync(p, \"utf-8\")); } catch (err) { logAndSwallow(\"ctx_start\", \"read ctx-start json\", err); return; }\n const now = Date.now();\n for (const key of Object.keys(data)) data[key] = now;\n writeFileSync(p, JSON.stringify(data), \"utf-8\");\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAQA,SAAS,YAAAA,iBAAgB;;;ACLzB;AACA;AACA;AANA,SAAS,gBAAgB;AACzB,SAAS,eAAe,YAAY,iBAAiB;AACrD,SAAS,YAAY;AAMrB,IAAM,MAAM;AAIZ,IAAM,iBAAiB;AAGvB,IAAM,kBAAkB;AAOjB,IAAM,aAAN,MAA2C;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACT,QAAQ;AAAA;AAAA,EAGhB;AAAA;AAAA,EAGQ,4BAA4B;AAAA,EAEpC,YAAY,aAAqB,iBAAyB,YAAoB;AAC5E,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SA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,CAAC,YAAoB;AACnB,cAAI;AAAE,mBAAO,IAAI,QAAQ,wBAAwB,IAAI,KAAK;AAAA,UAAM,SAAS,KAAK;AAAE,0BAAcD,MAAK,2BAA2B,GAAG;AAAG,mBAAO;AAAA,UAAM;AAAA,QACnJ;AAAA,MACF;AACA,MAAC,UAA2F,sBAAsB;AAClH,cAAQ,QAAQ,yDAAkD;AAAA,IACpE;AAAA,EACF;AAEA,MAAI,gBAAgB,WAAW;AAC7B,QAAI,oBAAmC;AACvC,IAAC,UAAkG,aAAa,CAAC,OAAO,QAAQ,WAAW;AACzI,YAAM,YAAY,SAAS,KAAK,MAAM,MAAM;AAC5C,YAAM,MAAM,kBAAa,SAAS,KAAK,KAAK,GAAG,UAAU,IAAI,WAAW,MAAM,OAAO,EAAE;AACvF,cAAQ,QAAQ,GAAG;AACnB,UAAI,UAAU,qBAAqB,WAAW,OAAO,GAAG;AACtD,4BAAoB;AACpB,eAAO,4BAA+B,EAAE,KAAK,CAAC,EAAE,iBAAiB,MAAM,iBAAiB,KAAK,GAAG,CAAC,EAAE,MAAM,SAAO,cAAcA,MAAK,6BAA6B,GAAG,CAAC;AAAA,MACtK;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAMA,eAAsB,iBAAiB,KAAoC;AACzE,UAAQ,QAAQ,mCAA4B;AAC5C,QAAM,eAAe,GAAG;AACxB,MAAI,IAAI,gBAAgB,IAAI,WAAW;AACrC,IAAC,IAAI,aAA+C,YAAY,IAAI;AAAA,EACtE;AACA,MAAI,IAAI,YAAY,IAAI,WAAW;AACjC,IAAC,IAAI,SAAsD,YAAY,IAAI;AAAA,EAC7E;AACA,UAAQ,QAAQ,0BAAqB;AACrC,SAAO;AACT;",
6
+ "names": ["execSync", "writeFileSync", "join", "TAG", "execSync"]
7
+ }
@@ -0,0 +1,83 @@
1
+ import { createRequire as __bundleCreateRequire } from 'node:module'; import { fileURLToPath as __bundleFileURLToPath } from 'node:url'; import { dirname as __bundleDirname } from 'node:path'; const require = __bundleCreateRequire(import.meta.url); const __chunk_filename = __bundleFileURLToPath(import.meta.url); const __chunk_dirname = __bundleDirname(__chunk_filename);
2
+ import {
3
+ init_log_and_swallow,
4
+ logAndSwallow
5
+ } from "./chunk-FMWKEPM7.js";
6
+ import {
7
+ abtarsHome,
8
+ init_paths
9
+ } from "./chunk-X76UX47U.js";
10
+
11
+ // src/components/skill-stats.ts
12
+ init_paths();
13
+ init_log_and_swallow();
14
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ var TAG = "skill-stats";
17
+ var stats = /* @__PURE__ */ new Map();
18
+ var dirty = false;
19
+ function statsPath() {
20
+ return join(abtarsHome(), "skills", ".stats.json");
21
+ }
22
+ function init() {
23
+ try {
24
+ const p = statsPath();
25
+ if (!existsSync(p)) return;
26
+ const data = JSON.parse(readFileSync(p, "utf-8"));
27
+ for (const [k, v] of Object.entries(data)) stats.set(k, v);
28
+ } catch (err) {
29
+ logAndSwallow(TAG, "init", err);
30
+ }
31
+ }
32
+ function bumpRead(name) {
33
+ const existing = stats.get(name);
34
+ const now = (/* @__PURE__ */ new Date()).toISOString();
35
+ if (existing) {
36
+ existing.reads++;
37
+ existing.lastRead = now;
38
+ } else {
39
+ stats.set(name, { reads: 1, lastRead: now });
40
+ }
41
+ dirty = true;
42
+ }
43
+ function setProvenance(name, createdBy) {
44
+ const existing = stats.get(name);
45
+ const now = (/* @__PURE__ */ new Date()).toISOString();
46
+ if (existing) {
47
+ existing.createdAt = now;
48
+ existing.createdBy = createdBy;
49
+ } else {
50
+ stats.set(name, { reads: 0, lastRead: now, createdAt: now, createdBy });
51
+ }
52
+ dirty = true;
53
+ }
54
+ function flush() {
55
+ if (!dirty) return;
56
+ try {
57
+ const dir = join(abtarsHome(), "skills");
58
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
59
+ const obj = {};
60
+ for (const [k, v] of stats) obj[k] = v;
61
+ writeFileSync(statsPath(), JSON.stringify(obj, null, 2) + "\n", "utf-8");
62
+ dirty = false;
63
+ } catch (err) {
64
+ logAndSwallow(TAG, "flush", err);
65
+ }
66
+ }
67
+ function _getStats() {
68
+ return stats;
69
+ }
70
+ function _reset() {
71
+ stats.clear();
72
+ dirty = false;
73
+ }
74
+
75
+ export {
76
+ init,
77
+ bumpRead,
78
+ setProvenance,
79
+ flush,
80
+ _getStats,
81
+ _reset
82
+ };
83
+ //# sourceMappingURL=chunk-AR6GO6YC.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/skill-stats.ts"],
4
+ "sourcesContent": ["/**\n * skill-stats.ts \u2014 in-memory skill usage tracking with debounced disk flush (#613).\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { abtarsHome } from \"../paths.js\";\nimport { logAndSwallow } from \"./log-and-swallow.js\";\n\nconst TAG = \"skill-stats\";\n\nexport interface SkillStat {\n reads: number;\n lastRead: string;\n createdAt?: string;\n createdBy?: string;\n}\n\nconst stats = new Map<string, SkillStat>();\nlet dirty = false;\n\nfunction statsPath(): string { return join(abtarsHome(), \"skills\", \".stats.json\"); }\n\nexport function init(): void {\n try {\n const p = statsPath();\n if (!existsSync(p)) return;\n const data = JSON.parse(readFileSync(p, \"utf-8\")) as Record<string, SkillStat>;\n for (const [k, v] of Object.entries(data)) stats.set(k, v);\n } catch (err) { logAndSwallow(TAG, \"init\", err); }\n}\n\nexport function bumpRead(name: string): void {\n const existing = stats.get(name);\n const now = new Date().toISOString();\n if (existing) {\n existing.reads++;\n existing.lastRead = now;\n } else {\n stats.set(name, { reads: 1, lastRead: now });\n }\n dirty = true;\n}\n\nexport function setProvenance(name: string, createdBy: string): void {\n const existing = stats.get(name);\n const now = new Date().toISOString();\n if (existing) {\n existing.createdAt = now;\n existing.createdBy = createdBy;\n } else {\n stats.set(name, { reads: 0, lastRead: now, createdAt: now, createdBy });\n }\n dirty = true;\n}\n\nexport function flush(): void {\n if (!dirty) return;\n try {\n const dir = join(abtarsHome(), \"skills\");\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const obj: Record<string, SkillStat> = {};\n for (const [k, v] of stats) obj[k] = v;\n writeFileSync(statsPath(), JSON.stringify(obj, null, 2) + \"\\n\", \"utf-8\");\n dirty = false;\n } catch (err) { logAndSwallow(TAG, \"flush\", err); }\n}\n\n/** Exposed for testing. */\nexport function _getStats(): Map<string, SkillStat> { return stats; }\nexport function _reset(): void { stats.clear(); dirty = false; }\n"],
5
+ "mappings": ";;;;;;;;;;;AAMA;AACA;AAHA,SAAS,YAAY,cAAc,eAAe,iBAAiB;AACnE,SAAS,YAAY;AAIrB,IAAM,MAAM;AASZ,IAAM,QAAQ,oBAAI,IAAuB;AACzC,IAAI,QAAQ;AAEZ,SAAS,YAAoB;AAAE,SAAO,KAAK,WAAW,GAAG,UAAU,aAAa;AAAG;AAE5E,SAAS,OAAa;AAC3B,MAAI;AACF,UAAM,IAAI,UAAU;AACpB,QAAI,CAAC,WAAW,CAAC,EAAG;AACpB,UAAM,OAAO,KAAK,MAAM,aAAa,GAAG,OAAO,CAAC;AAChD,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAI,EAAG,OAAM,IAAI,GAAG,CAAC;AAAA,EAC3D,SAAS,KAAK;AAAE,kBAAc,KAAK,QAAQ,GAAG;AAAA,EAAG;AACnD;AAEO,SAAS,SAAS,MAAoB;AAC3C,QAAM,WAAW,MAAM,IAAI,IAAI;AAC/B,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AACnC,MAAI,UAAU;AACZ,aAAS;AACT,aAAS,WAAW;AAAA,EACtB,OAAO;AACL,UAAM,IAAI,MAAM,EAAE,OAAO,GAAG,UAAU,IAAI,CAAC;AAAA,EAC7C;AACA,UAAQ;AACV;AAEO,SAAS,cAAc,MAAc,WAAyB;AACnE,QAAM,WAAW,MAAM,IAAI,IAAI;AAC/B,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AACnC,MAAI,UAAU;AACZ,aAAS,YAAY;AACrB,aAAS,YAAY;AAAA,EACvB,OAAO;AACL,UAAM,IAAI,MAAM,EAAE,OAAO,GAAG,UAAU,KAAK,WAAW,KAAK,UAAU,CAAC;AAAA,EACxE;AACA,UAAQ;AACV;AAEO,SAAS,QAAc;AAC5B,MAAI,CAAC,MAAO;AACZ,MAAI;AACF,UAAM,MAAM,KAAK,WAAW,GAAG,QAAQ;AACvC,QAAI,CAAC,WAAW,GAAG,EAAG,WAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AACxD,UAAM,MAAiC,CAAC;AACxC,eAAW,CAAC,GAAG,CAAC,KAAK,MAAO,KAAI,CAAC,IAAI;AACrC,kBAAc,UAAU,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,MAAM,OAAO;AACvE,YAAQ;AAAA,EACV,SAAS,KAAK;AAAE,kBAAc,KAAK,SAAS,GAAG;AAAA,EAAG;AACpD;AAGO,SAAS,YAAoC;AAAE,SAAO;AAAO;AAC7D,SAAS,SAAe;AAAE,QAAM,MAAM;AAAG,UAAQ;AAAO;",
6
+ "names": []
7
+ }
@@ -0,0 +1,54 @@
1
+ import { createRequire as __bundleCreateRequire } from 'node:module'; import { fileURLToPath as __bundleFileURLToPath } from 'node:url'; import { dirname as __bundleDirname } from 'node:path'; const require = __bundleCreateRequire(import.meta.url); const __chunk_filename = __bundleFileURLToPath(import.meta.url); const __chunk_dirname = __bundleDirname(__chunk_filename);
2
+ import {
3
+ init_log_and_swallow,
4
+ logAndSwallow
5
+ } from "./chunk-FMWKEPM7.js";
6
+ import {
7
+ getEnv,
8
+ init_env_schema
9
+ } from "./chunk-JCJS4ZIB.js";
10
+ import {
11
+ init_logger,
12
+ logError,
13
+ logWarn
14
+ } from "./chunk-BUUVFUPO.js";
15
+
16
+ // src/components/main-chat.ts
17
+ init_env_schema();
18
+ init_logger();
19
+ async function sendToMainChat(adapters, text, opts) {
20
+ const chatId = getEnv().mainChatId;
21
+ if (!chatId) {
22
+ logWarn("main-chat", "no MAIN_CHAT_ID, skipping");
23
+ return { ok: false, reason: "no-chat-id" };
24
+ }
25
+ const provider = getEnv().mainChatProvider;
26
+ const adapter = provider === "discord" ? adapters.discord : adapters.telegram;
27
+ if (!adapter) {
28
+ logWarn("main-chat", `${provider} adapter not running, skipping`);
29
+ return { ok: false, reason: "adapter-missing" };
30
+ }
31
+ try {
32
+ await adapter.sendMessage(chatId, text, opts);
33
+ return { ok: true };
34
+ } catch (err) {
35
+ logError("main-chat", `send failed: ${err}`);
36
+ return { ok: false, reason: "send-failed" };
37
+ }
38
+ }
39
+
40
+ // src/components/notification.ts
41
+ init_log_and_swallow();
42
+ var TAG = "notification";
43
+ function sendNotification(ctx, msg) {
44
+ sendToMainChat(
45
+ { telegram: ctx.telegramAdapter, discord: ctx.discordAdapter },
46
+ msg
47
+ ).catch((err) => logAndSwallow(TAG, "sendToMainChat", err));
48
+ }
49
+
50
+ export {
51
+ sendToMainChat,
52
+ sendNotification
53
+ };
54
+ //# sourceMappingURL=chunk-AZJIODTQ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/main-chat.ts", "../src/components/notification.ts"],
4
+ "sourcesContent": ["/**\n * main-chat.ts \u2014 Route operator messages to the correct platform.\n * Uses MAIN_CHAT_PROVIDER to decide telegram vs discord.\n */\n\nimport { getEnv } from \"./env-schema.js\";\nimport { logWarn, logError } from \"./logger.js\";\n\nexport interface SendOpts {\n threadId?: number;\n}\n\nexport interface SendResult {\n ok: boolean;\n reason?: \"no-chat-id\" | \"adapter-missing\" | \"send-failed\";\n}\n\nexport type ChatAdapter = {\n sendMessage(chatId: string, text: string, opts?: any): Promise<unknown>;\n};\n\nexport async function sendToMainChat(\n adapters: { telegram?: ChatAdapter | null; discord?: ChatAdapter | null },\n text: string,\n opts?: SendOpts,\n): Promise<SendResult> {\n const chatId = getEnv().mainChatId;\n if (!chatId) {\n logWarn(\"main-chat\", \"no MAIN_CHAT_ID, skipping\");\n return { ok: false, reason: \"no-chat-id\" };\n }\n const provider = getEnv().mainChatProvider;\n const adapter = provider === \"discord\" ? adapters.discord : adapters.telegram;\n if (!adapter) {\n logWarn(\"main-chat\", `${provider} adapter not running, skipping`);\n return { ok: false, reason: \"adapter-missing\" };\n }\n try {\n await adapter.sendMessage(chatId, text, opts);\n return { ok: true };\n } catch (err) {\n logError(\"main-chat\", `send failed: ${err}`);\n return { ok: false, reason: \"send-failed\" };\n }\n}\n", "/**\n * sendNotification \u2014 send a notification to the operator's main channel.\n * Routes via MAIN_CHAT_PROVIDER. Fire-and-forget.\n */\n\nimport type { BootCtx } from \"../boot/context.js\";\nimport { sendToMainChat } from \"./main-chat.js\";\nimport { logAndSwallow } from \"./log-and-swallow.js\";\n\nconst TAG = \"notification\";\n\nexport function sendNotification(ctx: BootCtx, msg: string): void {\n sendToMainChat(\n { telegram: ctx.telegramAdapter, discord: ctx.discordAdapter },\n msg,\n ).catch(err => logAndSwallow(TAG, \"sendToMainChat\", err));\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;AAKA;AACA;AAeA,eAAsB,eACpB,UACA,MACA,MACqB;AACrB,QAAM,SAAS,OAAO,EAAE;AACxB,MAAI,CAAC,QAAQ;AACX,YAAQ,aAAa,2BAA2B;AAChD,WAAO,EAAE,IAAI,OAAO,QAAQ,aAAa;AAAA,EAC3C;AACA,QAAM,WAAW,OAAO,EAAE;AAC1B,QAAM,UAAU,aAAa,YAAY,SAAS,UAAU,SAAS;AACrE,MAAI,CAAC,SAAS;AACZ,YAAQ,aAAa,GAAG,QAAQ,gCAAgC;AAChE,WAAO,EAAE,IAAI,OAAO,QAAQ,kBAAkB;AAAA,EAChD;AACA,MAAI;AACF,UAAM,QAAQ,YAAY,QAAQ,MAAM,IAAI;AAC5C,WAAO,EAAE,IAAI,KAAK;AAAA,EACpB,SAAS,KAAK;AACZ,aAAS,aAAa,gBAAgB,GAAG,EAAE;AAC3C,WAAO,EAAE,IAAI,OAAO,QAAQ,cAAc;AAAA,EAC5C;AACF;;;ACrCA;AAEA,IAAM,MAAM;AAEL,SAAS,iBAAiB,KAAc,KAAmB;AAChE;AAAA,IACE,EAAE,UAAU,IAAI,iBAAiB,SAAS,IAAI,eAAe;AAAA,IAC7D;AAAA,EACF,EAAE,MAAM,SAAO,cAAc,KAAK,kBAAkB,GAAG,CAAC;AAC1D;",
6
+ "names": []
7
+ }