tenjin-cli 0.1.0-alpha.33 → 0.1.0-alpha.35

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 (495) hide show
  1. package/NOTICE.md +110 -0
  2. package/README.md +87 -81
  3. package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
  4. package/dist/alive-5TV22PNF.js +51 -0
  5. package/dist/auth-XI7BJFLW.js +47 -0
  6. package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
  7. package/dist/balance-DFHC6XEU.js +71 -0
  8. package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
  9. package/dist/chunk-24XKUN2S.js +202 -0
  10. package/dist/chunk-24XKUN2S.js.map +1 -0
  11. package/dist/chunk-2L7TDGLV.js +56 -0
  12. package/dist/chunk-2L7TDGLV.js.map +1 -0
  13. package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
  14. package/dist/chunk-2U7H35IP.js.map +1 -0
  15. package/dist/chunk-2W4DQQUU.js +176 -0
  16. package/dist/chunk-2W4DQQUU.js.map +1 -0
  17. package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
  18. package/dist/chunk-34SAECKZ.js.map +1 -0
  19. package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
  20. package/dist/chunk-3MZ7DYRO.js.map +1 -0
  21. package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
  22. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  23. package/dist/chunk-3Y6BHIN6.js +169 -0
  24. package/dist/chunk-3Y6BHIN6.js.map +1 -0
  25. package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
  26. package/dist/chunk-3YPL6T3P.js.map +1 -0
  27. package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
  28. package/dist/chunk-44MVIRZH.js.map +1 -0
  29. package/dist/chunk-45MMSBHA.js +321 -0
  30. package/dist/chunk-45MMSBHA.js.map +1 -0
  31. package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
  32. package/dist/chunk-4CE6TMI5.js.map +1 -0
  33. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  34. package/dist/chunk-4MBCJFY4.js.map +1 -0
  35. package/dist/chunk-4TPL54KW.js +227 -0
  36. package/dist/chunk-4TPL54KW.js.map +1 -0
  37. package/dist/chunk-54ELBTKE.js +1615 -0
  38. package/dist/chunk-54ELBTKE.js.map +1 -0
  39. package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
  40. package/dist/chunk-5F4OB5B3.js.map +1 -0
  41. package/dist/chunk-5HN4KVQU.js +3348 -0
  42. package/dist/chunk-5HN4KVQU.js.map +1 -0
  43. package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
  44. package/dist/chunk-5J4E5GYI.js.map +1 -0
  45. package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
  46. package/dist/chunk-5N4GGUBN.js.map +1 -0
  47. package/dist/chunk-5USBZ2MU.js +58 -0
  48. package/dist/chunk-5USBZ2MU.js.map +1 -0
  49. package/dist/chunk-64WOMNYR.js +183 -0
  50. package/dist/chunk-64WOMNYR.js.map +1 -0
  51. package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
  52. package/dist/chunk-65RS4LQS.js.map +1 -0
  53. package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
  54. package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
  55. package/dist/chunk-7SLOTLO7.js.map +1 -0
  56. package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
  57. package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
  58. package/dist/chunk-BGA4DO5M.js +719 -0
  59. package/dist/chunk-BGA4DO5M.js.map +1 -0
  60. package/dist/chunk-BVP7YK2J.js +706 -0
  61. package/dist/chunk-BVP7YK2J.js.map +1 -0
  62. package/dist/chunk-C265QIMJ.js +83 -0
  63. package/dist/chunk-C265QIMJ.js.map +1 -0
  64. package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
  65. package/dist/chunk-CRG54LEB.js.map +1 -0
  66. package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
  67. package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
  68. package/dist/chunk-D6M3ZK66.js.map +1 -0
  69. package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
  70. package/dist/chunk-DI4QAGRZ.js.map +1 -0
  71. package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
  72. package/dist/chunk-DIH2G3YG.js.map +1 -0
  73. package/dist/chunk-DJ36BM62.js +78 -0
  74. package/dist/chunk-DJ36BM62.js.map +1 -0
  75. package/dist/chunk-DTEWAVNE.js +114 -0
  76. package/dist/chunk-DTEWAVNE.js.map +1 -0
  77. package/dist/chunk-F2KJAJ7T.js +13 -0
  78. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  79. package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
  80. package/dist/chunk-F3QPGYOY.js.map +1 -0
  81. package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
  82. package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
  83. package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
  84. package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
  85. package/dist/chunk-GAJC4BQZ.js +1096 -0
  86. package/dist/chunk-GAJC4BQZ.js.map +1 -0
  87. package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
  88. package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
  89. package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
  90. package/dist/chunk-HAZAN4UM.js.map +1 -0
  91. package/dist/chunk-HI5XQOX2.js +393 -0
  92. package/dist/chunk-HI5XQOX2.js.map +1 -0
  93. package/dist/chunk-HKGUKAQW.js +488 -0
  94. package/dist/chunk-HKGUKAQW.js.map +1 -0
  95. package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
  96. package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
  97. package/dist/chunk-HQR4BWKX.js.map +1 -0
  98. package/dist/chunk-HZKANST2.js +177 -0
  99. package/dist/chunk-HZKANST2.js.map +1 -0
  100. package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
  101. package/dist/chunk-I557SAOM.js.map +1 -0
  102. package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
  103. package/dist/chunk-IGLWLH73.js.map +1 -0
  104. package/dist/chunk-ILWCKCOI.js +58 -0
  105. package/dist/chunk-ILWCKCOI.js.map +1 -0
  106. package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
  107. package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
  108. package/dist/chunk-IULCDMVG.js.map +1 -0
  109. package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
  110. package/dist/chunk-IVNSUAVC.js.map +1 -0
  111. package/dist/chunk-JDQZCREI.js +87 -0
  112. package/dist/chunk-JDQZCREI.js.map +1 -0
  113. package/dist/chunk-JHFFUVON.js +1050 -0
  114. package/dist/chunk-JHFFUVON.js.map +1 -0
  115. package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
  116. package/dist/chunk-JTILUN4W.js +2933 -0
  117. package/dist/chunk-JTILUN4W.js.map +1 -0
  118. package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
  119. package/dist/chunk-JTX3BUDK.js.map +1 -0
  120. package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
  121. package/dist/chunk-JUUBBBY5.js.map +1 -0
  122. package/dist/chunk-JWAK7JQB.js +15 -0
  123. package/dist/chunk-JWAK7JQB.js.map +1 -0
  124. package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
  125. package/dist/chunk-K5KNGC4I.js.map +1 -0
  126. package/dist/chunk-KAQ4Q3TO.js +135 -0
  127. package/dist/chunk-KAQ4Q3TO.js.map +1 -0
  128. package/dist/chunk-KFVJYLVL.js +125 -0
  129. package/dist/chunk-KFVJYLVL.js.map +1 -0
  130. package/dist/chunk-KGUE5AVX.js +69 -0
  131. package/dist/chunk-KGUE5AVX.js.map +1 -0
  132. package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
  133. package/dist/chunk-KLDMLWXT.js.map +1 -0
  134. package/dist/chunk-KNKDMTHU.js +453 -0
  135. package/dist/chunk-KNKDMTHU.js.map +1 -0
  136. package/dist/chunk-LDA6TAYQ.js +95 -0
  137. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  138. package/dist/chunk-LWSSIZOY.js +347 -0
  139. package/dist/chunk-LWSSIZOY.js.map +1 -0
  140. package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
  141. package/dist/chunk-MAHNZA6C.js.map +1 -0
  142. package/dist/chunk-MEWZCIA6.js +220 -0
  143. package/dist/chunk-MEWZCIA6.js.map +1 -0
  144. package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
  145. package/dist/chunk-MEZJ3I63.js.map +1 -0
  146. package/dist/chunk-MJDO4EXD.js +353 -0
  147. package/dist/chunk-MJDO4EXD.js.map +1 -0
  148. package/dist/chunk-NJA6NT3A.js +6595 -0
  149. package/dist/chunk-NJA6NT3A.js.map +1 -0
  150. package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
  151. package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
  152. package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
  153. package/dist/chunk-OC7K2DVZ.js.map +1 -0
  154. package/dist/chunk-ODRPASFP.js +2078 -0
  155. package/dist/chunk-ODRPASFP.js.map +1 -0
  156. package/dist/chunk-OJJFANO6.js +133 -0
  157. package/dist/chunk-OJJFANO6.js.map +1 -0
  158. package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
  159. package/dist/chunk-OQWPRFAC.js.map +1 -0
  160. package/dist/chunk-P4I7BFNJ.js +11 -0
  161. package/dist/chunk-P4I7BFNJ.js.map +1 -0
  162. package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
  163. package/dist/chunk-P6YQWIT2.js.map +1 -0
  164. package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
  165. package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
  166. package/dist/chunk-Q6RSJCXB.js.map +1 -0
  167. package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
  168. package/dist/chunk-QKEUKBRK.js.map +1 -0
  169. package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
  170. package/dist/chunk-QKYUCITR.js.map +1 -0
  171. package/dist/chunk-QQDPRTLP.js +127 -0
  172. package/dist/chunk-QQDPRTLP.js.map +1 -0
  173. package/dist/chunk-QQYCYAKI.js +79 -0
  174. package/dist/chunk-QQYCYAKI.js.map +1 -0
  175. package/dist/chunk-R4KDH477.js +1064 -0
  176. package/dist/chunk-R4KDH477.js.map +1 -0
  177. package/dist/chunk-R5TR2DIK.js +119 -0
  178. package/dist/chunk-R5TR2DIK.js.map +1 -0
  179. package/dist/chunk-R62PKTAG.js +66 -0
  180. package/dist/chunk-R62PKTAG.js.map +1 -0
  181. package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
  182. package/dist/chunk-RFZA7PSM.js.map +1 -0
  183. package/dist/chunk-RGCPELQN.js +219 -0
  184. package/dist/chunk-RGCPELQN.js.map +1 -0
  185. package/dist/chunk-RGVCOG2S.js +910 -0
  186. package/dist/chunk-RGVCOG2S.js.map +1 -0
  187. package/dist/chunk-SOLNJ3AZ.js +209 -0
  188. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  189. package/dist/chunk-TFT2X7SH.js +77 -0
  190. package/dist/chunk-TFT2X7SH.js.map +1 -0
  191. package/dist/chunk-TUCKEEXE.js +2 -0
  192. package/dist/chunk-TVWCLUBI.js +293 -0
  193. package/dist/chunk-TVWCLUBI.js.map +1 -0
  194. package/dist/chunk-U4TRWSVE.js +78 -0
  195. package/dist/chunk-U4TRWSVE.js.map +1 -0
  196. package/dist/chunk-UIB33QQP.js +379 -0
  197. package/dist/chunk-UIB33QQP.js.map +1 -0
  198. package/dist/chunk-V6GIVALQ.js +1889 -0
  199. package/dist/chunk-V6GIVALQ.js.map +1 -0
  200. package/dist/chunk-VHXCPXUS.js +366 -0
  201. package/dist/chunk-VHXCPXUS.js.map +1 -0
  202. package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
  203. package/dist/chunk-VU6GMWF6.js.map +1 -0
  204. package/dist/chunk-VWZYE3NC.js +8415 -0
  205. package/dist/chunk-VWZYE3NC.js.map +1 -0
  206. package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
  207. package/dist/chunk-W2GXIARJ.js.map +1 -0
  208. package/dist/chunk-W4G3K3V7.js +288 -0
  209. package/dist/chunk-W4G3K3V7.js.map +1 -0
  210. package/dist/chunk-W74LJ5OT.js +588 -0
  211. package/dist/chunk-W74LJ5OT.js.map +1 -0
  212. package/dist/chunk-W7ELYLYK.js +233 -0
  213. package/dist/chunk-W7ELYLYK.js.map +1 -0
  214. package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
  215. package/dist/chunk-WXA3WTPF.js +20 -0
  216. package/dist/chunk-WXA3WTPF.js.map +1 -0
  217. package/dist/chunk-XRGFH7FI.js +454 -0
  218. package/dist/chunk-XRGFH7FI.js.map +1 -0
  219. package/dist/chunk-XSCGUO2U.js +330 -0
  220. package/dist/chunk-XSCGUO2U.js.map +1 -0
  221. package/dist/chunk-XWROSMI5.js +1039 -0
  222. package/dist/chunk-XWROSMI5.js.map +1 -0
  223. package/dist/chunk-Y2EXZ47H.js +40 -0
  224. package/dist/chunk-Y2EXZ47H.js.map +1 -0
  225. package/dist/chunk-YJGEVBKZ.js +47 -0
  226. package/dist/chunk-YJGEVBKZ.js.map +1 -0
  227. package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
  228. package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
  229. package/dist/chunk-ZCT5DJ3G.js.map +1 -0
  230. package/dist/chunk-ZEYA2WWX.js +982 -0
  231. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  232. package/dist/chunk-ZRC7Z5X3.js +82 -0
  233. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  234. package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
  235. package/dist/chunk-ZS7JIUJ3.js.map +1 -0
  236. package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
  237. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  238. package/dist/claude-install-BAUSJMW3.js +64 -0
  239. package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
  240. package/dist/cli-QY4KKA3D.js.map +1 -0
  241. package/dist/client-3YQKORVK.js +710 -0
  242. package/dist/client-3YQKORVK.js.map +1 -0
  243. package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
  244. package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
  245. package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
  246. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  247. package/dist/config-QZOBMTEL.js +57 -0
  248. package/dist/config-names-Z5NZD5R2.js +224 -0
  249. package/dist/config-names-Z5NZD5R2.js.map +1 -0
  250. package/dist/config-rules-YOYHS6YL.js +55 -0
  251. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  252. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  253. package/dist/connect-YDWTYU4B.js +1020 -0
  254. package/dist/connect-YDWTYU4B.js.map +1 -0
  255. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  256. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  257. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  258. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  259. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  260. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  261. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  262. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  263. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  264. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  265. package/dist/decision-QSKHOGCO.js +145 -0
  266. package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
  267. package/dist/doctor-ZWJXRD75.js.map +1 -0
  268. package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
  269. package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
  270. package/dist/explicit-ME2NRADQ.js +371 -0
  271. package/dist/explicit-ME2NRADQ.js.map +1 -0
  272. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  273. package/dist/fund-VF7TLDJH.js +722 -0
  274. package/dist/fund-VF7TLDJH.js.map +1 -0
  275. package/dist/hook-command-VZ27MGWO.js +49 -0
  276. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  277. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  278. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  279. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  280. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  281. package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
  282. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  283. package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
  284. package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
  285. package/dist/index.js +18 -15
  286. package/dist/index.js.map +1 -1
  287. package/dist/install-ZA7L2UF3.js +115 -0
  288. package/dist/install-funding-JDGYTF72.js +30 -0
  289. package/dist/install-identity-FFAYEFLX.js +30 -0
  290. package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
  291. package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
  292. package/dist/mcp-36S6MK3C.js +67642 -0
  293. package/dist/mcp-36S6MK3C.js.map +1 -0
  294. package/dist/new-install-5L4GY3LN.js +51 -0
  295. package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
  296. package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
  297. package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
  298. package/dist/pay-CMV5KL74.js +74 -0
  299. package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
  300. package/dist/payments-Z6UBZL4Z.js.map +1 -0
  301. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  302. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  303. package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
  304. package/dist/redact-LOTHE5TS.js.map +1 -0
  305. package/dist/routing-quote-AHLAREXR.js +40 -0
  306. package/dist/routing-quote-AHLAREXR.js.map +1 -0
  307. package/dist/run-JH7ELYAM.js +88 -0
  308. package/dist/run-JH7ELYAM.js.map +1 -0
  309. package/dist/runtime-2GX4ALJP.js +410 -0
  310. package/dist/runtime-2GX4ALJP.js.map +1 -0
  311. package/dist/runtime-activate-IDQ2NCSP.js +39 -0
  312. package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
  313. package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
  314. package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
  315. package/dist/runtime-launchers-YAPKCBHV.js +31 -0
  316. package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
  317. package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
  318. package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
  319. package/dist/runtime-place-4POL4KK4.js +37 -0
  320. package/dist/runtime-place-4POL4KK4.js.map +1 -0
  321. package/dist/runtime-provenance-MNJGVBV2.js +12 -0
  322. package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
  323. package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
  324. package/dist/secp256k1-N5P2GVGF.js.map +1 -0
  325. package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
  326. package/dist/send-ELXFKEKY.js.map +1 -0
  327. package/dist/status-FXUFWJDM.js +404 -0
  328. package/dist/status-FXUFWJDM.js.map +1 -0
  329. package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
  330. package/dist/status-line-IH5JBWBC.js.map +1 -0
  331. package/dist/streamableHttp-CP2ZQBIK.js +768 -0
  332. package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
  333. package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
  334. package/dist/uninstall-LJZUKM4D.js.map +1 -0
  335. package/dist/update-EUIX72IX.js +68 -0
  336. package/dist/update-EUIX72IX.js.map +1 -0
  337. package/dist/usage-EKDC7LUC.js +180 -0
  338. package/dist/usage-EKDC7LUC.js.map +1 -0
  339. package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
  340. package/dist/usdc-YIHK2OMC.js.map +1 -0
  341. package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
  342. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  343. package/dist/wallet-HSW757W6.js +80 -0
  344. package/dist/wallet-HSW757W6.js.map +1 -0
  345. package/dist/wallet-kdf-worker.mjs +1433 -818
  346. package/docs/agent-permissions.md +88 -155
  347. package/docs/router-reference.md +236 -0
  348. package/docs/safety-model.md +31 -33
  349. package/docs/subagents-internals.md +97 -0
  350. package/docs/subagents.md +348 -0
  351. package/docs/troubleshooting.md +10 -6
  352. package/package.json +12 -8
  353. package/scripts/installers/install.sh +7 -1
  354. package/dist/alive-GSOWKUOY.js +0 -38
  355. package/dist/chunk-2I4QTOLB.js.map +0 -1
  356. package/dist/chunk-2M2VPI2E.js +0 -560
  357. package/dist/chunk-2M2VPI2E.js.map +0 -1
  358. package/dist/chunk-2RWB7RKE.js.map +0 -1
  359. package/dist/chunk-2SNUOHAT.js.map +0 -1
  360. package/dist/chunk-3623BLPV.js +0 -184
  361. package/dist/chunk-3623BLPV.js.map +0 -1
  362. package/dist/chunk-36RVGZNY.js.map +0 -1
  363. package/dist/chunk-3AIHRXKO.js.map +0 -1
  364. package/dist/chunk-3FMZGI7I.js.map +0 -1
  365. package/dist/chunk-3UCIG4TG.js.map +0 -1
  366. package/dist/chunk-4K7TQHNP.js.map +0 -1
  367. package/dist/chunk-4LMUQMBH.js +0 -29
  368. package/dist/chunk-4LMUQMBH.js.map +0 -1
  369. package/dist/chunk-4USCZ2NI.js +0 -228
  370. package/dist/chunk-4USCZ2NI.js.map +0 -1
  371. package/dist/chunk-4YOZGGTZ.js.map +0 -1
  372. package/dist/chunk-62KNUYWD.js +0 -111
  373. package/dist/chunk-62KNUYWD.js.map +0 -1
  374. package/dist/chunk-A5GKIG5O.js +0 -2037
  375. package/dist/chunk-A5GKIG5O.js.map +0 -1
  376. package/dist/chunk-AGMVASXZ.js.map +0 -1
  377. package/dist/chunk-BF4XHEQK.js.map +0 -1
  378. package/dist/chunk-BFDQ4WNW.js.map +0 -1
  379. package/dist/chunk-C2Q76BVM.js.map +0 -1
  380. package/dist/chunk-CEXSOI5R.js +0 -808
  381. package/dist/chunk-CEXSOI5R.js.map +0 -1
  382. package/dist/chunk-E7SW44LM.js.map +0 -1
  383. package/dist/chunk-EDJWHDDL.js +0 -33
  384. package/dist/chunk-EDJWHDDL.js.map +0 -1
  385. package/dist/chunk-FVIGCDSV.js.map +0 -1
  386. package/dist/chunk-GTTUCOPD.js +0 -105
  387. package/dist/chunk-GTTUCOPD.js.map +0 -1
  388. package/dist/chunk-HDPUXS3Z.js +0 -122
  389. package/dist/chunk-HDPUXS3Z.js.map +0 -1
  390. package/dist/chunk-HGGWCP7W.js +0 -120
  391. package/dist/chunk-HGGWCP7W.js.map +0 -1
  392. package/dist/chunk-HGZEPQUT.js.map +0 -1
  393. package/dist/chunk-HMWYAUA6.js.map +0 -1
  394. package/dist/chunk-IADZOXKN.js.map +0 -1
  395. package/dist/chunk-ILNIZ5I2.js.map +0 -1
  396. package/dist/chunk-INTFHMU4.js.map +0 -1
  397. package/dist/chunk-JKKAIPTU.js.map +0 -1
  398. package/dist/chunk-JNJWBTU2.js.map +0 -1
  399. package/dist/chunk-KM7RY2ZS.js +0 -246
  400. package/dist/chunk-KM7RY2ZS.js.map +0 -1
  401. package/dist/chunk-KOGZDMHO.js +0 -21
  402. package/dist/chunk-KOGZDMHO.js.map +0 -1
  403. package/dist/chunk-L6JEXB3E.js.map +0 -1
  404. package/dist/chunk-LRW6S53P.js.map +0 -1
  405. package/dist/chunk-LXAYUOXI.js +0 -511
  406. package/dist/chunk-LXAYUOXI.js.map +0 -1
  407. package/dist/chunk-MEFB5KHA.js +0 -59
  408. package/dist/chunk-MEFB5KHA.js.map +0 -1
  409. package/dist/chunk-MPZUYCAP.js.map +0 -1
  410. package/dist/chunk-NDGZDTSJ.js.map +0 -1
  411. package/dist/chunk-OJNTCYQQ.js.map +0 -1
  412. package/dist/chunk-P3LFTKE7.js +0 -58
  413. package/dist/chunk-P3LFTKE7.js.map +0 -1
  414. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  415. package/dist/chunk-RVPYTUP4.js.map +0 -1
  416. package/dist/chunk-SNNSAGMT.js.map +0 -1
  417. package/dist/chunk-TC2WZLSC.js.map +0 -1
  418. package/dist/chunk-TKPF35W6.js +0 -29
  419. package/dist/chunk-TKPF35W6.js.map +0 -1
  420. package/dist/chunk-U3IKUGRP.js.map +0 -1
  421. package/dist/chunk-UUGOUOVT.js.map +0 -1
  422. package/dist/chunk-UXZONNEQ.js.map +0 -1
  423. package/dist/chunk-WXA2BWTE.js.map +0 -1
  424. package/dist/chunk-WYXUQGOL.js.map +0 -1
  425. package/dist/chunk-X5ZBP3IY.js.map +0 -1
  426. package/dist/chunk-XKESD27X.js +0 -10
  427. package/dist/chunk-XKESD27X.js.map +0 -1
  428. package/dist/chunk-XQJXNMSB.js.map +0 -1
  429. package/dist/chunk-Y527D4TV.js +0 -56
  430. package/dist/chunk-Y527D4TV.js.map +0 -1
  431. package/dist/chunk-ZDZERB6L.js.map +0 -1
  432. package/dist/chunk-ZNNXRNFD.js.map +0 -1
  433. package/dist/chunk-ZURZHELF.js.map +0 -1
  434. package/dist/cli-E36SPKBW.js.map +0 -1
  435. package/dist/codex-install-HQZDGFXW.js.map +0 -1
  436. package/dist/config-HY2E4GGW.js +0 -55
  437. package/dist/doctor-I6XQEKWD.js.map +0 -1
  438. package/dist/fund-2QRO7OJL.js +0 -378
  439. package/dist/fund-2QRO7OJL.js.map +0 -1
  440. package/dist/hook-command-2UBCSZG6.js +0 -43
  441. package/dist/install-ILUX5C4A.js +0 -107
  442. package/dist/install-identity-TZKGY6LQ.js +0 -31
  443. package/dist/install-wallet-5M4OTYLX.js.map +0 -1
  444. package/dist/mcp-LE4DUS22.js +0 -14127
  445. package/dist/mcp-LE4DUS22.js.map +0 -1
  446. package/dist/pay-WCG3IH4R.js +0 -55
  447. package/dist/payments-HFPPWHTV.js.map +0 -1
  448. package/dist/plugin-registration-PZFI5GZW.js +0 -68
  449. package/dist/runtime-UZOKSUZX.js +0 -1321
  450. package/dist/runtime-UZOKSUZX.js.map +0 -1
  451. package/dist/send-GCVEAQKL.js.map +0 -1
  452. package/dist/status-HCVAOCN7.js +0 -150
  453. package/dist/status-HCVAOCN7.js.map +0 -1
  454. package/dist/status-line-OPCXDHL2.js.map +0 -1
  455. package/dist/uninstall-BAWRBXXQ.js.map +0 -1
  456. package/dist/update-CACXLQLR.js +0 -56
  457. package/dist/wallet-QL4UUXEZ.js +0 -55
  458. /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
  459. /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
  460. /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
  461. /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
  462. /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
  463. /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  464. /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
  465. /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
  466. /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
  467. /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
  468. /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
  469. /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
  470. /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
  471. /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
  472. /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
  473. /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
  474. /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
  475. /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
  476. /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  477. /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  478. /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
  479. /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  480. /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
  481. /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  482. /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
  483. /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
  484. /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
  485. /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  486. /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  487. /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
  488. /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
  489. /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
  490. /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  491. /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
  492. /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
  493. /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  494. /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
  495. /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
