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,126 @@
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
+ buildUsersBlock,
4
+ loadUsers
5
+ } from "./chunk-GST5T3WZ.js";
6
+ import {
7
+ init_log_and_swallow,
8
+ logAndSwallow
9
+ } from "./chunk-FMWKEPM7.js";
10
+ import {
11
+ getEnv,
12
+ init_env_schema
13
+ } from "./chunk-JCJS4ZIB.js";
14
+ import {
15
+ init_logger,
16
+ logDebug,
17
+ logInfo,
18
+ logWarn
19
+ } from "./chunk-BUUVFUPO.js";
20
+ import {
21
+ abtarsHome,
22
+ init_paths
23
+ } from "./chunk-X76UX47U.js";
24
+
25
+ // src/components/soul-loader.ts
26
+ init_log_and_swallow();
27
+ init_env_schema();
28
+ init_logger();
29
+ init_paths();
30
+ import { existsSync, readFileSync } from "node:fs";
31
+ import { join } from "node:path";
32
+ var TAG = "soul-loader";
33
+ var HOST_CORE_DIR = join(abtarsHome(), "core");
34
+ function readOr(path) {
35
+ try {
36
+ return existsSync(path) ? readFileSync(path, "utf-8").trim() : "";
37
+ } catch {
38
+ return "";
39
+ }
40
+ }
41
+ function buildModelInstructions() {
42
+ const lines = [];
43
+ if (getEnv().primingModelTopics) {
44
+ lines.push("End each response with [TOPICS: kw1, kw2, kw3] \u2014 your top 3 topics from this exchange. Keep them English, lowercase, concise.");
45
+ }
46
+ return lines.length > 0 ? `# Model Instructions
47
+
48
+ ${lines.join("\n")}` : "";
49
+ }
50
+ function loadSoulBundle(memory) {
51
+ const parts = [];
52
+ let bundle = null;
53
+ try {
54
+ bundle = memory?.getSessionBundle() ?? null;
55
+ } catch (err) {
56
+ logAndSwallow("soul_loader", "op", err);
57
+ }
58
+ const soul = bundle?.soul || readOr(join(HOST_CORE_DIR, "SOUL.md"));
59
+ const profile = bundle?.profile || readOr(join(HOST_CORE_DIR, "user_profile.md"));
60
+ const notes = bundle?.notes || readOr(join(HOST_CORE_DIR, "agent_notes.md"));
61
+ const memoryTools = bundle?.memoryTools || readOr(join(HOST_CORE_DIR, "TOOLS.md"));
62
+ const coreFacts = bundle?.coreFacts || readOr(join(HOST_CORE_DIR, "core_facts.md"));
63
+ if (soul) parts.push(soul);
64
+ if (memoryTools) parts.push(memoryTools);
65
+ if (profile) parts.push(profile);
66
+ if (notes) parts.push(notes);
67
+ if (coreFacts) parts.push(coreFacts);
68
+ const skillsCatalog = readOr(join(HOST_CORE_DIR, "skills_catalog.md"));
69
+ if (skillsCatalog) parts.push(skillsCatalog);
70
+ const modelInstructions = buildModelInstructions();
71
+ if (modelInstructions) parts.push(modelInstructions);
72
+ try {
73
+ const arcs = memory?.getEmotionalArcs() ?? [];
74
+ if (arcs.length > 0) {
75
+ const ARC_LABELS = { "\u2191": "user sentiment improving", "\u2193": "user sentiment worsening \u2014 be careful", "\u2195": "volatile \u2014 user feelings fluctuate", "\u2192": "stable" };
76
+ const lines = arcs.map((a) => `- ${a.topic}: ${a.arc} (${ARC_LABELS[a.arc] ?? "unknown"})`);
77
+ parts.push(`[EMOTIONAL CONTEXT]
78
+ ${lines.join("\n")}`);
79
+ }
80
+ } catch (err) {
81
+ logAndSwallow("soul_loader", "op", err);
82
+ }
83
+ try {
84
+ const registry = loadUsers();
85
+ if (registry.users.length > 0) parts.push(buildUsersBlock(registry));
86
+ } catch (err) {
87
+ logAndSwallow("soul_loader", "op", err);
88
+ }
89
+ const now = /* @__PURE__ */ new Date();
90
+ const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
91
+ parts.push(`[CURRENT TIME] ${now.toLocaleDateString("en-GB")} ${days[now.getDay()]}, ${now.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}`);
92
+ if (parts.length === 0) {
93
+ logWarn(TAG, "No session bundle files found");
94
+ return null;
95
+ }
96
+ logInfo(TAG, `Session bundle: ${parts.length} parts (abmind: ${bundle ? "API" : "fallback"})`);
97
+ logDebug(TAG, `Bundle parts: soul=${!!soul} profile=${!!profile} notes=${!!notes} memTools=${!!memoryTools} coreFacts=${!!coreFacts} skills=${!!skillsCatalog}`);
98
+ return parts.join("\n\n---\n\n");
99
+ }
100
+ function loadMinimalSoul(memory) {
101
+ const parts = [];
102
+ let bundle = null;
103
+ try {
104
+ bundle = memory?.getSessionBundle() ?? null;
105
+ } catch (err) {
106
+ logAndSwallow("soul_loader", "op", err);
107
+ }
108
+ const notes = bundle?.notes || readOr(join(HOST_CORE_DIR, "agent_notes.md"));
109
+ const memoryTools = bundle?.memoryTools || readOr(join(HOST_CORE_DIR, "TOOLS.md"));
110
+ if (notes) parts.push(notes);
111
+ if (memoryTools) parts.push(memoryTools);
112
+ const skillsCatalog = readOr(join(HOST_CORE_DIR, "skills_catalog.md"));
113
+ if (skillsCatalog) parts.push(skillsCatalog);
114
+ const now = /* @__PURE__ */ new Date();
115
+ const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
116
+ parts.push(`[CURRENT TIME] ${now.toLocaleDateString("en-GB")} ${days[now.getDay()]}, ${now.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}`);
117
+ if (parts.length === 0) return null;
118
+ logInfo(TAG, `Minimal soul (Code): ${parts.length} parts`);
119
+ return parts.join("\n\n---\n\n");
120
+ }
121
+
122
+ export {
123
+ loadSoulBundle,
124
+ loadMinimalSoul
125
+ };
126
+ //# sourceMappingURL=chunk-UCQ2WC3B.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/soul-loader.ts"],
4
+ "sourcesContent": ["import { logAndSwallow } from \"./log-and-swallow.js\";\nimport { getEnv } from \"./env-schema.js\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { logInfo, logDebug, logWarn } from \"./logger.js\";\nimport { abtarsHome } from \"../paths.js\";\nimport { loadUsers, buildUsersBlock } from \"./user-registry.js\";\nimport type { MemoryManager } from \"abmind\";\n\nconst TAG = \"soul-loader\";\nconst HOST_CORE_DIR = join(abtarsHome(), \"core\");\n\n/** Read a single file, return empty string on failure. */\nfunction readOr(path: string): string {\n try { return existsSync(path) ? readFileSync(path, \"utf-8\").trim() : \"\"; } catch { return \"\"; }\n}\n\n/** Build env-gated model behavior directives. Generated at session start. */\nfunction buildModelInstructions(): string {\n const lines: string[] = [];\n if (getEnv().primingModelTopics) {\n lines.push(\"End each response with [TOPICS: kw1, kw2, kw3] \u2014 your top 3 topics from this exchange. Keep them English, lowercase, concise.\");\n }\n return lines.length > 0 ? `# Model Instructions\\n\\n${lines.join(\"\\n\")}` : \"\";\n}\n\n/**\n * Build the session injection bundle: abmind 4 + host 2.\n *\n * abmind files via memory.getSessionBundle() (SOUL, profile, notes, memory-tools).\n * Transition fallback: if memory unavailable or file missing, reads from ~/.abtars/core/.\n * Host files (core_facts.md, skills_catalog.md) always from ~/.abtars/core/.\n * Appends [USERS] block.\n */\nexport function loadSoulBundle(memory?: MemoryManager | null): string | null {\n const parts: string[] = [];\n\n // abmind 4 \u2014 prefer getSessionBundle(), fall back to host core dir\n let bundle: { soul: string; profile: string; notes: string; memoryTools: string; coreFacts: string } | null = null;\n try { bundle = memory?.getSessionBundle() ?? null; } catch (err) { logAndSwallow(\"soul_loader\", \"op\", err); }\n\n const soul = bundle?.soul || readOr(join(HOST_CORE_DIR, \"SOUL.md\"));\n const profile = bundle?.profile || readOr(join(HOST_CORE_DIR, \"user_profile.md\"));\n const notes = bundle?.notes || readOr(join(HOST_CORE_DIR, \"agent_notes.md\"));\n const memoryTools = bundle?.memoryTools || readOr(join(HOST_CORE_DIR, \"TOOLS.md\"));\n const coreFacts = bundle?.coreFacts || readOr(join(HOST_CORE_DIR, \"core_facts.md\"));\n\n if (soul) parts.push(soul);\n if (memoryTools) parts.push(memoryTools);\n if (profile) parts.push(profile);\n if (notes) parts.push(notes);\n if (coreFacts) parts.push(coreFacts);\n\n // Host 2 \u2014 skills_catalog stays in ~/.abtars/core/ (generated by hotskills watcher)\n const skillsCatalog = readOr(join(HOST_CORE_DIR, \"skills_catalog.md\"));\n if (skillsCatalog) parts.push(skillsCatalog);\n\n // Host 3: model-instructions \u2014 env-gated dynamic directives\n const modelInstructions = buildModelInstructions();\n if (modelInstructions) parts.push(modelInstructions);\n\n // [EMOTIONAL CONTEXT] \u2014 topic arcs for tone awareness\n try {\n const arcs = memory?.getEmotionalArcs() ?? [];\n if (arcs.length > 0) {\n const ARC_LABELS: Record<string, string> = { \"\u2191\": \"user sentiment improving\", \"\u2193\": \"user sentiment worsening \u2014 be careful\", \"\u2195\": \"volatile \u2014 user feelings fluctuate\", \"\u2192\": \"stable\" };\n const lines = arcs.map(a => `- ${a.topic}: ${a.arc} (${ARC_LABELS[a.arc] ?? \"unknown\"})`);\n parts.push(`[EMOTIONAL CONTEXT]\\n${lines.join(\"\\n\")}`);\n }\n } catch (err) { logAndSwallow(\"soul_loader\", \"op\", err); }\n\n // [USERS] block\n try {\n const registry = loadUsers();\n if (registry.users.length > 0) parts.push(buildUsersBlock(registry));\n } catch (err) { logAndSwallow(\"soul_loader\", \"op\", err); }\n\n // Current date/time \u2014 prevents model from hallucinating temporal context\n const now = new Date();\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n parts.push(`[CURRENT TIME] ${now.toLocaleDateString(\"en-GB\")} ${days[now.getDay()]}, ${now.toLocaleTimeString(\"en-GB\", { hour: \"2-digit\", minute: \"2-digit\" })}`);\n\n if (parts.length === 0) {\n logWarn(TAG, \"No session bundle files found\");\n return null;\n }\n\n logInfo(TAG, `Session bundle: ${parts.length} parts (abmind: ${bundle ? \"API\" : \"fallback\"})`);\n logDebug(TAG, `Bundle parts: soul=${!!soul} profile=${!!profile} notes=${!!notes} memTools=${!!memoryTools} coreFacts=${!!coreFacts} skills=${!!skillsCatalog}`);\n return parts.join(\"\\n\\n---\\n\\n\");\n}\n\n/**\n * Minimal soul for Code sessions (#658): agent_notes + memory-tools + skills + time.\n * No personality, no user_profile, no core_facts, no emotional context.\n */\nexport function loadMinimalSoul(memory?: MemoryManager | null): string | null {\n const parts: string[] = [];\n\n let bundle: { notes: string; memoryTools: string } | null = null;\n try { bundle = memory?.getSessionBundle() ?? null; } catch (err) { logAndSwallow(\"soul_loader\", \"op\", err); }\n\n const notes = bundle?.notes || readOr(join(HOST_CORE_DIR, \"agent_notes.md\"));\n const memoryTools = bundle?.memoryTools || readOr(join(HOST_CORE_DIR, \"TOOLS.md\"));\n\n if (notes) parts.push(notes);\n if (memoryTools) parts.push(memoryTools);\n\n const skillsCatalog = readOr(join(HOST_CORE_DIR, \"skills_catalog.md\"));\n if (skillsCatalog) parts.push(skillsCatalog);\n\n const now = new Date();\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n parts.push(`[CURRENT TIME] ${now.toLocaleDateString(\"en-GB\")} ${days[now.getDay()]}, ${now.toLocaleTimeString(\"en-GB\", { hour: \"2-digit\", minute: \"2-digit\" })}`);\n\n if (parts.length === 0) return null;\n logInfo(TAG, `Minimal soul (Code): ${parts.length} parts`);\n return parts.join(\"\\n\\n---\\n\\n\");\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAGA;AACA;AAHA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AAMrB,IAAM,MAAM;AACZ,IAAM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ACjC;AAMO,SAAS,gBAAgB,QAA8C;AAC5E,QAAM,QAAkB,CAAC;AAEzB,MAAI,SAAwD;AAC5D,MAAI;AAAE,aAAS,QAAQ,iBAAiB,KAAK;AAAA,EAAM,SAAS,KAAK;AAAE,kBAAc,eAAe,MAAM,GAAG;AAAA,EAAG;AAE5G,QAAM,QAAQ,QAAQ,SAAS,OAAO,KAAK,eAAe,gBAAgB,CAAC;AAC3E,QAAM,cAAc,QAAQ,eAAe,OAAO,KAAK,eAAe,UAAU,CAAC;AAEjF,MAAI,MAAO,OAAM,KAAK,KAAK;AAC3B,MAAI,YAAa,OAAM,KAAK,WAAW;AAEvC,QAAM,gBAAgB,OAAO,KAAK,eAAe,mBAAmB,CAAC;AACrE,MAAI,cAAe,OAAM,KAAK,aAAa;AAE3C,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,OAAO,CAAC,UAAU,UAAU,WAAW,aAAa,YAAY,UAAU,UAAU;AAC1F,QAAM,KAAK,kBAAkB,IAAI,mBAAmB,OAAO,CAAC,IAAI,KAAK,IAAI,OAAO,CAAC,CAAC,KAAK,IAAI,mBAAmB,SAAS,EAAE,MAAM,WAAW,QAAQ,UAAU,CAAC,CAAC,EAAE;AAEhK,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,UAAQ,KAAK,wBAAwB,MAAM,MAAM,QAAQ;AACzD,SAAO,MAAM,KAAK,aAAa;AACjC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,214 @@
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
+ addCompletion
4
+ } from "./chunk-LSPKJQCI.js";
5
+ import {
6
+ getEnv,
7
+ init_env_schema
8
+ } from "./chunk-JCJS4ZIB.js";
9
+ import {
10
+ init_logger,
11
+ logInfo,
12
+ logWarn
13
+ } from "./chunk-BUUVFUPO.js";
14
+
15
+ // src/components/transport/delegation-tools.ts
16
+ init_logger();
17
+ init_env_schema();
18
+ var TAG = "delegation";
19
+ var MAX_BACKGROUND = parseInt(process.env["MAX_BACKGROUND_SESSIONS"] ?? "3", 10);
20
+ var _runtime = null;
21
+ var _sessionManager = null;
22
+ function setDelegationDeps(runtime, sessionManager) {
23
+ _runtime = runtime;
24
+ _sessionManager = sessionManager;
25
+ }
26
+ var activeBackgrounds = /* @__PURE__ */ new Map();
27
+ function getActiveBackgrounds() {
28
+ return activeBackgrounds;
29
+ }
30
+ var TYPE_MAP = {
31
+ code: { sessionType: "C", agent: "coding" },
32
+ browse: { sessionType: "B", agent: "browsie" },
33
+ task: { sessionType: "T", agent: "task" }
34
+ };
35
+ var spawnSessionTool = {
36
+ name: "spawn_session",
37
+ description: "Spawn a background session that works independently. Returns immediately with a session ID. Use check_session to get results later.",
38
+ parameters: {
39
+ type: "object",
40
+ properties: {
41
+ type: { type: "string", enum: ["code", "browse", "task"], description: "Session type" },
42
+ goal: { type: "string", description: "What the sub-agent should accomplish" },
43
+ context: { type: "string", description: "Optional context/instructions" }
44
+ },
45
+ required: ["type", "goal"]
46
+ },
47
+ async execute(args) {
48
+ if (!_runtime || !_sessionManager) return JSON.stringify({ error: "Delegation not initialized" });
49
+ const typeInfo = TYPE_MAP[args.type ?? "task"];
50
+ if (!typeInfo) return JSON.stringify({ error: `Unknown type: ${args.type}. Use: code, browse, task` });
51
+ const running = [...activeBackgrounds.values()].filter((e) => e.status === "running");
52
+ if (running.length >= MAX_BACKGROUND) {
53
+ return JSON.stringify({ error: `Max ${MAX_BACKGROUND} concurrent background sessions. Wait for one to finish or terminate it.` });
54
+ }
55
+ const session = _sessionManager.createSubSession("master", "telegram", typeInfo.sessionType);
56
+ if (typeof session === "string") return JSON.stringify({ error: session });
57
+ const goal = args.goal ?? "No goal specified";
58
+ const prompt = args.context ? `${args.context}
59
+
60
+ Task: ${goal}` : goal;
61
+ const { taskId } = await _runtime.spawn(typeInfo.agent, prompt, {
62
+ onComplete: (id, result) => {
63
+ const entry = activeBackgrounds.get(id);
64
+ if (entry) {
65
+ entry.status = "done";
66
+ entry.result = result.slice(0, 4e3);
67
+ addCompletion({
68
+ sessionId: entry.sessionId,
69
+ motherId: session.motherId ?? "",
70
+ goal: entry.goal,
71
+ status: "done",
72
+ result: entry.result,
73
+ elapsedMs: Date.now() - entry.startedAt,
74
+ inputTokens: entry.inputTokens,
75
+ outputTokens: entry.outputTokens
76
+ });
77
+ logInfo(TAG, `Background ${id} completed (${Date.now() - entry.startedAt}ms)`);
78
+ }
79
+ },
80
+ onError: (id, err) => {
81
+ const entry = activeBackgrounds.get(id);
82
+ if (entry) {
83
+ entry.status = "failed";
84
+ entry.result = err.message.slice(0, 1e3);
85
+ addCompletion({
86
+ sessionId: entry.sessionId,
87
+ motherId: session.motherId ?? "",
88
+ goal: entry.goal,
89
+ status: "failed",
90
+ result: entry.result,
91
+ elapsedMs: Date.now() - entry.startedAt,
92
+ inputTokens: entry.inputTokens,
93
+ outputTokens: entry.outputTokens
94
+ });
95
+ logWarn(TAG, `Background ${id} failed: ${err.message}`);
96
+ }
97
+ }
98
+ });
99
+ activeBackgrounds.set(taskId, {
100
+ taskId,
101
+ sessionId: session.id,
102
+ goal,
103
+ startedAt: Date.now(),
104
+ status: "running",
105
+ inputTokens: 0,
106
+ outputTokens: 0
107
+ });
108
+ logInfo(TAG, `Spawned background: taskId=${taskId}, session=${session.id}, goal="${goal.slice(0, 60)}"`);
109
+ return JSON.stringify({ session_id: session.id, task_id: taskId, status: "running" });
110
+ }
111
+ };
112
+ var checkSessionTool = {
113
+ name: "check_session",
114
+ description: "Check the status of a background session. Returns status and result if completed.",
115
+ parameters: {
116
+ type: "object",
117
+ properties: {
118
+ task_id: { type: "string", description: "Task ID returned by spawn_session" }
119
+ },
120
+ required: ["task_id"]
121
+ },
122
+ async execute(args) {
123
+ const entry = activeBackgrounds.get(args.task_id ?? "");
124
+ if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });
125
+ const elapsed = Math.round((Date.now() - entry.startedAt) / 1e3);
126
+ return JSON.stringify({
127
+ task_id: entry.taskId,
128
+ session_id: entry.sessionId,
129
+ goal: entry.goal,
130
+ status: entry.status,
131
+ elapsed_seconds: elapsed,
132
+ result: entry.result ?? null
133
+ });
134
+ }
135
+ };
136
+ var terminateSessionTool = {
137
+ name: "terminate_session",
138
+ description: "Terminate a running background session. It finishes its current operation then stops.",
139
+ parameters: {
140
+ type: "object",
141
+ properties: {
142
+ task_id: { type: "string", description: "Task ID to terminate" }
143
+ },
144
+ required: ["task_id"]
145
+ },
146
+ async execute(args) {
147
+ if (!_runtime) return JSON.stringify({ error: "Delegation not initialized" });
148
+ const entry = activeBackgrounds.get(args.task_id ?? "");
149
+ if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });
150
+ if (entry.status !== "running") return JSON.stringify({ error: `Session already ${entry.status}` });
151
+ const interrupted = _runtime.interruptSpawn(entry.taskId);
152
+ entry.status = "terminated";
153
+ entry.result = "(terminated by user)";
154
+ if (entry.sessionId && _sessionManager) {
155
+ const managed = _sessionManager.getSessionById(entry.sessionId);
156
+ if (managed) managed.paused = true;
157
+ }
158
+ addCompletion({
159
+ sessionId: entry.sessionId,
160
+ motherId: _sessionManager?.getSessionById(entry.sessionId)?.motherId ?? "",
161
+ goal: entry.goal,
162
+ status: "terminated",
163
+ result: entry.result,
164
+ elapsedMs: Date.now() - entry.startedAt,
165
+ inputTokens: entry.inputTokens,
166
+ outputTokens: entry.outputTokens
167
+ });
168
+ logInfo(TAG, `Terminated background ${entry.taskId} (interrupted=${interrupted})`);
169
+ return JSON.stringify({ task_id: entry.taskId, status: "terminated" });
170
+ }
171
+ };
172
+ var sendToSessionTool = {
173
+ name: "send_to_session",
174
+ description: "Send a follow-up instruction to a running background session. The child receives it on its next turn.",
175
+ parameters: {
176
+ type: "object",
177
+ properties: {
178
+ task_id: { type: "string", description: "Task ID of the running session" },
179
+ message: { type: "string", description: "Instruction to send" }
180
+ },
181
+ required: ["task_id", "message"]
182
+ },
183
+ async execute(args) {
184
+ const entry = activeBackgrounds.get(args.task_id ?? "");
185
+ if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });
186
+ if (entry.status !== "running") return JSON.stringify({ error: `Session is ${entry.status}, cannot send instruction` });
187
+ entry.pendingInstruction = args.message;
188
+ logInfo(TAG, `Instruction queued for ${entry.taskId}: "${(args.message ?? "").slice(0, 60)}"`);
189
+ return JSON.stringify({ delivered: true, task_id: entry.taskId });
190
+ }
191
+ };
192
+ function consumePendingInstruction(taskId) {
193
+ const entry = activeBackgrounds.get(taskId);
194
+ if (!entry?.pendingInstruction) return void 0;
195
+ const msg = entry.pendingInstruction;
196
+ entry.pendingInstruction = void 0;
197
+ return msg;
198
+ }
199
+ function getDelegationTools() {
200
+ if (!getEnv().enableAsyncDelegation) return [];
201
+ return [spawnSessionTool, checkSessionTool, terminateSessionTool, sendToSessionTool];
202
+ }
203
+
204
+ export {
205
+ setDelegationDeps,
206
+ getActiveBackgrounds,
207
+ spawnSessionTool,
208
+ checkSessionTool,
209
+ terminateSessionTool,
210
+ sendToSessionTool,
211
+ consumePendingInstruction,
212
+ getDelegationTools
213
+ };
214
+ //# sourceMappingURL=chunk-UHRP745J.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/transport/delegation-tools.ts"],
4
+ "sourcesContent": ["/**\n * delegation-tools.ts \u2014 spawn_session, check_session, terminate_session (#570).\n * Gated behind ENABLE_ASYNC_DELEGATION env flag.\n */\n\nimport type { ToolDefinition } from \"./tool-registry.js\";\nimport type { SubagentRuntime, AgentName } from \"../subagent-runtime.js\";\nimport type { SessionManager, SessionType } from \"../session-manager.js\";\nimport { addCompletion } from \"../completion-buffer.js\";\nimport { logInfo, logWarn } from \"../logger.js\";\nimport { getEnv } from \"../env-schema.js\";\n\nconst TAG = \"delegation\";\nconst MAX_BACKGROUND = parseInt(process.env[\"MAX_BACKGROUND_SESSIONS\"] ?? \"3\", 10);\n\nlet _runtime: SubagentRuntime | null = null;\nlet _sessionManager: SessionManager | null = null;\n\nexport function setDelegationDeps(runtime: SubagentRuntime, sessionManager: SessionManager): void {\n _runtime = runtime;\n _sessionManager = sessionManager;\n}\n\n// Track active background sessions: taskId \u2192 metadata\ninterface BackgroundEntry {\n taskId: string;\n sessionId: string;\n goal: string;\n startedAt: number;\n status: \"running\" | \"done\" | \"failed\" | \"terminated\" | \"timeout\";\n result?: string;\n inputTokens: number;\n outputTokens: number;\n pendingInstruction?: string;\n}\n\nconst activeBackgrounds = new Map<string, BackgroundEntry>();\n\nexport function getActiveBackgrounds(): Map<string, BackgroundEntry> {\n return activeBackgrounds;\n}\n\nconst TYPE_MAP: Record<string, { sessionType: SessionType; agent: AgentName }> = {\n code: { sessionType: \"C\", agent: \"coding\" },\n browse: { sessionType: \"B\", agent: \"browsie\" },\n task: { sessionType: \"T\", agent: \"task\" },\n};\n\nexport const spawnSessionTool: ToolDefinition = {\n name: \"spawn_session\",\n description: \"Spawn a background session that works independently. Returns immediately with a session ID. Use check_session to get results later.\",\n parameters: {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"code\", \"browse\", \"task\"], description: \"Session type\" },\n goal: { type: \"string\", description: \"What the sub-agent should accomplish\" },\n context: { type: \"string\", description: \"Optional context/instructions\" },\n },\n required: [\"type\", \"goal\"],\n },\n async execute(args) {\n if (!_runtime || !_sessionManager) return JSON.stringify({ error: \"Delegation not initialized\" });\n\n const typeInfo = TYPE_MAP[args.type ?? \"task\"];\n if (!typeInfo) return JSON.stringify({ error: `Unknown type: ${args.type}. Use: code, browse, task` });\n\n // Check cap\n const running = [...activeBackgrounds.values()].filter(e => e.status === \"running\");\n if (running.length >= MAX_BACKGROUND) {\n return JSON.stringify({ error: `Max ${MAX_BACKGROUND} concurrent background sessions. Wait for one to finish or terminate it.` });\n }\n\n // Create session via session manager\n const session = _sessionManager.createSubSession(\"master\", \"telegram\", typeInfo.sessionType);\n if (typeof session === \"string\") return JSON.stringify({ error: session });\n\n const goal = args.goal ?? \"No goal specified\";\n const prompt = args.context ? `${args.context}\\n\\nTask: ${goal}` : goal;\n\n // Spawn via SubagentRuntime (fire-and-forget)\n const { taskId } = await _runtime.spawn(typeInfo.agent, prompt, {\n onComplete: (id, result) => {\n const entry = activeBackgrounds.get(id);\n if (entry) {\n entry.status = \"done\";\n entry.result = result.slice(0, 4000);\n addCompletion({\n sessionId: entry.sessionId,\n motherId: session.motherId ?? \"\",\n goal: entry.goal,\n status: \"done\",\n result: entry.result,\n elapsedMs: Date.now() - entry.startedAt,\n inputTokens: entry.inputTokens,\n outputTokens: entry.outputTokens,\n });\n logInfo(TAG, `Background ${id} completed (${Date.now() - entry.startedAt}ms)`);\n }\n },\n onError: (id, err) => {\n const entry = activeBackgrounds.get(id);\n if (entry) {\n entry.status = \"failed\";\n entry.result = err.message.slice(0, 1000);\n addCompletion({\n sessionId: entry.sessionId,\n motherId: session.motherId ?? \"\",\n goal: entry.goal,\n status: \"failed\",\n result: entry.result,\n elapsedMs: Date.now() - entry.startedAt,\n inputTokens: entry.inputTokens,\n outputTokens: entry.outputTokens,\n });\n logWarn(TAG, `Background ${id} failed: ${err.message}`);\n }\n },\n });\n\n activeBackgrounds.set(taskId, {\n taskId,\n sessionId: session.id,\n goal,\n startedAt: Date.now(),\n status: \"running\",\n inputTokens: 0,\n outputTokens: 0,\n });\n\n logInfo(TAG, `Spawned background: taskId=${taskId}, session=${session.id}, goal=\"${goal.slice(0, 60)}\"`);\n return JSON.stringify({ session_id: session.id, task_id: taskId, status: \"running\" });\n },\n};\n\nexport const checkSessionTool: ToolDefinition = {\n name: \"check_session\",\n description: \"Check the status of a background session. Returns status and result if completed.\",\n parameters: {\n type: \"object\",\n properties: {\n task_id: { type: \"string\", description: \"Task ID returned by spawn_session\" },\n },\n required: [\"task_id\"],\n },\n async execute(args) {\n const entry = activeBackgrounds.get(args.task_id ?? \"\");\n if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });\n\n const elapsed = Math.round((Date.now() - entry.startedAt) / 1000);\n return JSON.stringify({\n task_id: entry.taskId,\n session_id: entry.sessionId,\n goal: entry.goal,\n status: entry.status,\n elapsed_seconds: elapsed,\n result: entry.result ?? null,\n });\n },\n};\n\nexport const terminateSessionTool: ToolDefinition = {\n name: \"terminate_session\",\n description: \"Terminate a running background session. It finishes its current operation then stops.\",\n parameters: {\n type: \"object\",\n properties: {\n task_id: { type: \"string\", description: \"Task ID to terminate\" },\n },\n required: [\"task_id\"],\n },\n async execute(args) {\n if (!_runtime) return JSON.stringify({ error: \"Delegation not initialized\" });\n\n const entry = activeBackgrounds.get(args.task_id ?? \"\");\n if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });\n if (entry.status !== \"running\") return JSON.stringify({ error: `Session already ${entry.status}` });\n\n const interrupted = _runtime.interruptSpawn(entry.taskId);\n entry.status = \"terminated\";\n entry.result = \"(terminated by user)\";\n\n if (entry.sessionId && _sessionManager) {\n const managed = _sessionManager.getSessionById(entry.sessionId);\n if (managed) managed.paused = true;\n }\n\n addCompletion({\n sessionId: entry.sessionId,\n motherId: _sessionManager?.getSessionById(entry.sessionId)?.motherId ?? \"\",\n goal: entry.goal,\n status: \"terminated\",\n result: entry.result,\n elapsedMs: Date.now() - entry.startedAt,\n inputTokens: entry.inputTokens,\n outputTokens: entry.outputTokens,\n });\n\n logInfo(TAG, `Terminated background ${entry.taskId} (interrupted=${interrupted})`);\n return JSON.stringify({ task_id: entry.taskId, status: \"terminated\" });\n },\n};\n\nexport const sendToSessionTool: ToolDefinition = {\n name: \"send_to_session\",\n description: \"Send a follow-up instruction to a running background session. The child receives it on its next turn.\",\n parameters: {\n type: \"object\",\n properties: {\n task_id: { type: \"string\", description: \"Task ID of the running session\" },\n message: { type: \"string\", description: \"Instruction to send\" },\n },\n required: [\"task_id\", \"message\"],\n },\n async execute(args) {\n const entry = activeBackgrounds.get(args.task_id ?? \"\");\n if (!entry) return JSON.stringify({ error: `No background session found with task_id: ${args.task_id}` });\n if (entry.status !== \"running\") return JSON.stringify({ error: `Session is ${entry.status}, cannot send instruction` });\n entry.pendingInstruction = args.message;\n logInfo(TAG, `Instruction queued for ${entry.taskId}: \"${(args.message ?? \"\").slice(0, 60)}\"`);\n return JSON.stringify({ delivered: true, task_id: entry.taskId });\n },\n};\n\n/** Check and consume pending instruction for a task. Used by agent loop. */\nexport function consumePendingInstruction(taskId: string): string | undefined {\n const entry = activeBackgrounds.get(taskId);\n if (!entry?.pendingInstruction) return undefined;\n const msg = entry.pendingInstruction;\n entry.pendingInstruction = undefined;\n return msg;\n}\n\nexport function getDelegationTools(): ToolDefinition[] {\n if (!getEnv().enableAsyncDelegation) return [];\n return [spawnSessionTool, checkSessionTool, terminateSessionTool, sendToSessionTool];\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;AASA;AACA;AAEA,IAAM,MAAM;AACZ,IAAM,iBAAiB,SAAS,QAAQ,IAAI,yBAAyB,KAAK,KAAK,EAAE;AAEjF,IAAI,WAAmC;AACvC,IAAI,kBAAyC;AAEtC,SAAS,kBAAkB,SAA0B,gBAAsC;AAChG,aAAW;AACX,oBAAkB;AACpB;AAeA,IAAM,oBAAoB,oBAAI,IAA6B;AAEpD,SAAS,uBAAqD;AACnE,SAAO;AACT;AAEA,IAAM,WAA2E;AAAA,EAC/E,MAAM,EAAE,aAAa,KAAK,OAAO,SAAS;AAAA,EAC1C,QAAQ,EAAE,aAAa,KAAK,OAAO,UAAU;AAAA,EAC7C,MAAM,EAAE,aAAa,KAAK,OAAO,OAAO;AAC1C;AAEO,IAAM,mBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,aAAa;AAAA,EACb,YAAY;AAAA,IACV,MAAM;AAAA,IACN,YAAY;AAAA,MACV,MAAM,EAAE,MAAM,UAAU,MAAM,CAAC,QA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;AAC1C,MAAI,CAAC,OAAO,mBAAoB,QAAO;AACvC,QAAM,MAAM,MAAM;AAClB,QAAM,qBAAqB;AAC3B,SAAO;AACT;AAEO,SAAS,qBAAuC;AACrD,MAAI,CAAC,OAAO,EAAE,sBAAuB,QAAO,CAAC;AAC7C,SAAO,CAAC,kBAAkB,kBAAkB,sBAAsB,iBAAiB;AACrF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,58 @@
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
+ init_logger,
8
+ logDebug,
9
+ logInfo
10
+ } from "./chunk-BUUVFUPO.js";
11
+
12
+ // src/components/stt.ts
13
+ init_logger();
14
+ init_log_and_swallow();
15
+ var TAG = "stt";
16
+ var GROQ_ENDPOINT = "https://api.groq.com/openai/v1/audio/transcriptions";
17
+ var DEFAULT_MODEL = "whisper-large-v3";
18
+ var LANGUAGE_HINT_PROMPT = process.env["STT_LANGUAGE_HINT"] || "";
19
+ async function transcribeAudio(audioBuffer, filename, config) {
20
+ const model = config.model || DEFAULT_MODEL;
21
+ logInfo("stt", `Transcribing ${filename} (${audioBuffer.length} bytes) via ${config.provider}/${model}`);
22
+ const formData = new FormData();
23
+ const blob = new Blob([audioBuffer], { type: "audio/ogg" });
24
+ formData.append("file", blob, filename);
25
+ formData.append("model", model);
26
+ if (LANGUAGE_HINT_PROMPT) formData.append("prompt", LANGUAGE_HINT_PROMPT);
27
+ formData.append("response_format", "verbose_json");
28
+ const endpoint = GROQ_ENDPOINT;
29
+ const response = await fetch(endpoint, {
30
+ method: "POST",
31
+ headers: {
32
+ Authorization: `Bearer ${config.apiKey}`
33
+ },
34
+ body: formData
35
+ });
36
+ if (!response.ok) {
37
+ const text = await response.text().catch((err) => {
38
+ logAndSwallow(TAG, "read STT error body", err);
39
+ return "";
40
+ });
41
+ throw new Error(`STT failed (${response.status}): ${text}`);
42
+ }
43
+ const json = await response.json();
44
+ const transcript = json.text?.trim() ?? "";
45
+ const language = json.language?.trim() ?? "";
46
+ if (!transcript) {
47
+ logDebug("stt", "Empty transcript returned");
48
+ return { text: "", language };
49
+ }
50
+ logInfo("stt", `Transcript (${transcript.length} chars, lang=${language || "?"}): "${transcript.slice(0, 80)}"`);
51
+ return { text: transcript, language };
52
+ }
53
+
54
+ export {
55
+ LANGUAGE_HINT_PROMPT,
56
+ transcribeAudio
57
+ };
58
+ //# sourceMappingURL=chunk-V76TVMCM.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/stt.ts"],
4
+ "sourcesContent": ["import { logInfo, logDebug } from \"./logger.js\";\nimport { logAndSwallow } from \"./log-and-swallow.js\";\n\nconst TAG = \"stt\";\n\nexport type SttProvider = \"groq\";\n\nexport interface SttConfig {\n provider: SttProvider;\n apiKey: string;\n model?: string;\n}\n\nconst GROQ_ENDPOINT = \"https://api.groq.com/openai/v1/audio/transcriptions\";\nconst DEFAULT_MODEL = \"whisper-large-v3\";\nexport const LANGUAGE_HINT_PROMPT = process.env[\"STT_LANGUAGE_HINT\"] || \"\";\n\n/**\n * Transcribe audio using Groq's OpenAI-compatible Whisper endpoint.\n * Sends the audio as multipart/form-data.\n */\nexport async function transcribeAudio(\n audioBuffer: Buffer,\n filename: string,\n config: SttConfig,\n): Promise<{ text: string; language: string }> {\n const model = config.model || DEFAULT_MODEL;\n logInfo(\"stt\", `Transcribing ${filename} (${audioBuffer.length} bytes) via ${config.provider}/${model}`);\n\n const formData = new FormData();\n const blob = new Blob([audioBuffer], { type: \"audio/ogg\" });\n formData.append(\"file\", blob, filename);\n formData.append(\"model\", model);\n if (LANGUAGE_HINT_PROMPT) formData.append(\"prompt\", LANGUAGE_HINT_PROMPT);\n formData.append(\"response_format\", \"verbose_json\");\n\n const endpoint = GROQ_ENDPOINT;\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n },\n body: formData,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(err => { logAndSwallow(TAG, \"read STT error body\", err); return \"\"; });\n throw new Error(`STT failed (${response.status}): ${text}`);\n }\n\n const json = (await response.json()) as { text?: string; language?: string };\n const transcript = json.text?.trim() ?? \"\";\n const language = json.language?.trim() ?? \"\";\n\n if (!transcript) {\n logDebug(\"stt\", \"Empty transcript returned\");\n return { text: \"\", language };\n }\n\n logInfo(\"stt\", `Transcript (${transcript.length} chars, lang=${language || \"?\"}): \"${transcript.slice(0, 80)}\"`);\n return { text: transcript, language };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AAAA;AACA;AAEA,IAAM,MAAM;AAUZ,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACf,IAAM,uBAAuB,QAAQ,IAAI,mBAAmB,KAAK;AAMxE,eAAsB,gBACpB,aACA,UACA,QAC6C;AAC7C,QAAM,QAAQ,OAAO,SAAS;AAC9B,UAAQ,OAAO,gBAAgB,QAAQ,KAAK,YAAY,MAAM,eAAe,OAAO,QAAQ,IAAI,KAAK,EAAE;AAEvG,QAAM,WAAW,IAAI,SAAS;AAC9B,QAAM,OAAO,IAAI,KAAK,CAAC,WAAW,GAAG,EAAE,MAAM,YAAY,CAAC;AAC1D,WAAS,OAAO,QAAQ,MAAM,QAAQ;AACtC,WAAS,OAAO,SAAS,KAAK;AAC9B,MAAI,qBAAsB,UAAS,OAAO,UAAU,oBAAoB;AACxE,WAAS,OAAO,mBAAmB,cAAc;AAEjD,QAAM,WAAW;AAEjB,QAAM,WAAW,MAAM,MAAM,UAAU;AAAA,IACrC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,UAAU,OAAO,MAAM;AAAA,IACxC;A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