@@ -0,0 +1,2987 @@
1
+ import type {
2
+ EngineInterface,
3
+ On,
4
+ TurnStepChunk,
5
+ TurnStepInput,
6
+ TurnStepResult,
7
+ } from 'claude-code';
8
+ import { update } from 'claude-code';
9
+ import {
10
+ asRecord as record,
11
+ subagentsEnabled as enabled,
12
+ HELD_NOT_STARTED,
13
+ HELD_WITH_OFFER,
14
+ tenjinDataDir,
15
+ textOf,
16
+ withDelegatedHint,
17
+ } from './hook-data';
18
+ import type {
19
+ TenjinModelActivity,
20
+ TenjinModelViewerRecord,
21
+ TenjinModelViewerState,
22
+ TenjinModelWorker,
23
+ } from '../types';
24
+
25
+ // Source candidate: the production native ordering, permissions and Remote Control gate is separate.
26
+ const TYPE = 'tenjin:deepseek-viewer';
27
+ export const VIEWER_TYPE = TYPE;
28
+ const ACCEPT = 'mcp__plugin_tenjin_router__subagent';
29
+ const ACTIVITY = 'mcp__plugin_tenjin_router__subagent_activity';
30
+ const SERVER = 'plugin:tenjin:router';
31
+ const STATE = { plugin: 'tenjin', key: 'modelViewers' } as const;
32
+ const WORKERS = { plugin: 'tenjin', key: 'modelWorkers' } as const;
33
+ const ASSIGNMENTS = { plugin: 'tenjin', key: 'modelAssignments' } as const;
34
+ const OFFERS = { plugin: 'tenjin', key: 'modelOffers' } as const;
35
+ /** How long the CLI keeps an offer open (`model-job.ts`). */
36
+ const OFFER_MS = 15 * 60_000;
37
+ /**
38
+ * Each loop's latest model request as the host numbers it, `<turn id>:<index>`, by
39
+ * agent id ('' for the main loop). A held call names the request that made it, so
40
+ * the CLI tells two calls of one response from the repeat that keeps an offer native.
41
+ */
42
+ const steps = new Map<string, string>();
43
+ export function modelStep(agentId: string | undefined): string | undefined {
44
+ const step = steps.get(agentId ?? '');
45
+ return short(step) ? step : undefined;
46
+ }
47
+ /**
48
+ * What the viewer agent is told. Its offer id and description follow, so the
49
+ * transcript's first message can be drawn as the worker's real assignment.
50
+ */
51
+ const VIEWER_PROMPT = 'Observe only the already owned DeepSeek worker activity.';
52
+ /**
53
+ * THE WORKER'S CALLS AS CLAUDE CODE DRAWS ITS OWN: a viewer step asks for these tools,
54
+ * and this module answers each from the worker's row, so none runs (`tool.call`
55
+ * below; `tool.check` refuses any other call in a viewer's loop). A call of another
56
+ * tool is written as a line of the step's text.
57
+ */
58
+ const VIEWER_TOOLS = ['Read', 'Bash', 'Edit', 'Write', 'WebFetch', 'WebSearch'] as const;
59
+ /** The ids a viewer step gives its calls, so no other call is answered as one. */
60
+ const CALL_ID = 'toolu_dsv';
61
+ /** A run's rows not yet written into its viewer's transcript, at most. */
62
+ const PENDING_ROWS = 2000;
63
+ /** What the engine draws of a message, at most. */
64
+ const ASSIGNMENT_CHARS = 100_000;
65
+ const RESULT_CHARS = 256 * 1024;
66
+ /** The CLI's own window of latest rows (`model-worker-activity.ts`). */
67
+ const ACTIVITY_ROWS = 128;
68
+ /** How often a running worker's row reads its activity file and its clock moves. */
69
+ const POLL_MS = 1000;
70
+ /** How long retirement waits for a viewer still starting, so it binds first. */
71
+ const SPAWN_WAIT_MS = 10_000;
72
+ /**
73
+ * How long one viewer step waits for the worker's next reply, so it ends by itself (by
74
+ * one 25 s read more at most) well before Claude Code ends it: the host aborts a
75
+ * background agent that shows no progress for ten minutes (its stall watchdog,
76
+ * 2.1.326). The viewer's stop is then held while the worker runs, and the next step
77
+ * follows on.
78
+ */
79
+ const STEP_MS = 5 * 60_000;
80
+ /** Claude Code ends a turn whose stop was held more than 8 times in a row. */
81
+ const MAX_HOLDS = 8;
82
+ /** Steps one viewer turn may take: one a worker reply, the holds between; past it the viewer ends, the worker runs on. */
83
+ const VIEWER_TURNS = 2000;
84
+ /** Viewer agents whose step ended at its bound, for their stop to be held once. */
85
+ const handedOver = new Set<string>();
86
+ type Row = TenjinModelActivity['rows'][number];
87
+ /**
88
+ * What a viewer agent has followed of its worker: the activity sequence read, the
89
+ * rows not yet written into its transcript, and how the job ended once it has. In
90
+ * memory only; a reload starts it over.
91
+ */
92
+ type View = {
93
+ offerId: string;
94
+ sequence: number;
95
+ rows: Row[];
96
+ shown: Set<string>;
97
+ dropped: number;
98
+ holds: number;
99
+ ended?: Json;
100
+ done?: boolean;
101
+ };
102
+ const views = new Map<string, View>();
103
+ /** The calls viewer steps made, by the id each step gave them, until each is answered. */
104
+ const viewerCalls = new Map<string, { row: Row; input: Json }>();
105
+ /** A viewer call a router tool served, by its id: its row names that tool (`Exa search`). */
106
+ const servedCalls = new Map<string, string>();
107
+ /**
108
+ * THE WORKER'S ROW STANDS WHERE ITS HELD AGENT CALL STOOD, as the tool router redraws a
109
+ * held `Web Search` row with the lookup that took it. Claude Code draws one Agent call
110
+ * of a response as a row of its own, which this mod redraws: the offer while it is
111
+ * open, then the worker. The accept call then draws nothing for that offer. Two or more
112
+ * Agent calls of one response are Claude Code's own summary block, which no hook
113
+ * redraws, so only their workers draw at the accept call.
114
+ *
115
+ * `heldRows`: the offers whose held row last drew compact, by surface. A row drawn in
116
+ * full (ctrl+o) is the engine's, and there the accept call draws the worker.
117
+ * `acceptSeen`: the accept call that runs an offer, as its row last read it; its answer
118
+ * is how the worker ended, which the held row has no other way to read after a resume.
119
+ * Facts about the drawing alone, in the module's own memory: a reload starts them over
120
+ * and the next drawing of each row writes them again.
121
+ */
122
+ const heldRows = new Set<string>();
123
+ /**
124
+ * Offers whose held call was one of two or more Agent calls of one response, which Claude
125
+ * Code draws as its summary block: never in place, whatever drew before. Live on alpha.80
126
+ * the first call of such a response drew as a row of its own for a moment, before the
127
+ * second call joined it, and marked itself in place; the accept then drew nothing for it
128
+ * and its worker had no row at all.
129
+ */
130
+ const groupedOffers = new Set<string>();
131
+ const inPlace = (surface: string, offerId: string) =>
132
+ heldRows.has(surface + ':' + offerId) && !groupedOffers.has(offerId.toLowerCase());
133
+ type AcceptCall = { output?: unknown; isInterrupted?: boolean; isErrored?: boolean };
134
+ type AcceptSeen = AcceptCall & { call: string; batched: boolean; started: boolean };
135
+ const acceptSeen = new Map<string, AcceptSeen>();
136
+ /** Kept for a session's rows: far more than one screen holds. */
137
+ const DRAWN_MAX = 512;
138
+ function markHeldRow($: Dollar, key: string, compact: boolean): void {
139
+ if (compact === heldRows.has(key)) return;
140
+ if (compact) heldRows.add(key);
141
+ else heldRows.delete(key);
142
+ if (heldRows.size > DRAWN_MAX) heldRows.delete(heldRows.values().next().value!);
143
+ $.ui.invalidate('ui.render');
144
+ }
145
+ /** An accept call that started nothing says so with an `action`; it never ran the worker. */
146
+ function startedNothing(output: unknown): boolean {
147
+ return typeof acceptResponse(textOf(output))?.action === 'string';
148
+ }
149
+ /**
150
+ * What an accept call's row read of its offers. The call that started the worker is
151
+ * the offer's own (the accept hook names it); a call sent again while the worker runs
152
+ * started nothing and never replaces it. After a reload the first call drawn takes an
153
+ * offer, and one that ran its worker takes it from one that started nothing.
154
+ */
155
+ function noteAccept($: Dollar, call: string | undefined, ids: string[], props: AcceptCall): void {
156
+ if (!short(call)) return;
157
+ let changed = false;
158
+ for (const id of ids) {
159
+ const held = acceptSeen.get(id);
160
+ const started = !startedNothing(props.output);
161
+ if (held && held.call !== call && (held.started || !started)) continue;
162
+ if (
163
+ held?.call === call &&
164
+ held.output === props.output &&
165
+ held.isInterrupted === props.isInterrupted &&
166
+ held.isErrored === props.isErrored
167
+ )
168
+ continue;
169
+ acceptSeen.delete(id);
170
+ acceptSeen.set(id, {
171
+ call,
172
+ batched: ids.length > 1,
173
+ started: held?.call === call ? held.started || started : started,
174
+ ...(props.output !== undefined ? { output: props.output } : {}),
175
+ ...(props.isInterrupted !== undefined ? { isInterrupted: props.isInterrupted } : {}),
176
+ ...(props.isErrored !== undefined ? { isErrored: props.isErrored } : {}),
177
+ });
178
+ changed = true;
179
+ }
180
+ while (acceptSeen.size > DRAWN_MAX) acceptSeen.delete(acceptSeen.keys().next().value!);
181
+ if (changed) $.ui.invalidate('ui.render');
182
+ }
183
+ /** An aborted viewer turn's agent is read again once, after this, in case its stop lands late. */
184
+ const RECHECK_MS = 1500;
185
+ /** Set once the session ends: what ends with it is not a person stopping an agent. */
186
+ let sessionEnding = false;
187
+ /**
188
+ * THE HELD NOTICE OF A PARALLEL AGENT SUMMARY. Claude Code draws two or more Agent calls of
189
+ * one response as a block of its own, which reads `Not run` for a held call and takes no
190
+ * text of ours. While those calls wait for the parent's answer, one line in the band above
191
+ * the prompt says Tenjin offered DeepSeek for them. It is taken back at the first answer
192
+ * to any of them (an accept, the call sent again, a cancel) and when the parent's turn or
193
+ * the session ends: the rows that start then say the rest, and a count that an answer made
194
+ * wrong is never left on screen. It is this module's memory alone, never the transcript's
195
+ * or the session's state, so a resumed session shows none.
196
+ */
197
+ let heldGroup = 0;
198
+ function showHeldGroup($: Dollar, calls: number): void {
199
+ if (heldGroup === calls) return;
200
+ heldGroup = calls;
201
+ try {
202
+ $.ui.invalidate('ui.render');
203
+ } catch {
204
+ /* Display only. */
205
+ }
206
+ }
207
+ /**
208
+ * A turn that starts is a live session: `/clear` keeps this module for the session that
209
+ * follows (Claude Code 2.1.328 ends the old one, then gives the process a new session id).
210
+ */
211
+ export function sessionLives(): void {
212
+ sessionEnding = false;
213
+ }
214
+ /**
215
+ * Workers whose rows this module follows: an accept call in flight, or one it
216
+ * took up again after a reload. A reload forgets them; a row then drawn as
217
+ * running asks the CLI how its job stands (`adopt`).
218
+ */
219
+ const liveWorkers = new Set<string>();
220
+ /** Rows taken up again in this module's life, each once. */
221
+ const adopted = new Set<string>();
222
+ /**
223
+ * What the host answers an accept call it moved to the background: a tool call
224
+ * still running after two minutes becomes a task of the session, and the
225
+ * parent reads this notice in place of the worker's answer until the task ends.
226
+ */
227
+ const HOST_MOVED = /still running after[\s\S]{0,80}moved to the background/;
228
+ /**
229
+ * What the host answers an accept call it ended itself because the call sent no response or
230
+ * progress for its idle limit (30 minutes by default). The worker runs on in the CLI and
231
+ * keeps its result with the job: this module follows it to its end and hands the result
232
+ * over as a background worker's, once.
233
+ */
234
+ const HOST_IDLE_ABORT = /sent no response or progress for \d+s/;
235
+ /** Those tasks, by the id the notice names, so the task's own lines can name their worker. */
236
+ const movedTasks = new Map<string, readonly string[]>();
237
+ /** Accept calls by their tool use id, for the same. */
238
+ const acceptCalls = new Map<string, readonly string[]>();
239
+ const ENDED = ['completed', 'cancelled', 'unknown'];
240
+ const ALIASES = 'deepseek-viewer-alias-v1:';
241
+ const SERIAL = 'deepseek-viewer-serial-v1';
242
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
243
+ /** The agent type a worker runs as: a built-in or a custom one. A plugin's (`a:b`) stays native. */
244
+ const PROFILE = /^[A-Za-z0-9_.-]{1,200}$/;
245
+ const profileOf = (value: unknown): value is string =>
246
+ typeof value === 'string' && PROFILE.test(value);
247
+ const WORKER =
248
+ /^tenjin-worker-[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
249
+ // Deny-only fallback when both public observation reads fail. No job or scope authority.
250
+ const liveViewerGuards = new Map<string, { turnId?: string }>();
251
+ let pendingViewerSpawns = 0;
252
+ function guardViewer(id: string, turnId?: string) {
253
+ let held = liveViewerGuards.get(id);
254
+ if (!held && liveViewerGuards.size < 16) {
255
+ held = {};
256
+ liveViewerGuards.set(id, held);
257
+ }
258
+ if (held && !held.turnId && turnId) held.turnId = turnId;
259
+ return held;
260
+ }
261
+ type Dollar = EngineInterface;
262
+ type Json = Record<string, unknown>;
263
+ type ViewerBinding = { parentSessionId: string; cwd: string; offerId: string };
264
+ type Alias = {
265
+ parentSessionId: string;
266
+ cwd: string;
267
+ nativeId: string;
268
+ workerHandle: string;
269
+ offerId: string;
270
+ generation: string;
271
+ profile: string;
272
+ ordinal: number;
273
+ };
274
+
275
+ const short = (value: unknown, max = 200): value is string =>
276
+ typeof value === 'string' && value.length > 0 && value.length <= max;
277
+ function clean(value: string, bytes = 512): string {
278
+ // The controller already masks known secrets; remove terminal/format controls again at display.
279
+ const text = value
280
+ // eslint-disable-next-line no-control-regex
281
+ .replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g, '')
282
+ .replace(/[\p{Cc}\p{Cf}]/gu, ' ')
283
+ .trim();
284
+ const encoded = new TextEncoder().encode(text);
285
+ return encoded.length <= bytes
286
+ ? text
287
+ : new TextDecoder().decode(encoded.slice(0, bytes - 4)) + '…';
288
+ }
289
+ /** Display text of several lines: terminal and format controls removed, line breaks kept. */
290
+ function plain(value: string, chars: number): string {
291
+ const text = value
292
+ // eslint-disable-next-line no-control-regex
293
+ .replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g, '')
294
+ .replace(/\r\n?/g, '\n')
295
+ .replace(/(?![\n\t])[\p{Cc}\p{Cf}]/gu, ' ')
296
+ .trim();
297
+ return text.length <= chars ? text : text.slice(0, chars - 1) + '…';
298
+ }
299
+ function json(value: unknown, max = 300_000): Json | undefined {
300
+ if (typeof value !== 'string' || value.length > max) return undefined;
301
+ try {
302
+ return record(JSON.parse(value));
303
+ } catch {
304
+ return undefined;
305
+ }
306
+ }
307
+ function body(value: unknown): Json | undefined {
308
+ const outer = record(value);
309
+ if (!outer || !Array.isArray(outer.content)) return json(value);
310
+ for (const block of outer.content.slice(0, 4)) {
311
+ const text = record(block);
312
+ if (text?.type === 'text') {
313
+ const parsed = json(text.text);
314
+ if (parsed) return parsed;
315
+ }
316
+ }
317
+ return undefined;
318
+ }
319
+
320
+ async function scope($: Dollar) {
321
+ const parentSessionId = await $.session.id();
322
+ const cwd = (await $.fs.stat(await $.session.cwd(), { resolve: true })).realPath;
323
+ return short(parentSessionId, 2000) && short(cwd, 4000) ? { parentSessionId, cwd } : undefined;
324
+ }
325
+ async function load($: Dollar) {
326
+ const owner = await scope($);
327
+ if (!owner) return undefined;
328
+ const held = await $.state.get(STATE);
329
+ const old = held.value;
330
+ const same =
331
+ old?.version === 1 && old.parentSessionId === owner.parentSessionId && old.cwd === owner.cwd;
332
+ const state: TenjinModelViewerState = same
333
+ ? structuredClone(old)
334
+ : {
335
+ version: 1,
336
+ ...owner,
337
+ serial: old?.serial ?? 0,
338
+ records: [],
339
+ knownIds: [],
340
+ };
341
+ return { state, version: held.version };
342
+ }
343
+ async function change($: Dollar, edit: (state: TenjinModelViewerState) => void) {
344
+ const owner = await scope($);
345
+ if (!owner) return;
346
+ // The public helper retries CAS conflicts and reapplies the ownership checks to fresh state.
347
+ return update($, STATE, (old) => {
348
+ const previous =
349
+ old?.version === 1 && old.parentSessionId === owner.parentSessionId ? old : undefined;
350
+ const state: TenjinModelViewerState =
351
+ previous?.cwd === owner.cwd
352
+ ? structuredClone(previous)
353
+ : { version: 1, ...owner, serial: old?.serial ?? 0, records: [], knownIds: [] };
354
+ if (previous && previous.cwd !== owner.cwd) {
355
+ // A worker can outlive the directory that started it. Retain only the
356
+ // identity needed to stop it. Its former display scope no longer applies.
357
+ state.priorStops = [
358
+ ...(previous.priorStops ?? []),
359
+ ...previous.records
360
+ .filter((r) => r.active)
361
+ .map(({ offerId, nativeId, turnId }) => ({ offerId, nativeId, turnId })),
362
+ ];
363
+ }
364
+ edit(state);
365
+ return state;
366
+ });
367
+ }
368
+ async function retireViewer($: Dollar, binding: ViewerBinding): Promise<void> {
369
+ const [parentSessionId, held] = await Promise.all([$.session.id(), $.state.get(STATE)]);
370
+ const previous = held.value;
371
+ const item =
372
+ (previous?.cwd === binding.cwd
373
+ ? previous.records.find((r) => r.offerId === binding.offerId)
374
+ : undefined) ?? previous?.priorStops?.find((r) => r.offerId === binding.offerId);
375
+ if (
376
+ !previous ||
377
+ !item ||
378
+ parentSessionId !== binding.parentSessionId ||
379
+ previous.parentSessionId !== binding.parentSessionId
380
+ )
381
+ return;
382
+ const nativeId = item.nativeId;
383
+ // Display retirement uses the accepted binding, not current filesystem access.
384
+ await update($, STATE, (current) => {
385
+ if (!current) throw new Error('Activity binding unavailable');
386
+ if (current.parentSessionId !== binding.parentSessionId) return current;
387
+ const state = structuredClone(current);
388
+ state.priorStops = state.priorStops?.filter((r) => r.offerId !== binding.offerId);
389
+ const owned =
390
+ state.cwd === binding.cwd
391
+ ? state.records.find((r) => r.offerId === binding.offerId && r.nativeId === nativeId)
392
+ : undefined;
393
+ if (owned) {
394
+ owned.active = false;
395
+ owned.inspectionUnavailable = true;
396
+ }
397
+ return state;
398
+ });
399
+ }
400
+ async function hex(text: string): Promise<string> {
401
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
402
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
403
+ }
404
+ async function aliasKey(nativeId: string): Promise<string> {
405
+ return ALIASES + (await hex(nativeId));
406
+ }
407
+ /** The held Agent call's description as a row may show it: never a secret, URL or address. */
408
+ function titleOf(input: Json | undefined, fallback: string): string {
409
+ const raw = typeof input?.description === 'string' ? input.description : fallback;
410
+ return /secret|password|token|api.key|bearer|https?:|0x[0-9a-f]{32}/i.test(raw)
411
+ ? fallback
412
+ : clean(raw, 64) || fallback;
413
+ }
414
+ /** Where the CLI keeps a running worker's display activity (`model-worker-progress.ts`). */
415
+ async function progressPath($: Dollar, offerId: string): Promise<string | undefined> {
416
+ const data = await tenjinDataDir($);
417
+ if (!data) return undefined;
418
+ const session = await $.session.id();
419
+ return `${data}/progress/model-workers/${await hex(session)}-${await hex(offerId)}.json`;
420
+ }
421
+ async function readAlias($: Dollar, nativeId: unknown): Promise<Alias | undefined> {
422
+ if (!short(nativeId)) return;
423
+ const a = record(await $.store.get(await aliasKey(nativeId)));
424
+ if (
425
+ a &&
426
+ short(a.parentSessionId, 2000) &&
427
+ short(a.cwd, 4000) &&
428
+ a.nativeId === nativeId &&
429
+ short(a.workerHandle) &&
430
+ WORKER.test(a.workerHandle) &&
431
+ short(a.offerId) &&
432
+ UUID.test(a.offerId) &&
433
+ short(a.generation) &&
434
+ profileOf(a.profile) &&
435
+ Number.isSafeInteger(a.ordinal) &&
436
+ Number(a.ordinal) > 0
437
+ )
438
+ return a as Alias;
439
+ }
440
+ async function serial($: Dollar): Promise<number> {
441
+ const value = await $.store.get(SERIAL);
442
+ return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : 0;
443
+ }
444
+ async function registerType($: Dollar): Promise<void> {
445
+ await $.agent.register({
446
+ name: 'deepseek-viewer',
447
+ description: 'Read-only activity for an already owned Tenjin DeepSeek worker',
448
+ prompt:
449
+ 'Display the already owned DeepSeek worker activity. Never execute its assignment or request model inference.',
450
+ // Every step is the plugin's own made-up response and every call it makes is answered
451
+ // here, so no model request is made and no tool runs. The model is a placeholder that
452
+ // only a failure of every guard below could reach. Worker limits are independent.
453
+ tools: [...VIEWER_TOOLS],
454
+ model: 'haiku',
455
+ maxTurns: VIEWER_TURNS,
456
+ omitClaudeMd: true,
457
+ });
458
+ }
459
+
460
+ /**
461
+ * Called only after the existing local handoff validated its offer. The held
462
+ * call's own prompt is kept in the session's state, for its viewer's first
463
+ * message alone; nothing here is saved across sessions but the serial.
464
+ */
465
+ export async function rememberModelOffer(
466
+ $: Dollar,
467
+ offerId: string,
468
+ nativeInput: Json,
469
+ ): Promise<void> {
470
+ try {
471
+ if (!UUID.test(offerId) || !(await enabled($))) return;
472
+ const profile = nativeInput.subagent_type ?? 'general-purpose';
473
+ if (!profileOf(profile)) return;
474
+ const priorSerial = await serial($);
475
+ const title = titleOf(nativeInput, profile);
476
+ await registerType($);
477
+ let released: string | undefined;
478
+ const current = await change($, (state) => {
479
+ released = undefined;
480
+ if (state.records.some((r) => r.offerId === offerId)) return;
481
+ if (state.records.length >= 16) {
482
+ // A worker that ran and ended goes before an offer that may still be accepted.
483
+ const ran = state.records.findIndex((r) => !r.active && r.activity);
484
+ const free = ran >= 0 ? ran : state.records.findIndex((r) => !r.active);
485
+ if (free < 0) return;
486
+ released = state.records.splice(free, 1)[0]?.offerId;
487
+ }
488
+ const ordinal = Math.max(state.serial, priorSerial) + 1;
489
+ if (!Number.isSafeInteger(ordinal)) return;
490
+ state.serial = ordinal;
491
+ // THE AGENT LIST NAMES THE VIEWER AS THE TASK, as a native subagent's entry is its
492
+ // call's description: ` (2)` on a second of the same, since the viewer binds by it.
493
+ const taken = new Set(state.records.map((r) => r.description));
494
+ let description = title;
495
+ for (let n = 2; taken.has(description); n++) description = title + ' (' + n + ')';
496
+ state.records.push({ offerId, ordinal, profile, title, description, active: false });
497
+ });
498
+ if (current) {
499
+ await $.store.set(SERIAL, Math.max(await serial($), current.serial));
500
+ // An Agent call's prompt, or a follow-up's message to its worker.
501
+ const assignment = [nativeInput.prompt, nativeInput.message].find(
502
+ (text): text is string => typeof text === 'string' && text.trim().length > 0,
503
+ );
504
+ if (assignment && current.records.some((r) => r.offerId === offerId))
505
+ await $.state.set({ ...ASSIGNMENTS, id: offerId }, plain(assignment, ASSIGNMENT_CHARS));
506
+ await $.state.set(
507
+ { ...OFFERS, id: offerId },
508
+ {
509
+ at: await $.clock.now(),
510
+ state: 'offered',
511
+ // The host may hand the field over as the string "true" (2.1.327).
512
+ ...(nativeInput.run_in_background === true || nativeInput.run_in_background === 'true'
513
+ ? { background: true as const }
514
+ : {}),
515
+ },
516
+ );
517
+ if (released) await $.state.set({ ...ASSIGNMENTS, id: released }, '');
518
+ }
519
+ } catch {
520
+ /* An unavailable viewer never changes the held assignment or acceptance. */
521
+ }
522
+ }
523
+
524
+ /**
525
+ * THE VETO IS THE SAME CALL SENT AGAIN, which the CLI lets run native, naming the
526
+ * one open offer that repeat settled. That offer's row gives way to the native
527
+ * call's own: one row a task. Any other offer, of the same assignment too, stays open.
528
+ */
529
+ export async function keptNative($: Dollar, offerId: unknown): Promise<void> {
530
+ try {
531
+ if (!short(offerId) || !UUID.test(offerId)) return;
532
+ showHeldGroup($, 0);
533
+ const ref = { ...OFFERS, id: offerId };
534
+ const offer = (await $.state.get(ref)).value;
535
+ if (offer?.state === 'offered') await $.state.set(ref, { ...offer, state: 'native' });
536
+ } catch {
537
+ /* Display only. */
538
+ }
539
+ }
540
+
541
+ function activityOf(response: unknown, offerId: string): TenjinModelActivity | undefined {
542
+ const outer = body(response),
543
+ a = record(outer?.activity);
544
+ if (
545
+ outer?.status !== 'activity' ||
546
+ a?.version !== 1 ||
547
+ a.offerId !== offerId ||
548
+ !short(a.workerHandle) ||
549
+ !WORKER.test(a.workerHandle) ||
550
+ !short(a.generation) ||
551
+ !profileOf(a.nativeProfile) ||
552
+ !Number.isSafeInteger(a.sequence) ||
553
+ Number(a.sequence) < 0 ||
554
+ !['starting', 'running', 'completed', 'cancelled', 'unknown'].includes(String(a.state))
555
+ )
556
+ return;
557
+ const rows: TenjinModelActivity['rows'] = [];
558
+ if (Array.isArray(a.rows))
559
+ for (const value of a.rows.slice(-ACTIVITY_ROWS)) {
560
+ const r = record(value);
561
+ if (
562
+ !r ||
563
+ !short(r.id) ||
564
+ !Number.isSafeInteger(r.sequence) ||
565
+ !['text', 'tool', 'status', 'compaction'].includes(String(r.kind)) ||
566
+ !['running', 'completed', 'error', 'cancelled', 'unknown'].includes(String(r.state))
567
+ )
568
+ continue;
569
+ rows.push({
570
+ id: r.id,
571
+ sequence: Number(r.sequence),
572
+ kind: r.kind as Row['kind'],
573
+ state: String(r.state),
574
+ ...(short(r.message, 64) ? { message: r.message } : {}),
575
+ ...(Number.isSafeInteger(r.lines) && Number(r.lines) >= 0
576
+ ? { lines: Number(r.lines) }
577
+ : {}),
578
+ ...(typeof r.target === 'string' ? { target: clean(r.target, 1024) } : {}),
579
+ ...(short(r.via, 64) ? { via: clean(r.via, 64) } : {}),
580
+ ...figuresOf(record(r.figures)),
581
+ ...(typeof r.name === 'string' ? { name: clean(r.name, 120) } : {}),
582
+ ...(typeof r.text === 'string' ? { text: clean(r.text) } : {}),
583
+ ...(typeof r.inputSummary === 'string' ? { inputSummary: clean(r.inputSummary) } : {}),
584
+ ...(typeof r.command === 'string' ? { command: clean(r.command, 1024) } : {}),
585
+ // Its lines kept: a command's result line is its output's first lines.
586
+ ...(typeof r.outputPreview === 'string'
587
+ ? { outputPreview: plain(r.outputPreview, 1024) }
588
+ : {}),
589
+ ...(typeof r.elapsedSeconds === 'number' &&
590
+ Number.isFinite(r.elapsedSeconds) &&
591
+ r.elapsedSeconds >= 0
592
+ ? { elapsedSeconds: r.elapsedSeconds }
593
+ : {}),
594
+ });
595
+ }
596
+ const spend = record(a.spend);
597
+ const validSpend =
598
+ spend &&
599
+ typeof spend.reservedAtomic === 'string' &&
600
+ /^\d{1,30}$/.test(spend.reservedAtomic) &&
601
+ typeof spend.actualAtomic === 'string' &&
602
+ /^\d{1,30}$/.test(spend.actualAtomic) &&
603
+ Array.isArray(spend.uncertain) &&
604
+ spend.uncertain.length <= 128 &&
605
+ spend.uncertain.every((v) => short(v));
606
+ return {
607
+ version: 1,
608
+ offerId,
609
+ workerHandle: a.workerHandle,
610
+ generation: a.generation,
611
+ nativeProfile: a.nativeProfile,
612
+ sequence: Number(a.sequence),
613
+ state: a.state as TenjinModelActivity['state'],
614
+ ...(typeof a.started === 'boolean' ? { started: a.started } : {}),
615
+ droppedRows:
616
+ (Number.isSafeInteger(a.droppedRows) && Number(a.droppedRows) >= 0
617
+ ? Number(a.droppedRows)
618
+ : 0) + (Array.isArray(a.rows) ? Math.max(0, a.rows.length - ACTIVITY_ROWS) : 0),
619
+ rows,
620
+ ...(Number.isSafeInteger(a.toolUses) && Number(a.toolUses) >= 0
621
+ ? { toolUses: Number(a.toolUses) }
622
+ : {}),
623
+ ...(Number.isSafeInteger(a.tokens) && Number(a.tokens) >= 0
624
+ ? { tokens: Number(a.tokens) }
625
+ : {}),
626
+ ...(validSpend
627
+ ? {
628
+ spend: {
629
+ reservedAtomic: spend.reservedAtomic as string,
630
+ actualAtomic: spend.actualAtomic as string,
631
+ uncertain: [...(spend.uncertain as string[])],
632
+ },
633
+ }
634
+ : {}),
635
+ };
636
+ }
637
+ async function refresh($: Dollar, offerId: string, isCurrent = () => true): Promise<boolean> {
638
+ const data = activityOf(
639
+ await $.mcp.call(SERVER, 'subagent_activity', { offer_id: offerId }),
640
+ offerId,
641
+ );
642
+ if (!data || !isCurrent()) return false;
643
+ let applied = false;
644
+ const current = await change($, (state) => {
645
+ applied = false;
646
+ const r = state.records.find((r) => r.offerId === offerId);
647
+ if (
648
+ !isCurrent() ||
649
+ !r?.nativeId ||
650
+ (r.workerHandle && r.workerHandle !== data.workerHandle) ||
651
+ (r.generation && r.generation !== data.generation) ||
652
+ (r.activity && r.activity.sequence > data.sequence)
653
+ )
654
+ return;
655
+ r.workerHandle = data.workerHandle;
656
+ r.generation = data.generation;
657
+ r.profile = data.nativeProfile;
658
+ r.activity = data;
659
+ r.inspectionUnavailable = !r.active && ['starting', 'running'].includes(data.state);
660
+ applied = true;
661
+ });
662
+ const r = current?.records.find((r) => r.offerId === offerId);
663
+ if (!current || !r?.nativeId || !applied) return false;
664
+ const alias: Alias = {
665
+ parentSessionId: current.parentSessionId,
666
+ cwd: current.cwd,
667
+ nativeId: r.nativeId,
668
+ workerHandle: data.workerHandle,
669
+ generation: data.generation,
670
+ offerId,
671
+ profile: r.profile,
672
+ ordinal: r.ordinal,
673
+ };
674
+ // Each owned native id retains its small metadata alias until the host's store limit is reached.
675
+ // The bounded UI window must not silently discard across-day continuation identity.
676
+ await $.store.set(await aliasKey(alias.nativeId), alias);
677
+ return true;
678
+ }
679
+
680
+ /**
681
+ * Adds what the CLI reports to the rows the viewer has yet to write. A row is kept
682
+ * by its id as it changes; one already written is never written again.
683
+ */
684
+ function merge(view: View, activity: TenjinModelActivity): void {
685
+ view.sequence = Math.max(view.sequence, activity.sequence);
686
+ for (const row of activity.rows) {
687
+ // A status says only what runs now, which the row in the parent's view says.
688
+ if (row.kind === 'status' || view.shown.has(row.id)) continue;
689
+ const at = view.rows.findIndex((held) => held.id === row.id);
690
+ if (at >= 0) view.rows[at] = row;
691
+ else view.rows.push(row);
692
+ }
693
+ while (view.rows.length > PENDING_ROWS) {
694
+ view.rows.shift();
695
+ view.dropped++;
696
+ }
697
+ }
698
+ /**
699
+ * THE NEXT STEP OF THE VIEWER'S TRANSCRIPT: the worker's next reply whose calls have
700
+ * all ended, its text and calls together, as a native subagent's reply is one step.
701
+ * A reply of text alone goes with the next one, or with the end, since a step with
702
+ * no call would end the viewer's turn.
703
+ */
704
+ function nextReply(view: View): Row[] | undefined {
705
+ const rows = view.rows;
706
+ const key = (row: Row) => row.message ?? row.id;
707
+ for (let from = 0; from < rows.length;) {
708
+ let to = from;
709
+ while (to < rows.length && key(rows[to]!) === key(rows[from]!)) to++;
710
+ const calls = rows.slice(from, to).filter((row) => row.kind === 'tool');
711
+ const ended = to < rows.length || !!view.ended || !calls.some((r) => r.state === 'running');
712
+ if (!ended) return undefined;
713
+ from = to;
714
+ if (calls.some((row) => callOf(row))) return rows.splice(0, from);
715
+ }
716
+ return undefined;
717
+ }
718
+ /** A worker's call as one of the viewer's own tools takes it, or undefined for a line of text. */
719
+ function callOf(row: Row): Json | undefined {
720
+ const given = json(row.inputSummary) ?? {};
721
+ const text = (key: string) => typeof given[key] === 'string';
722
+ if (row.name === 'Bash' && row.command) return { command: row.command };
723
+ // A read is drawn as one only with its line count: `Read 0 lines` would be a wrong figure.
724
+ if (
725
+ row.name === 'Read' &&
726
+ text('file_path') &&
727
+ (row.lines !== undefined || row.state !== 'completed')
728
+ )
729
+ return {
730
+ file_path: given.file_path,
731
+ ...(typeof given.offset === 'number' ? { offset: given.offset } : {}),
732
+ };
733
+ if (row.name === 'Edit' && text('file_path') && text('old_string') && text('new_string'))
734
+ return {
735
+ file_path: given.file_path,
736
+ old_string: given.old_string,
737
+ new_string: given.new_string,
738
+ };
739
+ if (row.name === 'Write' && text('file_path') && text('content'))
740
+ return { file_path: given.file_path, content: given.content };
741
+ // A web call is drawn as one only with its own figures, which its native line reads.
742
+ const known = row.state !== 'completed' || row.figures !== undefined;
743
+ if (row.name === 'WebFetch' && row.target && known)
744
+ return { url: row.target, prompt: text('prompt') ? given.prompt : '' };
745
+ if (row.name === 'WebSearch' && row.target && known) return { query: row.target };
746
+ return undefined;
747
+ }
748
+ /** A web call's figures from the CLI, numbers and a status word only. */
749
+ function figuresOf(given: Json | undefined): { figures?: NonNullable<Row['figures']> } {
750
+ if (!given) return {};
751
+ const figures: NonNullable<Row['figures']> = {};
752
+ for (const key of ['bytes', 'code', 'durationMs', 'searchCount', 'durationSeconds'] as const) {
753
+ const value = given[key];
754
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) figures[key] = value;
755
+ }
756
+ if (typeof given.codeText === 'string') figures.codeText = clean(given.codeText, 64);
757
+ return Object.keys(figures).length ? { figures } : {};
758
+ }
759
+ /**
760
+ * A call's answer, from the worker's row: what Claude Code draws under the call. Never
761
+ * a file's content: a read's line count, a command's first three lines of output (the
762
+ * CLI's already replaced preview), an edit's path. A failed call reads its reason.
763
+ */
764
+ function answerOf(tool: string, row: Row, input: Json): { result: unknown } | { deny: string } {
765
+ if (row.state === 'error') return { deny: clean(row.outputPreview ?? 'Error', 400) };
766
+ if (row.state !== 'completed') return { deny: 'Interrupted' };
767
+ const filePath = String(input.file_path ?? '');
768
+ if (tool === 'Read') {
769
+ const lines = row.lines ?? 0;
770
+ const startLine = typeof input.offset === 'number' ? input.offset : 1;
771
+ return {
772
+ result: {
773
+ type: 'text',
774
+ file: { filePath, content: '', numLines: lines, startLine, totalLines: lines },
775
+ },
776
+ };
777
+ }
778
+ if (tool === 'Bash') {
779
+ const stdout = plain(row.outputPreview ?? '', 2000)
780
+ .split('\n')
781
+ .slice(0, 3)
782
+ .map((line) => clean(line, 400))
783
+ .join('\n');
784
+ return { result: { stdout, stderr: '', interrupted: false } };
785
+ }
786
+ const figures = row.figures ?? {};
787
+ if (tool === 'WebFetch')
788
+ return {
789
+ result: {
790
+ url: String(input.url ?? ''),
791
+ bytes: figures.bytes ?? 0,
792
+ code: figures.code ?? 200,
793
+ codeText: figures.codeText ?? '',
794
+ result: '',
795
+ durationMs: figures.durationMs ?? 0,
796
+ },
797
+ };
798
+ if (tool === 'WebSearch')
799
+ return {
800
+ result: {
801
+ query: String(input.query ?? ''),
802
+ results: [],
803
+ durationSeconds: figures.durationSeconds ?? 0,
804
+ ...(figures.searchCount !== undefined ? { searchCount: figures.searchCount } : {}),
805
+ },
806
+ };
807
+ const patch = { filePath, structuredPatch: [], originalFile: null };
808
+ return tool === 'Edit'
809
+ ? { result: { ...patch, oldString: '', newString: '', userModified: false, replaceAll: false } }
810
+ : { result: { ...patch, type: 'update', content: '' } };
811
+ }
812
+ /** A call of a tool the viewer does not take, as a line of its text: `WebFetch(…)` and what came of it. */
813
+ function callLine(row: Row, cwd: string): string {
814
+ const target = row.command ? clean(row.command, 240) : targetOf(row.inputSummary, cwd);
815
+ const head = '⏺ ' + (row.name ?? 'Tool') + (target ? '(' + target + ')' : '');
816
+ // A read says how much it read, never what: a file's content is never written here.
817
+ const under =
818
+ row.state === 'error'
819
+ ? clean(row.outputPreview ?? 'Error', 400)
820
+ : row.state !== 'completed'
821
+ ? 'Interrupted'
822
+ : row.name === 'Read'
823
+ ? row.lines !== undefined
824
+ ? 'Read ' + row.lines + (row.lines === 1 ? ' line' : ' lines')
825
+ : ''
826
+ : clean(plain(row.outputPreview ?? '', 400).split('\n')[0] ?? '', 160).replace(
827
+ /\*\*|__/g,
828
+ '',
829
+ );
830
+ return '```\n' + (head + (under ? '\n ⎿ ' + under : '')).replaceAll('```', "'''") + '\n```';
831
+ }
832
+ /** Rows as a step's blocks: the worker's text and calls in order, each call with its id. */
833
+ function blocksOf(rows: Row[], cwd: string, view: View) {
834
+ const blocks: ({ text: string } | { id: string; name: string; input: Json })[] = [];
835
+ const say = (text: string) => {
836
+ const last = blocks.at(-1);
837
+ if (last && 'text' in last) last.text += '\n\n' + text;
838
+ else blocks.push({ text });
839
+ };
840
+ if (view.dropped) say(view.dropped + ' earlier events omitted');
841
+ view.dropped = 0;
842
+ for (const row of rows) {
843
+ view.shown.add(row.id);
844
+ const input = row.kind === 'tool' ? callOf(row) : undefined;
845
+ if (input && row.name) {
846
+ const id = CALL_ID + row.id.replace(/[^A-Za-z0-9]/g, '').slice(-24);
847
+ viewerCalls.set(id, { row, input });
848
+ if (viewerCalls.size > 256) viewerCalls.delete(viewerCalls.keys().next().value!);
849
+ if (row.via) servedCalls.set(id, row.via);
850
+ if (servedCalls.size > 512) servedCalls.delete(servedCalls.keys().next().value!);
851
+ blocks.push({ id, name: row.name, input });
852
+ // Claude Code draws no row for a tool search, a native subagent's too.
853
+ } else if (row.kind === 'tool' && row.name !== 'ToolSearch') say(callLine(row, cwd));
854
+ else if (row.text) say(row.text);
855
+ }
856
+ if (view.shown.size > 4096) view.shown.delete(view.shown.values().next().value!);
857
+ return blocks;
858
+ }
859
+
860
+ /** The one input a native row shows for a step: a path, under the session's folder when it is. */
861
+ function targetOf(summary: string | undefined, cwd: string): string | undefined {
862
+ if (!summary) return undefined;
863
+ const fields = json(summary);
864
+ const value = fields
865
+ ? Object.values(fields).find((v) => typeof v === 'string' && v.length > 0 && !v.startsWith('['))
866
+ : /^[[{]/.test(summary)
867
+ ? undefined
868
+ : summary;
869
+ if (typeof value !== 'string') return undefined;
870
+ const shown = Array.from(
871
+ clean(cwd && value.startsWith(cwd + '/') ? value.slice(cwd.length + 1) : value, 400),
872
+ );
873
+ return shown.length <= 48 ? shown.join('') : '…' + shown.slice(-47).join('');
874
+ }
875
+ /** The worker's latest step as a native subagent row names one: `Read(src/a.ts)`. */
876
+ function stepOf(activity: TenjinModelActivity, cwd: string): string | undefined {
877
+ const latest = activity.rows.at(-1);
878
+ if (latest?.kind === 'status' && latest.state === 'running' && latest.text) return latest.text;
879
+ const tool = [...activity.rows].reverse().find((r) => r.kind === 'tool' && r.name);
880
+ if (!tool?.name) return undefined;
881
+ const target = tool.command ? clean(tool.command, 96) : targetOf(tool.inputSummary, cwd);
882
+ return target ? tool.name + '(' + target + ')' : tool.name;
883
+ }
884
+ /** The viewer's band takes the newest activity the live file carried. Display only. */
885
+ async function showActivity($: Dollar, data: TenjinModelActivity): Promise<void> {
886
+ const known = (await $.state.get(STATE)).value?.records.find((r) => r.offerId === data.offerId);
887
+ if (!known || (known.activity && known.activity.sequence >= data.sequence)) return;
888
+ await change($, (state) => {
889
+ const r = state.records.find((r) => r.offerId === data.offerId);
890
+ if (
891
+ !r ||
892
+ (r.workerHandle && r.workerHandle !== data.workerHandle) ||
893
+ (r.generation && r.generation !== data.generation) ||
894
+ (r.activity && r.activity.sequence >= data.sequence)
895
+ )
896
+ return;
897
+ r.workerHandle = data.workerHandle;
898
+ r.generation = data.generation;
899
+ r.profile = data.nativeProfile;
900
+ r.activity = data;
901
+ r.inspectionUnavailable = !r.active && ['starting', 'running'].includes(data.state);
902
+ });
903
+ }
904
+ /**
905
+ * One tick of a running worker's row: its clock, and what the CLI's live file
906
+ * says it has done. A file read, never an MCP call, so it does not wait on the
907
+ * accept call that holds the connection.
908
+ */
909
+ async function pollWorker(
910
+ $: Dollar,
911
+ offerId: string,
912
+ path: string,
913
+ cwd: string,
914
+ ): Promise<TenjinModelActivity | 'missing'> {
915
+ const ref = { ...WORKERS, id: offerId };
916
+ const held = (await $.state.get(ref)).value;
917
+ const now = await $.clock.now();
918
+ let activity: TenjinModelActivity | undefined;
919
+ try {
920
+ activity = activityOf(await $.fs.read(path), offerId);
921
+ } catch {
922
+ // Not written yet, or already removed: the clock still moves.
923
+ }
924
+ const step = activity ? stepOf(activity, cwd) : undefined;
925
+ // A row taken up after a resume that lost its record has no clock of its own.
926
+ const live: TenjinModelWorker | undefined = held && {
927
+ ...held,
928
+ elapsedMs: Math.max(0, now - held.startedAt),
929
+ ...(activity
930
+ ? {
931
+ state: activity.state,
932
+ ...(activity.toolUses !== undefined ? { toolUses: activity.toolUses } : {}),
933
+ ...(activity.tokens !== undefined ? { tokens: activity.tokens } : {}),
934
+ ...(activity.spend ? { spentAtomic: activity.spend.actualAtomic } : {}),
935
+ ...(step ? { current: step } : {}),
936
+ }
937
+ : {}),
938
+ };
939
+ if (live && JSON.stringify(live) !== JSON.stringify(held)) await $.state.set(ref, live);
940
+ if (!activity) return 'missing';
941
+ await showActivity($, activity);
942
+ return activity;
943
+ }
944
+ /** How a worker ended, from the accept call's own answer; undefined when the answer is not one. */
945
+ function endedFrom(answer: Json | undefined): Partial<TenjinModelWorker> | undefined {
946
+ // A worker that stopped with a known cause (`endedBy`) is drawn as one with none.
947
+ const status = answer?.status === 'stopped' ? 'unknown' : answer?.status;
948
+ if (
949
+ status !== 'completed' &&
950
+ status !== 'cancelled' &&
951
+ status !== 'unknown' &&
952
+ status !== 'not_started'
953
+ )
954
+ return undefined;
955
+ const count = (value: unknown) =>
956
+ Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : undefined;
957
+ const spend = record(answer!.spend);
958
+ const actual =
959
+ typeof spend?.actualAtomic === 'string' && /^\d{1,30}$/.test(spend.actualAtomic)
960
+ ? spend.actualAtomic
961
+ : undefined;
962
+ const [uses, used, elapsed] = [answer!.toolUses, answer!.tokens, answer!.elapsedMs].map(count);
963
+ const omitted = count(record(answer!.omitted)?.blocks);
964
+ return {
965
+ ended: status,
966
+ state: status === 'not_started' ? 'unknown' : status,
967
+ ...(endedByOf(answer!.endedBy) ? { endedBy: answer!.endedBy as string } : {}),
968
+ ...(uses !== undefined ? { toolUses: uses } : {}),
969
+ ...(used !== undefined ? { tokens: used } : {}),
970
+ ...(elapsed !== undefined ? { elapsedMs: elapsed } : {}),
971
+ ...(omitted ? { omittedBlocks: omitted } : {}),
972
+ ...(actual !== undefined ? { spentAtomic: actual } : {}),
973
+ ...(Array.isArray(spend?.uncertain) && spend.uncertain.length ? { unresolved: true } : {}),
974
+ };
975
+ }
976
+ /** The same from the CLI's activity, for a call whose answer the host kept for a background task. */
977
+ function endedFromActivity(activity: TenjinModelActivity): Partial<TenjinModelWorker> {
978
+ const state = activity.state as 'completed' | 'cancelled' | 'unknown';
979
+ return {
980
+ ended: activity.started === false && state === 'unknown' ? 'not_started' : state,
981
+ state,
982
+ ...(activity.toolUses !== undefined ? { toolUses: activity.toolUses } : {}),
983
+ ...(activity.tokens !== undefined ? { tokens: activity.tokens } : {}),
984
+ ...(activity.spend ? { spentAtomic: activity.spend.actualAtomic } : {}),
985
+ ...(activity.spend?.uncertain.length ? { unresolved: true } : {}),
986
+ };
987
+ }
988
+ /**
989
+ * How a worker whose accept call no longer answers here ended, once it has: once its
990
+ * display file is gone or says so, the CLI tells, from the job's own record, with the
991
+ * job's own time. A job has no wall time: with no answer the row keeps following.
992
+ */
993
+ async function endedNow(
994
+ $: Dollar,
995
+ offerId: string,
996
+ seen: TenjinModelActivity | 'missing',
997
+ ): Promise<Partial<TenjinModelWorker> | undefined> {
998
+ if (seen !== 'missing' && !ENDED.includes(seen.state)) return undefined;
999
+ let ended: Partial<TenjinModelWorker> | undefined;
1000
+ try {
1001
+ const response = await $.mcp.call(SERVER, 'subagent_activity', { offer_id: offerId });
1002
+ ended = endedFrom(record(body(response)?.ended));
1003
+ const last = activityOf(response, offerId);
1004
+ if (last) {
1005
+ await showActivity($, last);
1006
+ if (!ended && ENDED.includes(last.state)) ended = endedFromActivity(last);
1007
+ }
1008
+ } catch {
1009
+ /* The file's own word still ends the row. */
1010
+ }
1011
+ if (!ended && seen !== 'missing') ended = endedFromActivity(seen);
1012
+ return ended;
1013
+ }
1014
+ /**
1015
+ * A ROW THAT NOTHING HERE FOLLOWS while it reads as running: its accept call began
1016
+ * before a reload, which stops this module's timers, or a resume. It asks the CLI
1017
+ * how the job stands: ended, its end line is written; running, it is followed again.
1018
+ */
1019
+ /**
1020
+ * A follow-up the CLI started in the background from one SendMessage: the accept hook never
1021
+ * sees it, so it gets here what an accepted job gets there. Its viewer is spawned (the
1022
+ * agent-list entry, its activity and its stop control, tied to the calling agent), and the
1023
+ * job is followed to its end, where its result is handed to the parent.
1024
+ */
1025
+ export async function watchContinuation(
1026
+ $: Dollar,
1027
+ offerId: string,
1028
+ caller: string | undefined,
1029
+ ): Promise<void> {
1030
+ const watcher = await watchAccept($, offerId, caller, false);
1031
+ watcher.follow();
1032
+ }
1033
+ async function settle($: Dollar, offerId: string, title: string): Promise<void> {
1034
+ if (liveWorkers.has(offerId)) return;
1035
+ const ref = { ...WORKERS, id: offerId };
1036
+ const [held, path, cwd, now] = await Promise.all([
1037
+ $.state.get(ref),
1038
+ progressPath($, offerId),
1039
+ $.session.cwd(),
1040
+ $.clock.now(),
1041
+ ]);
1042
+ if (held.value?.ended || !path) return;
1043
+ const startedAt = held.value?.startedAt ?? now;
1044
+ liveWorkers.add(offerId);
1045
+ let timer: { cancel(): void } | undefined;
1046
+ let polling = false;
1047
+ const end = async (ended: Partial<TenjinModelWorker>) => {
1048
+ timer?.cancel();
1049
+ try {
1050
+ const current = (await $.state.get(ref)).value;
1051
+ await $.state.set(ref, {
1052
+ ...(current ?? { offerId, title, startedAt, state: 'unknown' }),
1053
+ ...ended,
1054
+ });
1055
+ // A background worker this module took up again after a reload: its result is
1056
+ // still the parent's to get, once.
1057
+ void deliverBackground($, offerId, title);
1058
+ } finally {
1059
+ liveWorkers.delete(offerId);
1060
+ $.ui.invalidate('ui.render');
1061
+ }
1062
+ };
1063
+ try {
1064
+ // Once, whatever the display file says: a file a killed process left still says running.
1065
+ const ended = await endedNow($, offerId, 'missing');
1066
+ if (ended) return await end(ended);
1067
+ timer = $.clock.every(POLL_MS, async () => {
1068
+ if (polling) return;
1069
+ polling = true;
1070
+ try {
1071
+ const ended = await endedNow($, offerId, await pollWorker($, offerId, path, cwd));
1072
+ if (ended) await end(ended);
1073
+ } catch {
1074
+ /* Display only. */
1075
+ } finally {
1076
+ polling = false;
1077
+ }
1078
+ });
1079
+ } catch {
1080
+ liveWorkers.delete(offerId);
1081
+ }
1082
+ }
1083
+ /** Takes up a row once in this module's life, after the drawing that found it. */
1084
+ function adopt($: Dollar, offerId: string, title: string): void {
1085
+ if (adopted.has(offerId) || liveWorkers.has(offerId)) return;
1086
+ adopted.add(offerId);
1087
+ try {
1088
+ $.clock.after(0, () => settle($, offerId, title).catch(() => undefined));
1089
+ } catch {
1090
+ adopted.delete(offerId);
1091
+ }
1092
+ }
1093
+ /** Who or what ended a worker that did not complete, by the CLI's fixed code (`endedBy`). */
1094
+ const ENDED_BY: Record<string, string> = {
1095
+ agent_stopped: 'Stopped by you',
1096
+ parent_cancel: 'Cancelled by the parent',
1097
+ host_aborted: 'Interrupted',
1098
+ session_ended: 'Session ended',
1099
+ budget: 'Budget reached',
1100
+ model_call_failed: 'Model call failed',
1101
+ model_call_timeout: 'Model call timed out',
1102
+ payment_refused: 'Payment refused',
1103
+ provider: 'DeepSeek unavailable',
1104
+ refused: 'DeepSeek refused',
1105
+ worker_error: 'Stopped',
1106
+ };
1107
+ function endedByOf(code: unknown): code is string {
1108
+ return typeof code === 'string' && Object.hasOwn(ENDED_BY, code);
1109
+ }
1110
+ /**
1111
+ * The end word of a worker that did not complete: from the job's end code, which a read
1112
+ * carries once the job's record holds its handback, and from its state until then.
1113
+ */
1114
+ function stopWord(status: unknown, endedBy: unknown): string {
1115
+ if (endedByOf(endedBy)) return ENDED_BY[endedBy]!;
1116
+ return status === 'cancelled' ? 'Interrupted' : 'Stopped';
1117
+ }
1118
+ /** The end row's part for the image and document blocks the worker did not see. */
1119
+ function omittedWords(blocks: number): string {
1120
+ return `${blocks} image or document ${blocks === 1 ? 'block' : 'blocks'} omitted`;
1121
+ }
1122
+ type WorkerEnding = { word: string; parts: string[] };
1123
+
1124
+ function endingText({ word, parts }: WorkerEnding): string {
1125
+ return word + (parts.length ? ' (' + parts.join(' · ') + ')' : '');
1126
+ }
1127
+
1128
+ function workerEnding(live: TenjinModelWorker): WorkerEnding {
1129
+ const time = live.elapsedMs !== undefined ? [duration(live.elapsedMs)] : [];
1130
+ if (live.ended === 'not_started') return { word: 'Not started', parts: time };
1131
+ const word = live.ended === 'completed' ? 'Done' : stopWord(live.ended, live.endedBy);
1132
+ const parts = [
1133
+ ...(live.toolUses !== undefined || time.length ? [toolUses(live.toolUses ?? 0)] : []),
1134
+ ...(live.tokens !== undefined ? [tokens(live.tokens)] : []),
1135
+ ...time,
1136
+ ...(live.spentAtomic !== undefined
1137
+ ? [dollars(live.spentAtomic) + (live.unresolved ? ' · settlement unresolved' : '')]
1138
+ : []),
1139
+ ...(live.omittedBlocks ? [omittedWords(live.omittedBlocks)] : []),
1140
+ ];
1141
+ return { word, parts };
1142
+ }
1143
+
1144
+ function displayPreview(message: string, content: string): boolean {
1145
+ if (content === message) return true;
1146
+ if (!content.endsWith('…')) return false;
1147
+ const prefix = content.slice(0, -1);
1148
+ if (!prefix || prefix.length >= message.length || !message.startsWith(prefix)) return false;
1149
+ // Native Claude truncates display width at a grapheme boundary. The preview
1150
+ // carries no task authority; accept only an unchanged prefix of the full message.
1151
+ for (const part of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(message)) {
1152
+ const end = part.index + part.segment.length;
1153
+ if (end >= prefix.length) return end === prefix.length;
1154
+ }
1155
+ return false;
1156
+ }
1157
+ function claudeMessageInput(input: Json, recipientKind: 'agent' | 'name'): Json | undefined {
1158
+ const modern = input.to !== undefined && input.message !== undefined;
1159
+ const observable =
1160
+ ['type', 'recipient_kind', 'request_id', 'approve'].some((key) => key in input) ||
1161
+ (modern && (input.recipient !== undefined || input.content !== undefined));
1162
+ if (!observable) {
1163
+ const addresses = [input.to, input.recipient].filter((value) => value !== undefined);
1164
+ return addresses.length === 1 && (!Array.isArray(addresses[0]) || addresses[0].length === 1)
1165
+ ? input
1166
+ : undefined;
1167
+ }
1168
+ if (
1169
+ Array.isArray(input.to) ||
1170
+ Array.isArray(input.recipient) ||
1171
+ !modern ||
1172
+ typeof input.to !== 'string' ||
1173
+ typeof input.message !== 'string' ||
1174
+ new TextEncoder().encode(input.message).length > 128_000 ||
1175
+ input.type !== 'message' ||
1176
+ input.recipient !== input.to ||
1177
+ input.recipient_kind !== recipientKind ||
1178
+ typeof input.content !== 'string' ||
1179
+ !displayPreview(input.message, input.content) ||
1180
+ Object.keys(input).some(
1181
+ (key) =>
1182
+ ![
1183
+ 'to',
1184
+ 'message',
1185
+ 'summary',
1186
+ 'notify_when_idle',
1187
+ 'type',
1188
+ 'recipient',
1189
+ 'recipient_kind',
1190
+ 'content',
1191
+ ].includes(key),
1192
+ )
1193
+ )
1194
+ return undefined;
1195
+ // Claude 2.1.325 backfills this complete tuple for display while retaining
1196
+ // modern to/message. The strict backend still receives one address and full task.
1197
+ const canonical = { ...input };
1198
+ for (const key of ['type', 'recipient', 'recipient_kind', 'content']) delete canonical[key];
1199
+ return canonical;
1200
+ }
1201
+
1202
+ /** Alias resolution supplies identity only; the existing capture still owns veto, scope and execution. */
1203
+ export async function translateViewerContinuation(
1204
+ $: Dollar,
1205
+ tool: string,
1206
+ input: Json,
1207
+ ): Promise<{ input: Json; owned: boolean; unavailable?: boolean }> {
1208
+ let known = false;
1209
+ let targets: unknown[] = [];
1210
+ try {
1211
+ const fields = tool === 'SendMessage' ? ['to', 'recipient'] : ['resume'];
1212
+ let addresses = fields.filter((key) => input[key] !== undefined);
1213
+ targets = addresses.flatMap((key) =>
1214
+ Array.isArray(input[key]) ? (input[key] as unknown[]) : [input[key]],
1215
+ );
1216
+ if (
1217
+ tool === 'SendMessage' &&
1218
+ targets.some((target) => typeof target === 'string' && WORKER.test(target))
1219
+ ) {
1220
+ known = true;
1221
+ const canonical = claudeMessageInput(input, 'name');
1222
+ if (!canonical) return { input, owned: true, unavailable: true };
1223
+ input = canonical;
1224
+ addresses = fields.filter((key) => input[key] !== undefined);
1225
+ targets = addresses.flatMap((key) =>
1226
+ Array.isArray(input[key]) ? (input[key] as unknown[]) : [input[key]],
1227
+ );
1228
+ }
1229
+ if (
1230
+ addresses.length === 0 ||
1231
+ targets.every((target) => typeof target === 'string' && WORKER.test(target))
1232
+ )
1233
+ return { input, owned: false };
1234
+ const aliases = (
1235
+ await Promise.all(targets.slice(0, 16).map((target) => readAlias($, target)))
1236
+ ).filter((a): a is Alias => !!a);
1237
+ known = aliases.length > 0;
1238
+ if (!known) {
1239
+ const own = (await $.agent.list()).some((a) => targets.includes(a.id) && a.type === TYPE);
1240
+ return { input, owned: own, ...(own ? { unavailable: true } : {}) };
1241
+ }
1242
+ if (tool === 'SendMessage') {
1243
+ const canonical = claudeMessageInput(input, 'agent');
1244
+ if (!canonical) return { input, owned: true, unavailable: true };
1245
+ input = canonical;
1246
+ addresses = fields.filter((key) => input[key] !== undefined);
1247
+ targets = addresses.flatMap((key) =>
1248
+ Array.isArray(input[key]) ? (input[key] as unknown[]) : [input[key]],
1249
+ );
1250
+ }
1251
+ const owner = await scope($),
1252
+ alias = aliases.find((a) => a.nativeId === targets[0]);
1253
+ if (
1254
+ !owner ||
1255
+ !alias ||
1256
+ addresses.length !== 1 ||
1257
+ targets.length !== 1 ||
1258
+ aliases.some((a) => a.nativeId !== alias.nativeId) ||
1259
+ alias.parentSessionId !== owner.parentSessionId ||
1260
+ alias.cwd !== owner.cwd ||
1261
+ (tool !== 'SendMessage' &&
1262
+ input.subagent_type !== undefined &&
1263
+ input.subagent_type !== alias.profile)
1264
+ )
1265
+ return { input, owned: true, unavailable: true };
1266
+ const key = addresses[0]!;
1267
+ return {
1268
+ input: {
1269
+ ...input,
1270
+ [key]: Array.isArray(input[key]) ? [alias.workerHandle] : alias.workerHandle,
1271
+ ...(tool !== 'SendMessage' && input.subagent_type === undefined
1272
+ ? { subagent_type: alias.profile }
1273
+ : {}),
1274
+ },
1275
+ owned: true,
1276
+ };
1277
+ } catch {
1278
+ // A failed metadata store must not skip the independent native-type guard.
1279
+ try {
1280
+ known ||= (await $.agent.list()).some((a) => targets.includes(a.id) && a.type === TYPE);
1281
+ } catch {
1282
+ /* The deny-only tag below can still identify a previously observed native viewer. */
1283
+ }
1284
+ for (const target of targets.slice(0, 16))
1285
+ if (typeof target === 'string') known ||= await knownViewer($, target).catch(() => false);
1286
+ return { input, owned: known, ...(known ? { unavailable: true } : {}) };
1287
+ }
1288
+ }
1289
+
1290
+ async function identify(
1291
+ $: Dollar,
1292
+ agentId: string,
1293
+ turnId?: string,
1294
+ ): Promise<{ item: TenjinModelViewerRecord } | undefined> {
1295
+ const native = (await $.agent.list()).find((a) => a.id === agentId);
1296
+ if (!native || native.type !== TYPE || native.spawnedBy !== 'tenjin') return;
1297
+ let matched = false;
1298
+ const current = await change($, (state) => {
1299
+ matched = false;
1300
+ const matches = state.records.filter(
1301
+ (r) =>
1302
+ (r.active || (r.nativeId === agentId && !!turnId && r.turnId === turnId)) &&
1303
+ r.description === native.description &&
1304
+ // Under the agent that accepted, or under the main loop where the host does not
1305
+ // place a plugin's agent under another (before 2.1.326).
1306
+ (native.parentId === undefined || r.parentId === native.parentId) &&
1307
+ (!r.nativeId || r.nativeId === agentId) &&
1308
+ (!turnId || !r.turnId || r.turnId === turnId),
1309
+ );
1310
+ if (matches.length !== 1) return;
1311
+ const item = matches[0]!;
1312
+ item.nativeId = agentId;
1313
+ if (turnId) item.turnId = turnId;
1314
+ matched = true;
1315
+ });
1316
+ const item = current?.records.find((r) => r.nativeId === agentId);
1317
+ return matched && item ? { item } : undefined;
1318
+ }
1319
+ async function knownViewer($: Dollar, agentId: string): Promise<boolean> {
1320
+ // This is a deny-only type guard, not job authority. A lost cwd must not erase a known guard.
1321
+ const state = (await $.state.get(STATE)).value;
1322
+ return (
1323
+ !!state &&
1324
+ (state.knownIds.includes(agentId) ||
1325
+ state.records.some((r) => r.nativeId === agentId) ||
1326
+ !!state.priorStops?.some((r) => r.nativeId === agentId))
1327
+ );
1328
+ }
1329
+ async function* finish(
1330
+ e: TurnStepInput,
1331
+ answer: string,
1332
+ ): AsyncGenerator<TurnStepChunk, TurnStepResult> {
1333
+ if (answer) yield { kind: 'text', index: 0, text: answer };
1334
+ yield { kind: 'stop', stopReason: 'end_turn', usage: null };
1335
+ return {
1336
+ turnId: e.turnId,
1337
+ index: e.index,
1338
+ answer,
1339
+ toolUses: [],
1340
+ stopReason: 'end_turn',
1341
+ usage: null,
1342
+ };
1343
+ }
1344
+ /**
1345
+ * ONE STEP OF A VIEWER'S TRANSCRIPT: the worker's next reply, made up here, its calls
1346
+ * answered by the `tool.call` hook. It waits for that reply with follow reads that
1347
+ * wake when the activity moves (`after`); past its bound it ends empty and its stop
1348
+ * is held, so the next step follows on. Once the worker ended and its replies are
1349
+ * written, the last step writes its answer and end line.
1350
+ */
1351
+ async function* viewerStep(
1352
+ $: Dollar,
1353
+ e: TurnStepInput,
1354
+ agentId: string,
1355
+ item: TenjinModelViewerRecord,
1356
+ view: View,
1357
+ ): AsyncGenerator<TurnStepChunk, TurnStepResult> {
1358
+ const cwd = (await $.state.get(STATE)).value?.cwd ?? '';
1359
+ const stepStart = await $.clock.now();
1360
+ try {
1361
+ let quick = 0;
1362
+ // Bound by the step's time alone: a long command wakes the read each second it runs.
1363
+ for (;;) {
1364
+ const reply = nextReply(view);
1365
+ if (reply) {
1366
+ view.holds = 0;
1367
+ const blocks = blocksOf(reply, cwd, view);
1368
+ for (const [index, block] of blocks.entries()) {
1369
+ if ('text' in block) yield { kind: 'text', index, text: block.text };
1370
+ else {
1371
+ yield { kind: 'tool', index, id: block.id, name: block.name };
1372
+ yield { kind: 'input', index, json: JSON.stringify(block.input) };
1373
+ }
1374
+ }
1375
+ yield { kind: 'stop', stopReason: 'tool_use', usage: null };
1376
+ return {
1377
+ turnId: e.turnId,
1378
+ index: e.index,
1379
+ answer: blocks.flatMap((b) => ('text' in b ? [b.text] : [])).join('\n\n'),
1380
+ toolUses: blocks.flatMap((b) => ('id' in b ? [{ name: b.name, input: b.input }] : [])),
1381
+ stopReason: 'tool_use',
1382
+ usage: null,
1383
+ };
1384
+ }
1385
+ if (view.ended) {
1386
+ view.done = true;
1387
+ return yield* finish(e, await endOf($, item, view, cwd));
1388
+ }
1389
+ const before = await $.clock.now();
1390
+ if (before - stepStart >= STEP_MS) {
1391
+ // Ended here, before the host's ten-minute bound, with the stop held once.
1392
+ if (view.holds++ >= MAX_HOLDS) break;
1393
+ handedOver.add(agentId);
1394
+ return yield* finish(e, '');
1395
+ }
1396
+ const response = await $.mcp.call(SERVER, 'subagent_activity', {
1397
+ offer_id: view.offerId,
1398
+ follow: true,
1399
+ after: view.sequence,
1400
+ });
1401
+ if (response.isError) break;
1402
+ const value = body(response);
1403
+ const data = activityOf(response, view.offerId);
1404
+ const seen = view.sequence;
1405
+ if (data) merge(view, data);
1406
+ if (value?.status === 'ended' || (data && ENDED.includes(data.state))) {
1407
+ view.ended = { ...data, ...record(value?.ended) };
1408
+ try {
1409
+ // The run is over, so this read returns at once: its last rows and its answer.
1410
+ const last = await $.mcp.call(SERVER, 'subagent_activity', { offer_id: view.offerId });
1411
+ const final = activityOf(last, view.offerId);
1412
+ if (final) merge(view, final);
1413
+ const result = record(body(last)?.activity)?.result;
1414
+ view.ended = {
1415
+ ...view.ended,
1416
+ ...record(body(last)?.ended),
1417
+ ...(typeof result === 'string' && result.trim()
1418
+ ? { answer: plain(result, RESULT_CHARS) }
1419
+ : {}),
1420
+ };
1421
+ } catch {
1422
+ /* The rows read while it ran, and how it ended, still stand. */
1423
+ }
1424
+ continue;
1425
+ } else if (!data && value?.status !== 'waiting') break;
1426
+ // A read that did not wait and saw nothing new must not spin: a few short pauses.
1427
+ if (view.sequence === seen && (await $.clock.now()) - before < 1000) {
1428
+ if (++quick > 5) break;
1429
+ await $.clock.sleep(1000);
1430
+ }
1431
+ }
1432
+ } catch {
1433
+ /* An observer error never cancels, retries or replaces the actual worker. */
1434
+ }
1435
+ return yield* finish(
1436
+ e,
1437
+ 'Activity unavailable. The worker result is returned separately to the parent.',
1438
+ );
1439
+ }
1440
+ function dollars(atomic: string): string {
1441
+ const padded = atomic.padStart(7, '0');
1442
+ // Whole cents keep two places: `$1.00`, `$0.0043`.
1443
+ const fraction = padded.slice(-6).replace(/0+$/, '').padEnd(2, '0');
1444
+ return '$' + padded.slice(0, -6) + '.' + fraction;
1445
+ }
1446
+ /** Counts as a native subagent row writes them: `12 tool uses`, `41.2k tokens`, `2m 13s`. */
1447
+ function toolUses(count: number): string {
1448
+ return count + (count === 1 ? ' tool use' : ' tool uses');
1449
+ }
1450
+ function tokens(count: number): string {
1451
+ const compact = (value: number, unit: string) =>
1452
+ (Math.floor(value * 10) / 10).toFixed(1).replace(/\.0$/, '') + unit;
1453
+ return (
1454
+ (count < 1000
1455
+ ? String(count)
1456
+ : count < 1_000_000
1457
+ ? compact(count / 1000, 'k')
1458
+ : compact(count / 1_000_000, 'm')) + ' tokens'
1459
+ );
1460
+ }
1461
+ function duration(ms: number): string {
1462
+ const seconds = Math.floor(Math.max(0, ms) / 1000);
1463
+ if (seconds < 60) return seconds + 's';
1464
+ const minutes = Math.floor(seconds / 60);
1465
+ if (minutes < 60) return minutes + 'm ' + (seconds % 60) + 's';
1466
+ return Math.floor(minutes / 60) + 'h ' + (minutes % 60) + 'm';
1467
+ }
1468
+ function displayState(item: TenjinModelViewerRecord): string {
1469
+ return item.inspectionUnavailable
1470
+ ? 'activity unavailable'
1471
+ : (item.activity?.state ?? 'activity unavailable');
1472
+ }
1473
+
1474
+ /**
1475
+ * An accept call whose input does not yet say what it is: the model is still writing
1476
+ * it. A cancel and a capture name themselves by their own field.
1477
+ */
1478
+ function undecided(input: unknown): boolean {
1479
+ const given = record(input) ?? {};
1480
+ if (!['offer_id', 'offer_ids', 'cancel', 'capture'].some((key) => given[key] !== undefined))
1481
+ return true;
1482
+ // ITS OFFER ID STILL STREAMING: the host draws the input as it arrives, so for that
1483
+ // moment the call holds part of an id (live on alpha.64: the host's own
1484
+ // `plugin:tenjin:router` row stood between the offer row and the DeepSeek row).
1485
+ const partial = (id: unknown): boolean =>
1486
+ typeof id === 'string' && !UUID.test(id) && /^[0-9a-f-]{0,35}$/i.test(id);
1487
+ if (Object.keys(given).length !== 1) return false;
1488
+ // A cancel's id streams in the same way.
1489
+ if (partial(given.offer_id) || partial(given.cancel)) return true;
1490
+ const ids = given.offer_ids;
1491
+ return (
1492
+ Array.isArray(ids) &&
1493
+ (ids.length < 2 || ids.some(partial)) &&
1494
+ ids.every((id) => (short(id) && UUID.test(id)) || partial(id))
1495
+ );
1496
+ }
1497
+
1498
+ /** A cancel of one offer by its id, as the model writes it: the offer's id. */
1499
+ function cancelOf(input: unknown): string | undefined {
1500
+ const given = record(input);
1501
+ const id = given?.cancel;
1502
+ return given && Object.keys(given).length === 1 && short(id) && UUID.test(id) ? id : undefined;
1503
+ }
1504
+ /** The CLI's answer to a cancel that took: nothing but its status. */
1505
+ function cancelAnswer(answer: Json | undefined): boolean {
1506
+ return answer?.status === 'cancelled' && Object.keys(answer).length === 1;
1507
+ }
1508
+
1509
+ function acceptedIds(input: unknown, withMetadata = false): string[] | undefined {
1510
+ const given = record(input);
1511
+ if (!given) return undefined;
1512
+ const keys = Object.keys(given).filter(
1513
+ (key) => !withMetadata || !['tool', 'tool_use_id', 'agentId', 'requestMeta'].includes(key),
1514
+ );
1515
+ if (keys.length !== 1) return undefined;
1516
+ if (keys[0] === 'offer_id' && short(given.offer_id) && UUID.test(given.offer_id))
1517
+ return [given.offer_id];
1518
+ const ids = given.offer_ids;
1519
+ if (
1520
+ keys[0] === 'offer_ids' &&
1521
+ Array.isArray(ids) &&
1522
+ ids.length >= 2 &&
1523
+ ids.every((id): id is string => short(id) && UUID.test(id)) &&
1524
+ new Set(ids.map((id) => id.toLowerCase())).size === ids.length
1525
+ )
1526
+ return ids;
1527
+ }
1528
+
1529
+ function acceptResponse(text: string | undefined): Json | undefined {
1530
+ // A combined handback can exceed a single report. The router writes this envelope
1531
+ // as compact JSON. Keep any host result-file notice visible as received.
1532
+ return json(text, text?.startsWith('{"results":[') ? text.length : undefined);
1533
+ }
1534
+
1535
+ function batchOutcomes(answer: Json | undefined): Map<string, Json> | undefined {
1536
+ if (!Array.isArray(answer?.results) || answer.results.length < 2) return undefined;
1537
+ const outcomes = new Map<string, Json>();
1538
+ for (const entry of answer.results) {
1539
+ const item = record(entry);
1540
+ const id = item?.offer_id;
1541
+ const outcome = record(item?.outcome);
1542
+ if (!short(id) || !UUID.test(id) || !outcome || outcomes.has(id)) return undefined;
1543
+ outcomes.set(id, outcome);
1544
+ }
1545
+ return outcomes;
1546
+ }
1547
+ /**
1548
+ * The accept calls a person's permission settings never ask about, as the plugin's
1549
+ * allow leg answered them before (it ran for each, and the host drew its run): the
1550
+ * model's accept or cancel of an offer by its id, and this plugin's own capture. Any
1551
+ * other input gets the host's own verdict; the CLI still checks the offer is this
1552
+ * session's own.
1553
+ */
1554
+ function allowedAccept(input: unknown, ownCall: boolean): boolean {
1555
+ const given = record(input);
1556
+ const keys = given ? Object.keys(given) : [];
1557
+ // Its own capture, and its own read of an ended background worker's stored result.
1558
+ if (ownCall)
1559
+ return keys.length === 1 && (record(given?.capture) !== undefined || !!acceptedIds(input));
1560
+ const id = keys.length === 1 ? given?.[keys[0]!] : undefined;
1561
+ return !!acceptedIds(input) || (keys[0] === 'cancel' && short(id) && UUID.test(id));
1562
+ }
1563
+
1564
+ /**
1565
+ * A BACKGROUND WORKER'S RESULT REACHES THE PARENT AS A PROMPT OF THIS PLUGIN, once the
1566
+ * worker has ended. Its accept call answered at once, so nothing else carries it: Claude
1567
+ * Code gives a plugin's own agent (the viewer) no completion notice in any mode (2.1.327
1568
+ * marks it notified at launch), and no call asks the host to move an MCP call to the
1569
+ * background at once. `$.prompt.submit` queues behind a running turn and starts a turn of
1570
+ * its own when the session is idle, as a background agent's notice does.
1571
+ *
1572
+ * What is handed over is the job's stored handback, read by the accept of an ended offer,
1573
+ * which starts nothing and charges nothing. Once per offer: the record says so, also
1574
+ * after a reload.
1575
+ */
1576
+ const BACKGROUND_RESULT = 'DeepSeek background worker';
1577
+ /**
1578
+ * Results whose prompt the host did not take, by offer, with the task's title. The host
1579
+ * refuses a prompt submitted while a `tool.call` hook of this plugin holds the turn (a
1580
+ * batch's accept call waiting for its foreground workers): it is sent again when that
1581
+ * call has returned, and when the main loop's turn completes.
1582
+ */
1583
+ const undelivered = new Map<string, string>();
1584
+ function deliverLater($: Dollar): void {
1585
+ for (const [offerId, title] of [...undelivered]) void deliverBackground($, offerId, title);
1586
+ }
1587
+ /** That prompt's first line, as its row reads it, bare or under the host's frame for a plugin's prompt. */
1588
+ const BACKGROUND_ROW =
1589
+ /DeepSeek background worker "[^"\n]{0,80}" \(offer [0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\) /i;
1590
+ const delivering = new Set<string>();
1591
+ /** How long a read waits for the CLI to store an ended job's handback, at most. */
1592
+ const HANDBACK_READS = 20;
1593
+ async function deliverBackground($: Dollar, offerId: string, title: string): Promise<void> {
1594
+ if (sessionEnding || delivering.has(offerId)) return;
1595
+ delivering.add(offerId);
1596
+ try {
1597
+ const ref = { ...OFFERS, id: offerId };
1598
+ const offer = (await $.state.get(ref)).value;
1599
+ if (!offer?.background || offer.delivered) return;
1600
+ let handback: string | undefined;
1601
+ for (let read = 0; read < HANDBACK_READS && !handback; read++) {
1602
+ const said = textOf(await $.mcp.call(SERVER, 'subagent', { offer_id: offerId }));
1603
+ // Still closing: its record is written a moment after its display says it ended.
1604
+ if (said && !startedNothing(said) && !startedInBackground(acceptResponse(said)))
1605
+ handback = said;
1606
+ else await $.clock.sleep(500);
1607
+ }
1608
+ // HOW IT ENDED COMES FIRST, in the job's own words: a worker the parent cancelled says
1609
+ // so before anything else, so its late message is not read as new work.
1610
+ const answer = acceptResponse(handback);
1611
+ const how =
1612
+ answer?.status === 'completed'
1613
+ ? 'finished.'
1614
+ : typeof answer?.ended === 'string' && answer.ended.trim()
1615
+ ? 'did not complete: ' + clean(answer.ended, 200).replace(/[.]?$/, '.')
1616
+ : 'ended.';
1617
+ await $.prompt.submit({
1618
+ text:
1619
+ `${BACKGROUND_RESULT} "${title}" (offer ${offerId}) ${how} This is the result of the background subagent call you accepted earlier, as a background agent's result arrives: it is not a new task, nothing new started and nothing more was charged.\n` +
1620
+ (handback ??
1621
+ '{"status":"unknown","nextStep":"Its result could not be read here. Accept this offer again with subagent({offer_id}) to read the stored result; that starts no worker."}'),
1622
+ });
1623
+ undelivered.delete(offerId);
1624
+ const current = (await $.state.get(ref)).value;
1625
+ if (current) await $.state.set(ref, { ...current, delivered: true });
1626
+ } catch {
1627
+ // Sent again from a later event. The stored result stays too: accepting the offer
1628
+ // again returns it.
1629
+ undelivered.delete(offerId);
1630
+ undelivered.set(offerId, title);
1631
+ if (undelivered.size > 64) undelivered.delete(undelivered.keys().next().value!);
1632
+ } finally {
1633
+ delivering.delete(offerId);
1634
+ }
1635
+ }
1636
+
1637
+ /** How long the session's end waits for its cancels to be taken, at most. */
1638
+ const SESSION_END_WAIT_MS = 1500;
1639
+ /**
1640
+ * THE SESSION'S END ENDS ITS BACKGROUND WORKERS. A foreground worker ends with its accept
1641
+ * call. A background worker is tied to the Tenjin process alone, which the host may keep
1642
+ * across `/clear`: it would run on and spend up to its cap, for a session that can no
1643
+ * longer be handed its result. Each offer of a background call whose result was not
1644
+ * handed over is cancelled by its own id, with the reason its record keeps. An ended
1645
+ * job's cancel changes nothing, and its stored result stays readable on a resume.
1646
+ */
1647
+ async function endBackgroundWorkers($: Dollar, closed: string | undefined): Promise<void> {
1648
+ const ids = new Set<string>([...liveWorkers, ...undelivered.keys()]);
1649
+ try {
1650
+ for (const record of (await $.state.get(STATE)).value?.records ?? []) ids.add(record.offerId);
1651
+ } catch {
1652
+ /* The workers this module follows are still named. */
1653
+ }
1654
+ const cancels = [...ids].map(async (offerId) => {
1655
+ try {
1656
+ const offer = (await $.state.get({ ...OFFERS, id: offerId })).value;
1657
+ if (
1658
+ !offer?.background ||
1659
+ offer.delivered ||
1660
+ offer.state === 'native' ||
1661
+ offer.state === 'cancelled'
1662
+ )
1663
+ return;
1664
+ await $.mcp.call(SERVER, 'subagent', { cancel: offerId, reason: 'session_ended' });
1665
+ } catch {
1666
+ /* The Tenjin process ends its own workers when it stops. */
1667
+ }
1668
+ });
1669
+ // THE CLI IS TOLD THE SESSION CLOSED, after the cancels: it ends what this module did
1670
+ // not know of (a worker warming for an open offer) and drops its record of the session,
1671
+ // so that the next session of this Claude Code is taken up and gets offers.
1672
+ const told = (async () => {
1673
+ await Promise.allSettled(cancels);
1674
+ try {
1675
+ await $.mcp.call(SERVER, 'subagent', { end_session: closed ?? (await $.session.id()) });
1676
+ } catch {
1677
+ /* The Tenjin process ends its own workers when it stops. */
1678
+ }
1679
+ })();
1680
+ await Promise.race([told, $.clock.sleep(SESSION_END_WAIT_MS)]);
1681
+ }
1682
+
1683
+ async function watchAccept(
1684
+ $: Dollar,
1685
+ offerId: string,
1686
+ caller: string | undefined,
1687
+ batched: boolean,
1688
+ ) {
1689
+ let timer: { cancel(): void } | undefined;
1690
+ let binding: ViewerBinding | undefined;
1691
+ let spawned: Promise<void> | undefined;
1692
+ let polling = false,
1693
+ closed = false,
1694
+ prepared = false,
1695
+ viewerStarted = false,
1696
+ background = false,
1697
+ stopped = false,
1698
+ observed = false;
1699
+ // THE END OF THE LIVE DISPLAY, once: with the accept call's own answer, or,
1700
+ // for a call the host moved to the background, when the CLI says the worker ended.
1701
+ const stop = (ended?: Partial<TenjinModelWorker>) => {
1702
+ if (stopped) return;
1703
+ stopped = true;
1704
+ closed = true;
1705
+ try {
1706
+ timer?.cancel();
1707
+ } catch {
1708
+ /* Timer failures do not rewrite the handback. */
1709
+ }
1710
+ try {
1711
+ // UI I/O cannot delay or replace the original worker result, even when inspect hangs.
1712
+ $.clock.after(0, async () => {
1713
+ try {
1714
+ if (ended) {
1715
+ const ref = { ...WORKERS, id: offerId };
1716
+ const held = (await $.state.get(ref)).value;
1717
+ if (held) await $.state.set(ref, { ...held, ...ended });
1718
+ }
1719
+ } catch {
1720
+ /* The row then ends from the call's own answer. */
1721
+ }
1722
+ // Followed here no more once its end is written, so no drawing takes it for a
1723
+ // row that a reload left behind.
1724
+ if (liveWorkers.delete(offerId)) $.ui.invalidate('ui.render');
1725
+ // A background worker's result goes to the parent now, whichever came first: its
1726
+ // end, or its accept call's answer (a batch holds that until its foreground
1727
+ // workers end). `deliverBackground` sends nothing for a foreground offer.
1728
+ if (ended) {
1729
+ const title = (await $.state.get({ ...WORKERS, id: offerId }).catch(() => undefined))
1730
+ ?.value?.title;
1731
+ void deliverBackground($, offerId, title ?? 'subagent');
1732
+ }
1733
+ try {
1734
+ if (!prepared) return;
1735
+ // A viewer still starting binds to its running record before it retires.
1736
+ if (spawned && !viewerStarted)
1737
+ await Promise.race([spawned, $.clock.sleep(SPAWN_WAIT_MS)]);
1738
+ if (binding) await retireViewer($, binding);
1739
+ await refresh($, offerId);
1740
+ } catch {
1741
+ /* The last confirmed rows remain visibly marked unavailable. */
1742
+ }
1743
+ });
1744
+ } catch {
1745
+ /* Preserve the exact original acceptance outcome. */
1746
+ liveWorkers.delete(offerId);
1747
+ }
1748
+ };
1749
+ if (await enabled($).catch(() => false)) {
1750
+ // THE LIVE ROW comes first and stands alone: it reads the CLI's own activity
1751
+ // file, so it needs neither the viewer, nor its bookkeeping below, nor a
1752
+ // second call on this connection. Followed here before its record is written.
1753
+ liveWorkers.delete(offerId);
1754
+ liveWorkers.add(offerId);
1755
+ try {
1756
+ const known = (await $.state.get(STATE)).value?.records.find((r) => r.offerId === offerId);
1757
+ await $.state.set(
1758
+ { ...WORKERS, id: offerId },
1759
+ {
1760
+ offerId,
1761
+ title: known?.title ?? 'subagent',
1762
+ startedAt: await $.clock.now(),
1763
+ elapsedMs: 0,
1764
+ state: 'starting',
1765
+ },
1766
+ );
1767
+ } catch {
1768
+ /* The row then draws without its title or clock. */
1769
+ }
1770
+ try {
1771
+ $.ui.invalidate('ui.render');
1772
+ const [path, cwd] = await Promise.all([progressPath($, offerId), $.session.cwd()]);
1773
+ if (path)
1774
+ timer = $.clock.every(POLL_MS, async () => {
1775
+ if (closed || polling) return;
1776
+ polling = true;
1777
+ try {
1778
+ const seen = await pollWorker($, offerId, path, cwd);
1779
+ observed ||= seen !== 'missing';
1780
+ if (stopped || (!background && !(batched && observed))) return;
1781
+ const ended = await endedNow($, offerId, seen);
1782
+ if (ended) stop(ended);
1783
+ } catch {
1784
+ /* Display only. */
1785
+ } finally {
1786
+ polling = false;
1787
+ }
1788
+ });
1789
+ } catch {
1790
+ /* Display only. */
1791
+ }
1792
+ try {
1793
+ const current = await change($, (state) => {
1794
+ prepared = false;
1795
+ const item = state.records.find((r) => r.offerId === offerId);
1796
+ if (
1797
+ !item ||
1798
+ item.active ||
1799
+ item.nativeId ||
1800
+ state.priorStops?.some((r) => r.offerId === offerId) ||
1801
+ (state.priorStops?.length ?? 0) + state.records.filter((r) => r.active).length >= 16
1802
+ )
1803
+ return;
1804
+ item.active = true;
1805
+ // The viewer is listed under the agent that accepted, as its own subagent is.
1806
+ if (caller !== undefined) item.parentId = caller;
1807
+ else delete item.parentId;
1808
+ prepared = true;
1809
+ });
1810
+ const item = current?.records.find((r) => r.offerId === offerId);
1811
+ if (current && item && prepared)
1812
+ binding = {
1813
+ parentSessionId: current.parentSessionId,
1814
+ cwd: current.cwd,
1815
+ offerId: item.offerId,
1816
+ };
1817
+ if (current && item && prepared && liveViewerGuards.size + pendingViewerSpawns < 16) {
1818
+ // Count the pending spawn until it returns, even after classic-start tags its id.
1819
+ pendingViewerSpawns++;
1820
+ // NOT AWAITED: the worker never waits for its viewer to start.
1821
+ spawned = (async () => {
1822
+ try {
1823
+ const viewer = await $.agent.spawn({
1824
+ subagentType: TYPE,
1825
+ ...(caller !== undefined ? { parentAgentId: caller } : {}),
1826
+ description: item.description,
1827
+ prompt: VIEWER_PROMPT + ' ' + offerId + ' ' + item.description,
1828
+ cwd: current.cwd,
1829
+ });
1830
+ if (viewer.agentId) {
1831
+ const nativeId = viewer.agentId;
1832
+ if ((await $.session.id()) !== current.parentSessionId) return;
1833
+ await update($, STATE, (held) => {
1834
+ if (!held) throw new Error('Activity binding unavailable');
1835
+ if (held.parentSessionId !== current.parentSessionId) return held;
1836
+ const state = structuredClone(held);
1837
+ const r =
1838
+ state.records.find((record) => record.offerId === offerId && record.active) ??
1839
+ state.priorStops?.find((record) => record.offerId === offerId);
1840
+ if (r && (!r.nativeId || r.nativeId === nativeId)) r.nativeId = nativeId;
1841
+ return state;
1842
+ });
1843
+ }
1844
+ } catch {
1845
+ /* Failed observation cannot start, duplicate or cancel the real worker. */
1846
+ } finally {
1847
+ pendingViewerSpawns--;
1848
+ viewerStarted = true;
1849
+ }
1850
+ })();
1851
+ }
1852
+ } catch {
1853
+ /* All observation setup is optional. */
1854
+ }
1855
+ }
1856
+ return {
1857
+ stop,
1858
+ move: () => {
1859
+ if (timer) background = true;
1860
+ else stop();
1861
+ },
1862
+ /** A background call's worker: followed to its end, where its result is handed to the parent. */
1863
+ follow: () => {
1864
+ if (timer) background = true;
1865
+ else stop();
1866
+ },
1867
+ };
1868
+ }
1869
+
1870
+ /** Whether a call is this plugin's own (its activity read, its viewer agent), by who raised it. */
1871
+ export function raisedByThisPlugin(origin: { plugin?: string } | undefined): boolean {
1872
+ return origin?.plugin === 'tenjin';
1873
+ }
1874
+
1875
+ export function registerModelViewer(on: On): void {
1876
+ on('agent.offer', { agent: TYPE }, () => ({ isOffered: false }));
1877
+ on('session.start', async ($, e, next) => {
1878
+ // A module the host keeps across `/clear` serves the next session too.
1879
+ sessionEnding = false;
1880
+ try {
1881
+ if (await enabled($)) await registerType($);
1882
+ } catch {
1883
+ /* Optional viewer. */
1884
+ }
1885
+ return next(e);
1886
+ });
1887
+ on('session.end', async ($, e, next) => {
1888
+ sessionEnding = true;
1889
+ showHeldGroup($, 0);
1890
+ try {
1891
+ // The event names the session that closed.
1892
+ const closed = (e as { sessionId?: unknown }).sessionId;
1893
+ await endBackgroundWorkers($, typeof closed === 'string' && closed ? closed : undefined);
1894
+ } catch {
1895
+ /* The session ends as it would have. */
1896
+ }
1897
+ return next(e);
1898
+ });
1899
+ // A STEP THAT ENDED AT ITS BOUND while its worker runs: the viewer's stop is held,
1900
+ // so the next step of the same turn follows on and its agent stays listed.
1901
+ on('classic.SubagentStop', async ($, e, next) => {
1902
+ if (next.origin.plugin !== 'engine' || e.agent_type !== TYPE || !handedOver.has(e.agent_id))
1903
+ return next(e);
1904
+ try {
1905
+ const item = (await $.state.get(STATE)).value?.records.find((r) => r.nativeId === e.agent_id);
1906
+ if (item?.active) return { block: 'The DeepSeek worker is still running.' };
1907
+ } catch {
1908
+ /* The viewer ends; the worker runs on. */
1909
+ }
1910
+ handedOver.delete(e.agent_id);
1911
+ return next(e);
1912
+ });
1913
+ on('classic.SubagentStart', async ($, e, next) => {
1914
+ if (next.origin.plugin === 'engine' && e.agent_type === TYPE) {
1915
+ // Tag before any fallible host call; the native event pins this type and id.
1916
+ guardViewer(e.agent_id);
1917
+ try {
1918
+ // A listed viewer may be stopped before its first step supplies a turn id.
1919
+ await identify($, e.agent_id).catch(() => undefined);
1920
+ await change($, (state) => {
1921
+ if (state.knownIds.includes(e.agent_id)) return;
1922
+ const live = state.records.filter((r) => r.active).map((r) => r.nativeId);
1923
+ const ids = [...state.knownIds, e.agent_id];
1924
+ while (ids.length > 16) {
1925
+ const free = ids.findIndex((id) => !live.includes(id) && id !== e.agent_id);
1926
+ if (free < 0) break;
1927
+ ids.splice(free, 1);
1928
+ }
1929
+ state.knownIds = ids.slice(-16);
1930
+ });
1931
+ } catch {
1932
+ /* The native qualification must prove this mark precedes the first step. */
1933
+ }
1934
+ return next(e);
1935
+ }
1936
+ // Any other subagent: the router's hint for its task, if its call had one.
1937
+ return withDelegatedHint($, e, await next(e));
1938
+ });
1939
+ on('agent.spawn', { subagentType: TYPE }, async ($, e, next) => {
1940
+ try {
1941
+ const held = await load($);
1942
+ const matches = held?.state.records.filter(
1943
+ (r) =>
1944
+ r.active &&
1945
+ !r.nativeId &&
1946
+ r.description === e.description &&
1947
+ (e.parentAgentId === undefined || r.parentId === e.parentAgentId),
1948
+ );
1949
+ if (e.resume || next.origin.plugin !== 'tenjin' || matches?.length !== 1)
1950
+ return { deny: 'This activity viewer cannot execute or resume an assignment.' };
1951
+ return next(e);
1952
+ } catch {
1953
+ return { deny: 'DeepSeek activity viewer is unavailable.' };
1954
+ }
1955
+ }).catch(() => ({ deny: 'DeepSeek activity viewer is unavailable.' }));
1956
+
1957
+ // THE ACTIVITY READ IS THE VIEWER'S OWN. A parent that polls a running worker with
1958
+ // it reads the whole activity into its context and draws a `Called
1959
+ // plugin:tenjin:router` line; a native subagent's parent does not check on it at
1960
+ // all. So the model's own call is refused. The host raises this plugin's own
1961
+ // `$.mcp.call` as a `tool.call` of the tool too, under this plugin's origin (seen
1962
+ // on 2.1.326): refused there, the viewer's first read threw, and its agent ended
1963
+ // within a second of the accept and left the agent list.
1964
+ on('tool.call', { tool: ACTIVITY }, (_$, e, next) => {
1965
+ if (raisedByThisPlugin(next.origin)) return next(e);
1966
+ return {
1967
+ deny: "This read is the Tenjin plugin's own, for the DeepSeek worker's viewer. A worker's result arrives by itself: as the result of your subagent call, or as that task's notification when the call was moved to the background. Do not check on it. If someone asks how it is doing, say it is still running and that they can open the DeepSeek agent in the agent list. To stop it, call subagent with cancel.",
1968
+ };
1969
+ });
1970
+
1971
+ // A VIEWER STEP'S CALL IS ANSWERED HERE, from the worker's row, and runs nothing: an
1972
+ // answer at `tool.call` serves the tool and skips its permission check. Any other call
1973
+ // in a viewer's loop, or one this hook fails to answer, is refused at `tool.check`.
1974
+ on('tool.call', { tool: [...VIEWER_TOOLS] }, (_$, e, next) => {
1975
+ const call = e.agentId !== undefined ? viewerCalls.get(e.tool_use_id ?? '') : undefined;
1976
+ if (!call) return next(e);
1977
+ viewerCalls.delete(e.tool_use_id!);
1978
+ return answerOf(e.tool, call.row, call.input) as never;
1979
+ }).catch((_$, e, next) =>
1980
+ next.called || !viewerCalls.has(e.tool_use_id ?? '')
1981
+ ? next(e)
1982
+ : { deny: 'DeepSeek activity unavailable.' },
1983
+ );
1984
+ const refused = {
1985
+ decision: 'deny',
1986
+ reason: 'The DeepSeek activity viewer runs no tool.',
1987
+ } as const;
1988
+ on('tool.check', async ($, e, next) => {
1989
+ if (e.agentId !== undefined) {
1990
+ const viewer =
1991
+ liveViewerGuards.has(e.agentId) || (await knownViewer($, e.agentId).catch(() => false));
1992
+ if (viewer) return refused;
1993
+ }
1994
+ // In place of the allow leg the plugin's hooks file runs for other hosts, whose run
1995
+ // the host draws as a row of its own beside the accept's.
1996
+ if (e.tool === ACCEPT && allowedAccept(e.input, raisedByThisPlugin(next.origin)))
1997
+ return { decision: 'allow', reason: 'Tenjin subagent' };
1998
+ return next(e);
1999
+ }).catch((_$, e, next) =>
2000
+ e.agentId !== undefined && liveViewerGuards.has(e.agentId) ? refused : next(e),
2001
+ );
2002
+
2003
+ on('tool.call', { tool: ACCEPT }, async ($, e, next) => {
2004
+ // ONLY A HELD CALL ASKS FOR AN OFFER. `capture` is this mod's own transport,
2005
+ // sent for an Agent, Task or SendMessage call it holds. Sent by the model it
2006
+ // would buy a routing decision for a call nobody made.
2007
+ if (e.capture !== undefined && next.origin.plugin !== 'tenjin')
2008
+ return {
2009
+ deny: 'Tenjin makes an offer only for an Agent, Task or SendMessage call it holds. Call that tool; never send capture yourself.',
2010
+ };
2011
+ // The end of a session is the host's word, which only this plugin relays.
2012
+ if (e.end_session !== undefined && next.origin.plugin !== 'tenjin')
2013
+ return { deny: 'Tenjin ends a session’s workers by itself when the session closes.' };
2014
+ // `reason` says the person stopped the worker's agent, or that its session ended, so
2015
+ // only this plugin sends it.
2016
+ if (e.reason !== undefined && next.origin.plugin !== 'tenjin')
2017
+ return {
2018
+ deny: 'Tenjin records why a worker stopped by itself. To stop a worker, call subagent with cancel alone.',
2019
+ };
2020
+ // The parent's first answer to a held group, an accept or a cancel, takes its notice
2021
+ // back. The plugin's own calls are no answer, and neither is a subagent's own call.
2022
+ if (
2023
+ e.capture === undefined &&
2024
+ e.end_session === undefined &&
2025
+ e.agentId === undefined &&
2026
+ !raisedByThisPlugin(next.origin)
2027
+ )
2028
+ showHeldGroup($, 0);
2029
+ // A cancelled offer is settled too: its row has nothing left to offer. A native
2030
+ // subagent's cancel of the offer it got settles it as the main loop's does.
2031
+ if (short(e.cancel) && UUID.test(e.cancel)) {
2032
+ const outcome = await next(e);
2033
+ try {
2034
+ const ref = { ...OFFERS, id: e.cancel };
2035
+ const offer = (await $.state.get(ref)).value;
2036
+ if (offer && json(outcome.text)?.status === 'cancelled')
2037
+ await $.state.set(ref, { ...offer, state: 'cancelled' });
2038
+ } catch {
2039
+ /* Display only. */
2040
+ }
2041
+ return outcome;
2042
+ }
2043
+ // Capture/cancel calls are never execution accepts. A NATIVE SUBAGENT'S ACCEPT is one:
2044
+ // its worker gets the same row, viewer and end line, the viewer under that subagent.
2045
+ // A viewer's own loop and a DeepSeek worker's process start none (neither has the tool).
2046
+ const offerIds = acceptedIds(e, true);
2047
+ if (
2048
+ !offerIds ||
2049
+ // The plugin's own read of an ended offer's stored result starts and draws nothing.
2050
+ raisedByThisPlugin(next.origin) ||
2051
+ (e.agentId !== undefined &&
2052
+ (liveViewerGuards.has(e.agentId) || (await knownViewer($, e.agentId).catch(() => true)))) ||
2053
+ (await $.env.get('TENJIN_MODEL_WORKER').catch(() => undefined)) === '1'
2054
+ )
2055
+ return next(e);
2056
+ const batched = offerIds.length > 1;
2057
+ // A repeat keeps the existing worker's observer and its clock.
2058
+ const watchers = new Map<string, Awaited<ReturnType<typeof watchAccept>>>();
2059
+ for (const id of offerIds) {
2060
+ if (!liveWorkers.has(id)) watchers.set(id, await watchAccept($, id, e.agentId, batched));
2061
+ }
2062
+ if (watchers.size && short(e.tool_use_id)) {
2063
+ acceptCalls.set(e.tool_use_id, offerIds);
2064
+ // This call runs these workers: its row's answer is theirs, whichever row draws it.
2065
+ for (const id of watchers.keys()) {
2066
+ const seen = acceptSeen.get(id);
2067
+ if (seen?.call === e.tool_use_id) seen.started = true;
2068
+ else acceptSeen.set(id, { call: e.tool_use_id, batched, started: true });
2069
+ }
2070
+ }
2071
+ let outcome: Awaited<ReturnType<typeof next>>;
2072
+ try {
2073
+ outcome = await next(e);
2074
+ } catch (error) {
2075
+ for (const watcher of watchers.values()) watcher.stop();
2076
+ throw error;
2077
+ }
2078
+ const said = typeof outcome.text === 'string' ? outcome.text : '';
2079
+ const answer = acceptResponse(said);
2080
+ if (!answer && HOST_MOVED.test(said)) {
2081
+ // The host owns this single outstanding request and its completion notice.
2082
+ // The worker displays follow their own jobs until each ends.
2083
+ for (const watcher of watchers.values()) watcher.move();
2084
+ const task = /\btask ([A-Za-z0-9_-]{1,64})\b/.exec(said)?.[1];
2085
+ if (task && watchers.size) movedTasks.set(task, offerIds);
2086
+ } else if (!answer && HOST_IDLE_ABORT.test(said)) {
2087
+ // The host ended the call; the workers did not end. Each is a background worker now.
2088
+ for (const [id, watcher] of watchers) {
2089
+ try {
2090
+ const ref = { ...OFFERS, id };
2091
+ const held = (await $.state.get(ref)).value;
2092
+ if (held) await $.state.set(ref, { ...held, background: true as const });
2093
+ } catch {
2094
+ /* The row still follows; the stored result stays readable by accepting again. */
2095
+ }
2096
+ // A worker of the batch that ended before the host gave up has stopped its own
2097
+ // watch, and its delivery was skipped while its offer was a foreground one: it is
2098
+ // handed over now, once. A worker still running is followed to its end.
2099
+ const row = (await $.state.get({ ...WORKERS, id }).catch(() => undefined))?.value;
2100
+ if (row?.ended) void deliverBackground($, id, row.title ?? 'subagent');
2101
+ else watcher.follow();
2102
+ }
2103
+ } else {
2104
+ const results = batched ? batchOutcomes(answer) : undefined;
2105
+ for (const [id, watcher] of watchers) {
2106
+ const own = results?.get(id) ?? answer;
2107
+ // A BACKGROUND CALL'S WORKER runs on past its accept call, which answered at once:
2108
+ // its row follows the job until it ends, as a call the host moved is followed.
2109
+ if (startedInBackground(own)) watcher.follow();
2110
+ else watcher.stop(endedFrom(own));
2111
+ }
2112
+ }
2113
+ // A background result that waited for this call to return goes out once it has.
2114
+ if (undelivered.size)
2115
+ try {
2116
+ $.clock.after(0, () => deliverLater($));
2117
+ } catch {
2118
+ /* The turn's end sends it. */
2119
+ }
2120
+ return outcome;
2121
+ });
2122
+ on('turn.step', async function* ($, e, next) {
2123
+ const loop = e.agentId ?? '';
2124
+ steps.delete(loop);
2125
+ steps.set(loop, e.turnId + ':' + e.index);
2126
+ if (steps.size > 64) steps.delete(steps.keys().next().value!);
2127
+ if (!e.agentId) return yield* next(e);
2128
+ let marked = !!liveViewerGuards.get(e.agentId);
2129
+ if (marked) guardViewer(e.agentId, e.turnId);
2130
+ try {
2131
+ marked ||= await knownViewer($, e.agentId).catch(() => false);
2132
+ if (marked) guardViewer(e.agentId, e.turnId);
2133
+ const native = (await $.agent.list()).find((a) => a.id === e.agentId);
2134
+ if (native?.type !== TYPE)
2135
+ return marked ? yield* finish(e, 'DeepSeek activity unavailable.') : yield* next(e);
2136
+ marked = true;
2137
+ guardViewer(e.agentId, e.turnId);
2138
+ const owned = await identify($, e.agentId, e.turnId);
2139
+ if (!owned || !(await enabled($)) || (owned.item.turnId && owned.item.turnId !== e.turnId))
2140
+ return yield* finish(
2141
+ e,
2142
+ 'DeepSeek activity unavailable. Continue through the owned worker handle.',
2143
+ );
2144
+ handedOver.delete(e.agentId);
2145
+ let view = views.get(e.agentId);
2146
+ if (view?.offerId !== owned.item.offerId) {
2147
+ view = {
2148
+ offerId: owned.item.offerId,
2149
+ sequence: 0,
2150
+ rows: [],
2151
+ shown: new Set(),
2152
+ dropped: 0,
2153
+ holds: 0,
2154
+ };
2155
+ views.set(e.agentId, view);
2156
+ if (views.size > 16) views.delete(views.keys().next().value!);
2157
+ }
2158
+ // AFTER ITS LAST STEP the viewer says nothing more: the host may ask it again (its
2159
+ // hand-back reminder asked three times live), and a native subagent's view ends
2160
+ // with its answer. An empty step draws nothing.
2161
+ if (view.done) return yield* finish(e, '');
2162
+ return yield* viewerStep($, e, e.agentId, owned.item, view);
2163
+ } catch {
2164
+ if (marked) return yield* finish(e, 'DeepSeek activity unavailable.');
2165
+ return yield* next(e);
2166
+ }
2167
+ }).catch(async function* ($, e, next) {
2168
+ if (
2169
+ e.agentId &&
2170
+ (liveViewerGuards.has(e.agentId) || (await knownViewer($, e.agentId).catch(() => false)))
2171
+ )
2172
+ return yield* finish(e, 'DeepSeek activity unavailable.');
2173
+ return yield* next(e);
2174
+ });
2175
+ on('turn.complete', async ($, e, next) => {
2176
+ // The main loop's turn alone: a viewer's turn that ends meanwhile says nothing of it.
2177
+ if (!e.agentId) showHeldGroup($, 0);
2178
+ if (!e.agentId && undelivered.size) deliverLater($);
2179
+ if (e.agentId) {
2180
+ const guard = liveViewerGuards.get(e.agentId);
2181
+ if (guard && (!guard.turnId || guard.turnId === e.turnId)) liveViewerGuards.delete(e.agentId);
2182
+ }
2183
+ if (e.agentId) {
2184
+ handedOver.delete(e.agentId);
2185
+ views.delete(e.agentId);
2186
+ }
2187
+ try {
2188
+ // ONLY A STOP OF THE AGENT CANCELS ITS WORKER: a person's from the agent list, or the
2189
+ // parent's TaskStop, as for a native subagent. An abort is also the host ending the
2190
+ // viewer's turn for its own reasons (its stall watchdog, at ten minutes), which says
2191
+ // nothing about the worker; only a stopped agent reads `killed`. How long the step
2192
+ // has run tells nothing: a person can stop the agent at any moment of it.
2193
+ if (e.agentId && e.reason === 'aborted' && !sessionEnding) {
2194
+ const agentId = e.agentId;
2195
+ // Cancellation uses the prior binding even when cwd access was revoked. This
2196
+ // grants no work/scope authority; the backend still checks its owned pending offer.
2197
+ const bound = async () => {
2198
+ const [parentSessionId, held] = await Promise.all([$.session.id(), $.state.get(STATE)]);
2199
+ const state = held.value;
2200
+ const item =
2201
+ state?.version === 1 && state.parentSessionId === parentSessionId
2202
+ ? (state.records.find((r) => r.active && r.nativeId === agentId) ??
2203
+ state.priorStops?.find((r) => r.nativeId === agentId))
2204
+ : undefined;
2205
+ return item && (!item.turnId || item.turnId === e.turnId)
2206
+ ? { offerId: item.offerId, parentSessionId }
2207
+ : undefined;
2208
+ };
2209
+ const stopped = async () =>
2210
+ (await $.agent.list()).some(
2211
+ (a) =>
2212
+ a.id === agentId &&
2213
+ a.type === TYPE &&
2214
+ a.spawnedBy === 'tenjin' &&
2215
+ (a.status === 'killed' || a.taskStatus === 'killed'),
2216
+ );
2217
+ const cancel = async (item: { offerId: string; parentSessionId: string }) => {
2218
+ const response = await $.mcp.call(SERVER, 'subagent', {
2219
+ cancel: item.offerId,
2220
+ reason: 'agent_stopped',
2221
+ });
2222
+ if (body(response)?.status !== 'cancelled') return;
2223
+ await update($, STATE, (state) => {
2224
+ if (!state) throw new Error('Activity binding unavailable');
2225
+ if (state.parentSessionId !== item.parentSessionId || !state.priorStops) return state;
2226
+ return {
2227
+ ...state,
2228
+ priorStops: state.priorStops.filter(
2229
+ (r) => !(r.offerId === item.offerId && r.nativeId === agentId),
2230
+ ),
2231
+ };
2232
+ });
2233
+ };
2234
+ const item = await bound();
2235
+ if (item && (await stopped())) await cancel(item);
2236
+ else if (item)
2237
+ // A stop may mark the agent a moment after its turn ends: read it once more.
2238
+ $.clock.after(RECHECK_MS, async () => {
2239
+ try {
2240
+ const still = await bound();
2241
+ if (still && !sessionEnding && (await stopped())) await cancel(still);
2242
+ } catch {
2243
+ /* Not a stop that can be told: the worker runs on. */
2244
+ }
2245
+ });
2246
+ }
2247
+ } catch {
2248
+ /* Failed UI cancellation is not a new execution or payment. */
2249
+ }
2250
+ return next(e);
2251
+ });
2252
+
2253
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
2254
+ const { view, hasSurvey, isCollapsed, maxRows, bodyColumns } = e.props;
2255
+ if (!view.agentId && heldGroup > 0 && !hasSurvey && !isCollapsed && maxRows >= 1) {
2256
+ // The main view, while a parallel summary's held calls wait for the parent's answer.
2257
+ const { Box, Text } = $.ui.resolve(e);
2258
+ return (
2259
+ <Box flexDirection="column">
2260
+ <Text dimColor wrap="truncate-end">
2261
+ {`Tenjin offered DeepSeek for ${heldGroup} Agent calls`}
2262
+ </Text>
2263
+ </Box>
2264
+ );
2265
+ }
2266
+ if (!view.agentId || hasSurvey || isCollapsed || maxRows < 1 || bodyColumns < 1) return next(e);
2267
+ const [parentSessionId, held] = await Promise.all([$.session.id(), $.state.get(STATE)]);
2268
+ const state = held.value;
2269
+ const item =
2270
+ state?.parentSessionId === parentSessionId
2271
+ ? state.records.find((r) => r.nativeId === view.agentId && r.turnId)
2272
+ : undefined;
2273
+ if (!item) return next(e);
2274
+ const { Box, Text } = $.ui.resolve(e);
2275
+ const a = item.activity;
2276
+ const width = Math.max(1, Math.min(160, Math.floor(bodyColumns)));
2277
+ const running =
2278
+ !item.inspectionUnavailable && (a?.state === 'starting' || a?.state === 'running');
2279
+ // ONE STATUS LINE, since a subagent's view has no other place for its model,
2280
+ // counts and spend. What the worker does is the transcript's to show, not
2281
+ // this band's. While it runs, only what has settled: never a reservation
2282
+ // that reads as a price.
2283
+ const line = [
2284
+ 'DeepSeek V4.1 Flash 1017',
2285
+ displayState(item),
2286
+ a?.toolUses !== undefined ? toolUses(a.toolUses) : undefined,
2287
+ a?.tokens ? tokens(a.tokens) : undefined,
2288
+ !a?.spend
2289
+ ? 'spend pending'
2290
+ : running
2291
+ ? dollars(a.spend.actualAtomic) + ' so far'
2292
+ : 'spent ' +
2293
+ dollars(a.spend.actualAtomic) +
2294
+ ' · reserved ' +
2295
+ dollars(a.spend.reservedAtomic) +
2296
+ (a.spend.uncertain.length ? ' · settlement unresolved' : ''),
2297
+ ]
2298
+ .filter((part): part is string => part !== undefined)
2299
+ .join(' · ');
2300
+ return (
2301
+ <Box flexDirection="column" width={width}>
2302
+ <Text wrap="truncate-end">{Array.from(clean(line, 640)).slice(0, width).join('')}</Text>
2303
+ </Box>
2304
+ );
2305
+ });
2306
+
2307
+ // Claude Code's parallel Agent summary bypasses the tool render hooks, and reads `Not run`
2308
+ // for a held call, which is true. TENJIN ADDS NO LINE OF ITS OWN TO IT (operator ruling
2309
+ // 2026-11-18): an accepted call has its DeepSeek row and a call sent again its native row.
2310
+ // By call: the offer it got, or none where Tenjin held it with no offer.
2311
+ const heldCalls = new Map<string, string | undefined>();
2312
+ on('tool.call', { tool: ['Agent', 'Task'] }, async ($, e, next) => {
2313
+ const answer = await next(e);
2314
+ // PostToolBatch sees model-facing text. Claude omits the agent id from
2315
+ // Explore and Plan handbacks, so identify holds before it formats them.
2316
+ const held = heldOffer(answer.deny ?? answer.result);
2317
+ // An Agent call of the main loop that ran is a row that started.
2318
+ if (!held && e.agentId === undefined) showHeldGroup($, 0);
2319
+ if (held) {
2320
+ heldCalls.set(e.tool_use_id, held === 'unavailable' ? undefined : held.offerId.toLowerCase());
2321
+ if (heldCalls.size > 512) heldCalls.delete(heldCalls.keys().next().value!);
2322
+ }
2323
+ return answer;
2324
+ });
2325
+ on('classic.PostToolBatch', ($, e, next) => {
2326
+ if (heldCalls.size === 0) return next(e);
2327
+ let offered = 0;
2328
+ for (const tool of ['Agent', 'Task']) {
2329
+ const calls = e.tool_calls.filter((call) => call.tool_name === tool);
2330
+ for (const call of calls.filter((held) => heldCalls.has(held.tool_use_id))) {
2331
+ const offer = heldCalls.get(call.tool_use_id);
2332
+ heldCalls.delete(call.tool_use_id);
2333
+ // One of several Agent calls of the response: the host's block is its row.
2334
+ if (offer && calls.length > 1) offered++;
2335
+ if (offer && calls.length > 1 && !groupedOffers.has(offer)) {
2336
+ groupedOffers.add(offer);
2337
+ if (groupedOffers.size > DRAWN_MAX)
2338
+ groupedOffers.delete(groupedOffers.values().next().value!);
2339
+ $.ui.invalidate('ui.render');
2340
+ }
2341
+ }
2342
+ }
2343
+ if (offered > 0) showHeldGroup($, offered);
2344
+ return next(e);
2345
+ });
2346
+
2347
+ // Individual accepts show a live DeepSeek row. Individual held Agent calls
2348
+ // show their offer until settled, with the result available in ctrl+o.
2349
+ on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
2350
+ const { tool, input, output, isInterrupted, isErrored } = e.props;
2351
+ // A WORKER'S CALL A ROUTER TOOL SERVED names that tool, as the router's own rows do
2352
+ // (`Exa search("q")`): in the worker nothing was replaced, Exa is what searched. Its
2353
+ // result line under the row stays the host's own.
2354
+ const via = servedCalls.get(e.props.tool_use_id);
2355
+ if (via && (tool === 'WebSearch' || tool === 'WebFetch')) {
2356
+ const given = record(input) ?? {};
2357
+ const argument =
2358
+ tool === 'WebSearch' ? '"' + String(given.query ?? '') + '"' : String(given.url ?? '');
2359
+ return workerRow($.ui.resolve(e), {
2360
+ state: e.props.isRunning ? 'running' : isErrored || isInterrupted ? 'error' : 'done',
2361
+ name: via,
2362
+ argument: clean(argument, 400),
2363
+ });
2364
+ }
2365
+ if (tool === ACCEPT) {
2366
+ const offerIds = acceptedIds(input);
2367
+ if (!offerIds) {
2368
+ // THE CALL AS THE MODEL IS STILL WRITING IT: no offer id to read yet, so the host's
2369
+ // own row would stand here for that moment as `plugin:tenjin:router - subagent`,
2370
+ // between the offer row and the DeepSeek row. Nothing is drawn until the input
2371
+ // says which call it is. A cancel, a capture and a call with an answer keep the
2372
+ // host's row. Also where the row reads as expanded: a folded run this mod unfolds
2373
+ // (the ToolGroup hook below) hands its rows down expanded, so passing those on
2374
+ // drew the host's row for that moment (live on alpha.66: `plugin:` for a split second).
2375
+ if (undecided(input) && output === undefined && !isErrored && !isInterrupted) {
2376
+ const { Box } = $.ui.resolve(e);
2377
+ return <Box display="none" />;
2378
+ }
2379
+ // A CANCEL DRAWS NOTHING OF ITS OWN, as an accept draws nothing: the worker's row
2380
+ // says `Cancelled by the parent`, and an offer nobody accepted says `cancelled` on
2381
+ // its held row. Live on alpha.80 the host's row stood under the worker's with the
2382
+ // raw `{"status":"cancelled"}`. A cancel that was refused, failed or was cut keeps
2383
+ // the host's row.
2384
+ if (
2385
+ cancelOf(input) &&
2386
+ !isErrored &&
2387
+ !isInterrupted &&
2388
+ (output === undefined || cancelAnswer(acceptResponse(textOf(output))))
2389
+ ) {
2390
+ const { Box } = $.ui.resolve(e);
2391
+ return <Box display="none" />;
2392
+ }
2393
+ return next(e);
2394
+ }
2395
+ return (
2396
+ (await acceptRows($, $.ui.resolve(e), e.surface, offerIds, e.props, e.props.isExpanded)) ??
2397
+ next(e)
2398
+ );
2399
+ }
2400
+ if (tool === 'Agent' || tool === 'Task') {
2401
+ const held = heldOffer(output);
2402
+ if (!held) return next(e);
2403
+ const offerId = held === 'unavailable' ? '' : held.offerId;
2404
+ const ui = $.ui.resolve(e);
2405
+ const full = e.props.isExpanded === true;
2406
+ if (held !== 'unavailable' && UUID.test(offerId)) {
2407
+ const [offer, worker, now] = await Promise.all([
2408
+ $.state.get({ ...OFFERS, id: offerId }),
2409
+ $.state.get({ ...WORKERS, id: offerId }),
2410
+ $.clock.now(),
2411
+ ]);
2412
+ const key = e.surface + ':' + offerId;
2413
+ const seen = acceptSeen.get(offerId);
2414
+ // ONE ROW A TASK, AND IT IS THIS ONE. An accepted offer's worker draws here, where
2415
+ // its call stood, and the accept call draws nothing for it. Shown in full
2416
+ // (ctrl+o), this row is the held call and its offer, and the accept call's row
2417
+ // is the worker's.
2418
+ if (worker.value || seen) {
2419
+ markHeldRow($, key, !full);
2420
+ if (full) return next(e);
2421
+ // In the host's summary block this row is not on the screen: the accept call's is.
2422
+ if (groupedOffers.has(offerId.toLowerCase())) return <ui.Box display="none" />;
2423
+ const row = await describeWorker(
2424
+ $,
2425
+ offerId,
2426
+ seen ?? {},
2427
+ seen?.batched ?? false,
2428
+ titleOf(record(input), 'subagent'),
2429
+ );
2430
+ if (row) return workerRow(ui, row);
2431
+ }
2432
+ // An offer kept native by its repeated call or left to expire is settled with no
2433
+ // worker: the native call's own row is the task's row, and this one draws nothing.
2434
+ else if (
2435
+ offer.value &&
2436
+ offer.value.state !== 'cancelled' &&
2437
+ (offer.value.state !== 'offered' || now - offer.value.at > OFFER_MS)
2438
+ ) {
2439
+ if (full) return next(e);
2440
+ return <ui.Box display="none" />;
2441
+ } else {
2442
+ markHeldRow($, key, !full);
2443
+ // A CANCELLED OFFER NOBODY ACCEPTED keeps this row, which says so: the cancel
2444
+ // call draws nothing, and no native call follows a cancel.
2445
+ if (offer.value?.state === 'cancelled')
2446
+ return workerRow(ui, {
2447
+ state: 'held',
2448
+ name: tool,
2449
+ struck: true,
2450
+ argument: titleOf(record(input), 'subagent'),
2451
+ tail: ' · Tenjin offered DeepSeek · cancelled',
2452
+ });
2453
+ }
2454
+ }
2455
+ // THE OFFER, as the tool router marks a held `Web Search` row: the native name
2456
+ // struck through, and what Tenjin offered in its place.
2457
+ return workerRow(ui, {
2458
+ state: 'held',
2459
+ name: tool,
2460
+ struck: held !== 'unavailable',
2461
+ argument: titleOf(record(input), 'subagent'),
2462
+ tail:
2463
+ held === 'unavailable'
2464
+ ? ' · Tenjin held it · not started'
2465
+ : ' · Tenjin offered DeepSeek' +
2466
+ (held.capAtomic ? ' · cap ' + dollars(held.capAtomic) : ''),
2467
+ });
2468
+ }
2469
+ return next(e);
2470
+ });
2471
+ // A standalone batch owns one compact group. Ctrl+O draws ToolUse and
2472
+ // ToolResult directly, so its individual rows can expand without render state.
2473
+ on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
2474
+ if (e.props.isExpanded) return next(e);
2475
+ const [call] = e.props.calls;
2476
+ if (e.props.isCallsOnly !== false && e.props.calls.length === 1 && call?.tool === ACCEPT) {
2477
+ const ids = acceptedIds(call.input);
2478
+ if (ids && ids.length > 1) {
2479
+ const batch = await acceptRows($, $.ui.resolve(e), e.surface, ids, call, false);
2480
+ if (batch !== undefined) return batch;
2481
+ }
2482
+ }
2483
+ // Other accepts in a folded run keep the engine's individual rows.
2484
+ const accepts = e.props.calls.some(
2485
+ (call) =>
2486
+ call.tool === ACCEPT &&
2487
+ (acceptedIds(call.input) || undecided(call.input) || cancelOf(call.input)),
2488
+ );
2489
+ return next(accepts ? { ...e, props: { ...e.props, isExpanded: true } } : e);
2490
+ });
2491
+ on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
2492
+ const { tool, output, isExpanded } = e.props;
2493
+ if (isExpanded === true) return next(e);
2494
+ // The host's notice for a call it moved to the background names the server and
2495
+ // the tool: the row above already says the worker runs on.
2496
+ const said = textOf(output);
2497
+ const answer = tool === ACCEPT ? acceptResponse(said) : undefined;
2498
+ const ours =
2499
+ tool === ACCEPT
2500
+ ? acceptAnswer(answer) ||
2501
+ !!batchOutcomes(answer) ||
2502
+ HOST_MOVED.test(said ?? '') ||
2503
+ // Only a cancel that took answers with its status alone.
2504
+ cancelAnswer(answer)
2505
+ : (tool === 'Agent' || tool === 'Task') && heldOffer(output) !== undefined;
2506
+ if (!ours) return next(e);
2507
+ const { Box } = $.ui.resolve(e);
2508
+ return <Box display="none" />;
2509
+ });
2510
+ // Its first message is the worker's real assignment, as a native subagent's
2511
+ // is the prompt its parent sent. The drawing alone: the viewer agent was told
2512
+ // only the short line above, and nothing is sent to its model.
2513
+ on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
2514
+ const told = e.props.text.trim();
2515
+ // THE END OF A WORKER WHOSE ACCEPT CALL THE HOST MOVED TO THE BACKGROUND comes as
2516
+ // that task's notification, which names the server and the tool. It reads as a
2517
+ // native subagent's does: who finished, and its counts.
2518
+ const task = e.props.task;
2519
+ const moved =
2520
+ (task?.toolUseId !== undefined ? acceptCalls.get(task.toolUseId) : undefined) ??
2521
+ (task?.id !== undefined ? movedTasks.get(task.id) : undefined) ??
2522
+ movedTasks.get(/^MCP task (\S+) \(/.exec(told)?.[1] ?? '');
2523
+ if (moved !== undefined && moved.length > 1) {
2524
+ // Completing the host task says nothing about how any one worker ended.
2525
+ const workers = await Promise.all(
2526
+ moved.map(async (id) => (await $.state.get({ ...WORKERS, id })).value),
2527
+ );
2528
+ if (workers.every((worker) => worker === undefined)) return next(e);
2529
+ const statuses = workers.map((worker) => worker?.ended);
2530
+ const finished = statuses.filter((status) => status === 'completed').length;
2531
+ const unconfirmed = statuses.filter((status) => !status || status === 'unknown').length;
2532
+ const other = moved.length - finished - unconfirmed;
2533
+ const summary = [
2534
+ finished ? finished + ' finished' : undefined,
2535
+ other ? other + ' ended without completing' : undefined,
2536
+ unconfirmed ? unconfirmed + ' unconfirmed' : undefined,
2537
+ ]
2538
+ .filter(Boolean)
2539
+ .join(' · ');
2540
+ if (e.props.isExpanded)
2541
+ return next({ ...e, props: { ...e.props, text: 'DeepSeek workers · ' + summary } });
2542
+ const { Box, Text } = $.ui.resolve(e);
2543
+ return (
2544
+ <Box marginTop={1}>
2545
+ <Text dimColor>{'› Message from @DeepSeek (ctrl+o to expand)'}</Text>
2546
+ </Box>
2547
+ );
2548
+ }
2549
+ if (moved?.[0] !== undefined) {
2550
+ const live = (await $.state.get({ ...WORKERS, id: moved[0] })).value;
2551
+ if (!live) return next(e);
2552
+ const how = live.ended ?? (task?.status === 'completed' ? 'completed' : undefined);
2553
+ const text =
2554
+ 'DeepSeek "' +
2555
+ live.title +
2556
+ '" ' +
2557
+ (how === 'completed'
2558
+ ? 'finished'
2559
+ : how === 'not_started'
2560
+ ? 'did not start'
2561
+ : how === undefined || endedByOf(live.endedBy)
2562
+ ? 'ended'
2563
+ : how === 'cancelled'
2564
+ ? 'was interrupted'
2565
+ : 'stopped') +
2566
+ (live.ended ? ' · ' + endingText(workerEnding(live)) : '');
2567
+ // AS A NATIVE SUBAGENT'S RETURN READS in the compact view: one dim line naming the
2568
+ // sender. The row's sender (`from`) is the host's alone to set, so the line is
2569
+ // drawn here; in full (ctrl+o) the row says who finished and its counts.
2570
+ if (e.props.isExpanded) return next({ ...e, props: { ...e.props, text } });
2571
+ const { Box, Text } = $.ui.resolve(e);
2572
+ return (
2573
+ <Box marginTop={1}>
2574
+ <Text dimColor>{'› Message from @DeepSeek (ctrl+o to expand)'}</Text>
2575
+ </Box>
2576
+ );
2577
+ }
2578
+ // A background worker's result, handed over by this plugin: one dim line naming the
2579
+ // sender in the compact view, as the notice of a moved call reads; in full, as sent.
2580
+ if (!task && BACKGROUND_ROW.test(told)) {
2581
+ if (e.props.isExpanded) return next(e);
2582
+ const { Box, Text } = $.ui.resolve(e);
2583
+ return (
2584
+ <Box marginTop={1}>
2585
+ <Text dimColor>{'› Message from @DeepSeek (ctrl+o to expand)'}</Text>
2586
+ </Box>
2587
+ );
2588
+ }
2589
+ if (!told.startsWith(VIEWER_PROMPT + ' ')) return next(e);
2590
+ // `<offer id> <description>`, as the viewer was told.
2591
+ const [, offerId, description = ''] =
2592
+ /^(\S{36}) ([\s\S]*)$/.exec(told.slice(VIEWER_PROMPT.length + 1)) ?? [];
2593
+ if (!offerId) return next(e);
2594
+ const item = (await $.state.get(STATE)).value?.records.find((r) => r.offerId === offerId);
2595
+ const assignment = item
2596
+ ? (await $.state.get({ ...ASSIGNMENTS, id: item.offerId })).value
2597
+ : undefined;
2598
+ // After a restart the prompt is no longer held: say whose viewer this is.
2599
+ const text =
2600
+ assignment || 'DeepSeek worker for: ' + description.replace(/^DeepSeek #\d+ · /, '');
2601
+ return next({ ...e, props: { ...e.props, text } });
2602
+ });
2603
+ // THE VIEWER'S ROW IN THE AGENT LIST reads as the worker's: `DeepSeek` where a native
2604
+ // row names its agent type, then the host's own words for the task (its progress
2605
+ // summary, else the description) and the worker's counts. The `tenjin:` type itself
2606
+ // is the host's to name; the row's body is the one part a plugin draws.
2607
+ on('ui.render', { component: 'AgentRow' }, async ($, e, next) => {
2608
+ if (e.props.type !== TYPE) return next(e);
2609
+ const item = (await $.state.get(STATE)).value?.records.find((r) => r.nativeId === e.props.id);
2610
+ const live = item ? (await $.state.get({ ...WORKERS, id: item.offerId })).value : undefined;
2611
+ const counts = [
2612
+ live?.toolUses ? toolUses(live.toolUses) : undefined,
2613
+ live?.tokens ? tokens(live.tokens) : undefined,
2614
+ live?.elapsedMs !== undefined ? duration(live.elapsedMs) : undefined,
2615
+ ].filter((part): part is string => part !== undefined);
2616
+ const task = clean(e.props.label.split('\n')[0] ?? '', 200) || clean(e.props.description, 200);
2617
+ return next({ ...e, props: { ...e.props, body: ['DeepSeek ' + task, ...counts].join(' · ') } });
2618
+ });
2619
+ }
2620
+
2621
+ /**
2622
+ * The viewer's last step after the worker ended: what is left of its rows, its answer
2623
+ * as the parent received it (in place of its last reply's shortened text), and the end
2624
+ * line with the job's own word, counts and time.
2625
+ */
2626
+ async function endOf(
2627
+ $: Dollar,
2628
+ item: TenjinModelViewerRecord,
2629
+ view: View,
2630
+ cwd: string,
2631
+ ): Promise<string> {
2632
+ const ended = view.ended ?? {};
2633
+ const answer = typeof ended.answer === 'string' ? ended.answer : undefined;
2634
+ const rows = view.rows.splice(0).filter((row) => !answer || row.kind !== 'text');
2635
+ const said = blocksOf(rows, cwd, view).flatMap((block) => ('text' in block ? [block.text] : []));
2636
+ const [live, now] = await Promise.all([
2637
+ $.state.get({ ...WORKERS, id: item.offerId }),
2638
+ $.clock.now(),
2639
+ ]);
2640
+ // The job's own time when the CLI gives it; otherwise the time since the accept.
2641
+ const elapsedMs = Number.isSafeInteger(ended.elapsedMs)
2642
+ ? ended.elapsedMs
2643
+ : live.value
2644
+ ? Math.max(0, now - live.value.startedAt)
2645
+ : undefined;
2646
+ const counts = doneParts(
2647
+ { ...ended, ...(elapsedMs !== undefined ? { elapsedMs } : {}) },
2648
+ live.value,
2649
+ ).join(' · ');
2650
+ const state = ended.state ?? (ended.status === 'stopped' ? 'unknown' : ended.status);
2651
+ const started = ended.started ?? ended.status !== 'not_started';
2652
+ const end =
2653
+ state === 'completed'
2654
+ ? 'Done (' + counts + ')'
2655
+ : started === false
2656
+ ? endingOf({ state, started })
2657
+ : stopWord(state, ended.endedBy) + ' (' + counts + ')\n' + endingOf({ state, started });
2658
+ return [...said, ...(answer ? [answer] : []), end].join('\n\n');
2659
+ }
2660
+ /** How the viewer's transcript ends: what happened to the worker, never a run that did not happen. */
2661
+ function endingOf(activity: Json): string {
2662
+ if (activity.started === false)
2663
+ return activity.state === 'cancelled'
2664
+ ? 'Not started: the start was interrupted, so no work ran.'
2665
+ : 'Not started: Claude Code did not start, so no work ran. The parent keeps this task native.';
2666
+ return activity.state === 'cancelled'
2667
+ ? 'Interrupted: the worker was stopped before it finished. What it had done is returned to the parent.'
2668
+ : 'Stopped: the worker ended before it finished. What it had done is returned to the parent.';
2669
+ }
2670
+
2671
+ type Elements = ReturnType<Dollar['ui']['resolve']>;
2672
+ type WorkerRow = {
2673
+ state: 'running' | 'done' | 'error' | 'held';
2674
+ name: string;
2675
+ /** The native call's name, struck through: an offer stands in its place. */
2676
+ struck?: boolean;
2677
+ argument?: string;
2678
+ starting?: boolean;
2679
+ tail?: string;
2680
+ under?: string;
2681
+ ending?: WorkerEnding;
2682
+ };
2683
+ /**
2684
+ * One worker's row, from the accept call that runs it (its answer, once it has one)
2685
+ * and the worker's own record. Undefined for an answered call that says nothing of a
2686
+ * worker and has none: that call keeps the engine's row.
2687
+ */
2688
+ async function describeWorker(
2689
+ $: Dollar,
2690
+ offerId: string,
2691
+ { output, isInterrupted, isErrored }: AcceptCall,
2692
+ batched: boolean,
2693
+ described?: string,
2694
+ ): Promise<WorkerRow | undefined> {
2695
+ const said = textOf(output);
2696
+ const answer = acceptResponse(said);
2697
+ const ended = (batched ? batchOutcomes(answer)?.get(offerId) : undefined) ?? answer;
2698
+ const [held, known, offer] = await Promise.all([
2699
+ $.state.get({ ...WORKERS, id: offerId }),
2700
+ $.state.get(STATE),
2701
+ $.state.get({ ...OFFERS, id: offerId }),
2702
+ ]);
2703
+ const live = held.value;
2704
+ // Before the accept hook has run (the host is still checking the call), the offer's
2705
+ // own record names the task; after a resume, the held call's own description does.
2706
+ const title =
2707
+ live?.title ??
2708
+ known.value?.records.find((r) => r.offerId === offerId)?.title ??
2709
+ described ??
2710
+ 'subagent';
2711
+ const head = { name: 'DeepSeek', argument: title };
2712
+ const status = ended?.status;
2713
+ if (
2714
+ status === 'completed' ||
2715
+ status === 'cancelled' ||
2716
+ status === 'unknown' ||
2717
+ status === 'stopped'
2718
+ ) {
2719
+ const word = status === 'completed' ? 'Done' : stopWord(status, ended!.endedBy);
2720
+ return {
2721
+ ...head,
2722
+ state: status === 'completed' ? 'done' : 'error',
2723
+ ending: { word, parts: doneParts(ended!, live) },
2724
+ };
2725
+ }
2726
+ // Nothing ran, and the answer says so: a start that never finished, or a refused accept.
2727
+ if (status === 'not_started' || typeof ended?.action === 'string')
2728
+ return {
2729
+ ...head,
2730
+ state: isErrored || status === 'not_started' ? 'error' : 'held',
2731
+ ending: {
2732
+ word: 'Not started',
2733
+ parts: typeof ended?.elapsedMs === 'number' ? [duration(ended.elapsedMs)] : [],
2734
+ },
2735
+ };
2736
+ // NOT THE WORKER'S ANSWER: nothing yet, an Esc, or the host's own notice
2737
+ // for a call it moved to the background after two minutes. The worker's
2738
+ // record says where it stands; a missing answer never reads as an end.
2739
+ if (live?.ended)
2740
+ return {
2741
+ ...head,
2742
+ state: live.ended === 'completed' ? 'done' : 'error',
2743
+ ending: workerEnding(live),
2744
+ };
2745
+ if (isInterrupted)
2746
+ return {
2747
+ ...head,
2748
+ state: 'error',
2749
+ ending: {
2750
+ word: 'Interrupted',
2751
+ parts: live?.elapsedMs !== undefined ? [duration(live.elapsedMs)] : [],
2752
+ },
2753
+ };
2754
+ // A BACKGROUND WORKER'S ROW READS AS A NATIVE BACKGROUND AGENT'S while it runs: one
2755
+ // still line, its progress in the agent list. Its end line follows when it has ended,
2756
+ // and its result arrives as a message of its own.
2757
+ if (startedInBackground(ended) || (live && offer.value?.background)) {
2758
+ // After a reload or a resume nothing here follows it: the CLI is asked how it stands.
2759
+ if (!liveWorkers.has(offerId)) adopt($, offerId, title);
2760
+ return { ...head, state: 'running', under: 'Backgrounded agent (↓ to manage)' };
2761
+ }
2762
+ const moved = output !== undefined && HOST_MOVED.test(said ?? '');
2763
+ if (output !== undefined && !live && !moved) return undefined;
2764
+ // A running row nothing here follows, after a reload or a resume: the CLI is asked.
2765
+ if ((live || moved) && !liveWorkers.has(offerId)) adopt($, offerId, title);
2766
+ // From the moment of accept: Claude Code is still starting until the first tick says more.
2767
+ const starting = live ? live.state !== 'running' : !moved;
2768
+ const parts = [
2769
+ !live && moved ? 'running in the background' : undefined,
2770
+ live?.toolUses ? toolUses(live.toolUses) : undefined,
2771
+ live?.tokens ? tokens(live.tokens) : undefined,
2772
+ live?.elapsedMs !== undefined ? duration(live.elapsedMs) : undefined,
2773
+ live?.spentAtomic ? dollars(live.spentAtomic) + ' so far' : undefined,
2774
+ ].filter((part): part is string => part !== undefined);
2775
+ return {
2776
+ ...head,
2777
+ state: 'running',
2778
+ starting,
2779
+ ...(parts.length ? { tail: ' · ' + parts.join(' · ') } : {}),
2780
+ ...(starting || !live ? {} : { under: live.current ?? 'Working' }),
2781
+ };
2782
+ }
2783
+ /**
2784
+ * WHAT AN ACCEPT CALL DRAWS: the workers whose held Agent row is not there to draw
2785
+ * them (see `heldRows`), as one row or one group. Nothing where each of its workers
2786
+ * draws on its own held row: the accept adds no row of its own, as the request call
2787
+ * that took a held `Web Search` draws none.
2788
+ */
2789
+ async function acceptRows(
2790
+ $: Dollar,
2791
+ ui: Elements,
2792
+ surface: string,
2793
+ offerIds: string[],
2794
+ call: AcceptCall & { tool_use_id?: string },
2795
+ isExpanded?: boolean,
2796
+ ) {
2797
+ noteAccept($, call.tool_use_id, offerIds, call);
2798
+ const batched = offerIds.length > 1;
2799
+ const described = await Promise.all(
2800
+ offerIds.map((offerId) => describeWorker($, offerId, call, batched)),
2801
+ );
2802
+ if (described.some((row) => row === undefined)) return undefined;
2803
+ const { Box } = ui;
2804
+ const kept = offerIds.flatMap((offerId, index) =>
2805
+ inPlace(surface, offerId) ? [] : [{ offerId, row: described[index]! }],
2806
+ );
2807
+ if (kept.length === 0) return <Box display="none" />;
2808
+ const rows = kept.map((item) => item.row);
2809
+ if (rows.length === 1) return workerRow(ui, rows[0]!);
2810
+ const ids = kept.map((item) => item.offerId);
2811
+ if (!isExpanded) return workerGroup(ui, rows, ids);
2812
+ return (
2813
+ <Box flexDirection="column">
2814
+ {rows.map((row, index) => (
2815
+ <Box key={ids[index]}>{workerRow(ui, row)}</Box>
2816
+ ))}
2817
+ </Box>
2818
+ );
2819
+ }
2820
+ /** A tool row as the engine draws one: the dot, the name bold, the input in
2821
+ * parentheses, a dim tail, and one dim line under it. */
2822
+ function workerRow({ Box, Text }: Elements, row: WorkerRow) {
2823
+ const dot =
2824
+ row.state === 'done'
2825
+ ? { color: 'success' }
2826
+ : row.state === 'error'
2827
+ ? { color: 'error' }
2828
+ : { dimColor: true };
2829
+ const head = (
2830
+ <Box key="head" flexDirection="row">
2831
+ <Box minWidth={2}>
2832
+ <Text {...dot}>⏺</Text>
2833
+ </Box>
2834
+ <Box flexShrink={0}>
2835
+ <Text bold strikethrough={row.struck === true} wrap="truncate-end">
2836
+ {row.name}
2837
+ </Text>
2838
+ </Box>
2839
+ <Box flexWrap="nowrap">
2840
+ <Text wrap="truncate-end">
2841
+ {row.argument !== undefined ? '(' + row.argument + ')' : ''}
2842
+ </Text>
2843
+ <Text dimColor>{(row.starting ? ' · starting' : '') + (row.tail ?? '')}</Text>
2844
+ </Box>
2845
+ </Box>
2846
+ );
2847
+ const detail = row.ending ? endingText(row.ending) : row.under;
2848
+ const under =
2849
+ detail === undefined
2850
+ ? []
2851
+ : [
2852
+ <Box key="under" flexDirection="row">
2853
+ <Text dimColor>{' ⎿ '}</Text>
2854
+ <Text dimColor wrap="truncate-end">
2855
+ {clean(detail, 400)}
2856
+ </Text>
2857
+ </Box>,
2858
+ ];
2859
+ return (
2860
+ <Box flexDirection="column" marginTop={1}>
2861
+ {[head, ...under]}
2862
+ </Box>
2863
+ );
2864
+ }
2865
+ /** A compact batch keeps the live state of every accepted worker visible. */
2866
+ function workerGroup({ Box, Text }: Elements, rows: WorkerRow[], offerIds: string[]) {
2867
+ const finished = rows.filter((row) => row.state === 'done').length;
2868
+ const running = rows.some((row) => row.state === 'running');
2869
+ const allFinished = finished === rows.length;
2870
+ const summary = running
2871
+ ? `Running ${rows.length} DeepSeek agents…`
2872
+ : allFinished
2873
+ ? `${rows.length} DeepSeek agents finished`
2874
+ : `${finished} of ${rows.length} DeepSeek agents finished`;
2875
+ const dot = running ? { dimColor: true } : { color: allFinished ? 'success' : 'error' };
2876
+ return (
2877
+ <Box flexDirection="column" marginTop={1}>
2878
+ <Box flexDirection="row">
2879
+ <Box minWidth={2}>
2880
+ <Text {...dot}>⏺</Text>
2881
+ </Box>
2882
+ <Text>{summary}</Text>
2883
+ </Box>
2884
+ {rows.map((row, index) => {
2885
+ const last = index === rows.length - 1;
2886
+ const detail =
2887
+ row.ending?.word ?? row.under ?? (row.starting ? 'Initializing…' : undefined);
2888
+ const tail = row.ending?.parts.length ? ' · ' + row.ending.parts.join(' · ') : row.tail;
2889
+ return (
2890
+ <Box key={offerIds[index]} flexDirection="column">
2891
+ <Box flexDirection="row">
2892
+ <Text dimColor>{last ? ' └ ' : ' ├ '}</Text>
2893
+ <Text bold wrap="truncate-end">
2894
+ {row.argument ?? row.name}
2895
+ </Text>
2896
+ <Text dimColor wrap="truncate-end">
2897
+ {tail ?? ''}
2898
+ </Text>
2899
+ </Box>
2900
+ {detail !== undefined ? (
2901
+ <Box flexDirection="row">
2902
+ <Text dimColor>{last ? ' ⎿ ' : ' │ ⎿ '}</Text>
2903
+ <Text dimColor wrap="truncate-end">
2904
+ {clean(detail, 400)}
2905
+ </Text>
2906
+ </Box>
2907
+ ) : null}
2908
+ </Box>
2909
+ );
2910
+ })}
2911
+ </Box>
2912
+ );
2913
+ }
2914
+
2915
+ /** An accept call's own answer, which its live row already says: a worker
2916
+ * handback (it carries `elapsedMs`) or a refusal to start one. A cancel's
2917
+ * short status is not one, and keeps the engine's result block. */
2918
+ function acceptAnswer(answer: Json | undefined): boolean {
2919
+ return (
2920
+ typeof answer?.elapsedMs === 'number' ||
2921
+ typeof answer?.action === 'string' ||
2922
+ startedInBackground(answer)
2923
+ );
2924
+ }
2925
+ /** An accept call's answer for a background call: its worker started and runs on (`model-mcp.ts`). */
2926
+ function startedInBackground(answer: Json | undefined): boolean {
2927
+ return answer?.status === 'started' && answer.background === true;
2928
+ }
2929
+ /** The `Done (…)` line's counts, from the handback, as a native subagent's: uses, tokens, time, then spend. */
2930
+ function doneParts(ended: Json, live: TenjinModelWorker | undefined): string[] {
2931
+ const count = (value: unknown) =>
2932
+ Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : undefined;
2933
+ const uses = count(ended.toolUses) ?? live?.toolUses ?? 0;
2934
+ const used = count(ended.tokens) ?? live?.tokens;
2935
+ const elapsed = count(ended.elapsedMs);
2936
+ const spend = record(ended.spend);
2937
+ const actual =
2938
+ typeof spend?.actualAtomic === 'string' && /^\d{1,30}$/.test(spend.actualAtomic)
2939
+ ? spend.actualAtomic
2940
+ : undefined;
2941
+ const unresolved = Array.isArray(spend?.uncertain) && spend.uncertain.length > 0;
2942
+ const omitted = count(ended.omittedBlocks) ?? count(record(ended.omitted)?.blocks);
2943
+ return [
2944
+ toolUses(uses),
2945
+ ...(used !== undefined ? [tokens(used)] : []),
2946
+ ...(elapsed !== undefined ? [duration(elapsed)] : []),
2947
+ ...(actual !== undefined
2948
+ ? [dollars(actual) + (unresolved ? ' · settlement unresolved' : '')]
2949
+ : spend?.accounting === 'unknown'
2950
+ ? ['spend unknown']
2951
+ : []),
2952
+ ...(omitted ? [omittedWords(omitted)] : []),
2953
+ ];
2954
+ }
2955
+ /**
2956
+ * A held Agent call, as the local hook answered it (`register.tsx`): refused with an
2957
+ * offer, whose id and cap are read from the refusal's text, or held and not started.
2958
+ * Told by the text's first line.
2959
+ */
2960
+ function heldOffer(
2961
+ output: unknown,
2962
+ ): { offerId: string; capAtomic?: string } | 'unavailable' | undefined {
2963
+ const capOf = (offer: Json | undefined): { capAtomic?: string } => {
2964
+ const cap = offer?.capAtomic;
2965
+ return typeof cap === 'string' && /^[1-9][0-9]{0,29}$/.test(cap) ? { capAtomic: cap } : {};
2966
+ };
2967
+ // The refusal, as the row holds it: its text, bare or inside the host's own wrapping.
2968
+ const said =
2969
+ typeof output === 'string'
2970
+ ? output
2971
+ : (textOf(output) ??
2972
+ [record(output)?.text, record(output)?.error, record(output)?.message].find(
2973
+ (text): text is string => typeof text === 'string',
2974
+ ));
2975
+ if (said) {
2976
+ const at = said.indexOf(HELD_WITH_OFFER + ' (offer ');
2977
+ if (at >= 0) {
2978
+ const offerId = said.slice(at + HELD_WITH_OFFER.length + 8, at + HELD_WITH_OFFER.length + 44);
2979
+ if (!UUID.test(offerId)) return undefined;
2980
+ // The offer is the text's last line, as the CLI wrote it.
2981
+ const from = said.indexOf('\n{', at);
2982
+ return { offerId, ...capOf(from < 0 ? undefined : json(said.slice(from + 1).trim())) };
2983
+ }
2984
+ if (said.includes(HELD_NOT_STARTED)) return 'unavailable';
2985
+ }
2986
+ return undefined;
2987
+ }