agent-relay 2.0.28 → 2.0.32

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 (894) hide show
  1. package/README.md +19 -0
  2. package/dist/index.cjs +85691 -0
  3. package/dist/src/bridge/index.d.ts.map +1 -0
  4. package/dist/src/bridge/index.js.map +1 -0
  5. package/dist/src/cli/commands/doctor.d.ts +2 -0
  6. package/dist/src/cli/commands/doctor.d.ts.map +1 -0
  7. package/dist/src/cli/commands/doctor.js +451 -0
  8. package/dist/src/cli/commands/doctor.js.map +1 -0
  9. package/dist/src/cli/index.d.ts.map +1 -0
  10. package/dist/src/cli/index.js +29 -1
  11. package/dist/src/cli/index.js.map +1 -0
  12. package/dist/src/config/relay-config.d.ts.map +1 -0
  13. package/dist/src/config/relay-config.js.map +1 -0
  14. package/dist/src/continuity/index.d.ts.map +1 -0
  15. package/dist/src/continuity/index.js.map +1 -0
  16. package/dist/src/daemon/index.d.ts.map +1 -0
  17. package/dist/src/daemon/index.js.map +1 -0
  18. package/dist/src/health-worker-manager.d.ts.map +1 -0
  19. package/dist/src/health-worker-manager.js.map +1 -0
  20. package/dist/src/health-worker.d.ts.map +1 -0
  21. package/dist/src/health-worker.js.map +1 -0
  22. package/dist/src/hooks/index.d.ts.map +1 -0
  23. package/dist/src/hooks/index.js.map +1 -0
  24. package/dist/src/index.d.ts.map +1 -0
  25. package/dist/src/index.js.map +1 -0
  26. package/dist/src/memory/index.d.ts.map +1 -0
  27. package/dist/src/memory/index.js.map +1 -0
  28. package/dist/src/policy/index.d.ts.map +1 -0
  29. package/dist/src/policy/index.js.map +1 -0
  30. package/dist/src/protocol/index.d.ts.map +1 -0
  31. package/dist/src/protocol/index.js.map +1 -0
  32. package/dist/src/resiliency/index.d.ts.map +1 -0
  33. package/dist/src/resiliency/index.js.map +1 -0
  34. package/dist/src/shared/cli-auth-config.d.ts.map +1 -0
  35. package/dist/src/shared/cli-auth-config.js.map +1 -0
  36. package/dist/src/state/index.d.ts.map +1 -0
  37. package/dist/src/state/index.js.map +1 -0
  38. package/dist/src/storage/index.d.ts.map +1 -0
  39. package/dist/src/storage/index.js.map +1 -0
  40. package/dist/src/trajectory/index.d.ts.map +1 -0
  41. package/dist/src/trajectory/index.js.map +1 -0
  42. package/dist/src/utils/index.d.ts.map +1 -0
  43. package/dist/src/utils/index.js.map +1 -0
  44. package/dist/src/wrapper/index.d.ts.map +1 -0
  45. package/dist/src/wrapper/index.js.map +1 -0
  46. package/package.json +83 -20
  47. package/packages/api-types/dist/index.d.ts.map +1 -0
  48. package/packages/api-types/dist/index.js.map +1 -0
  49. package/packages/api-types/dist/schemas/agent.d.ts.map +1 -0
  50. package/packages/api-types/dist/schemas/agent.js.map +1 -0
  51. package/packages/api-types/dist/schemas/api.d.ts.map +1 -0
  52. package/packages/api-types/dist/schemas/api.js.map +1 -0
  53. package/packages/api-types/dist/schemas/decision.d.ts.map +1 -0
  54. package/packages/api-types/dist/schemas/decision.js.map +1 -0
  55. package/packages/api-types/dist/schemas/fleet.d.ts.map +1 -0
  56. package/packages/api-types/dist/schemas/fleet.js.map +1 -0
  57. package/packages/api-types/dist/schemas/history.d.ts.map +1 -0
  58. package/packages/api-types/dist/schemas/history.js.map +1 -0
  59. package/packages/api-types/dist/schemas/index.d.ts.map +1 -0
  60. package/packages/api-types/dist/schemas/index.js.map +1 -0
  61. package/packages/api-types/dist/schemas/message.d.ts.map +1 -0
  62. package/packages/api-types/dist/schemas/message.js.map +1 -0
  63. package/packages/api-types/dist/schemas/session.d.ts.map +1 -0
  64. package/packages/api-types/dist/schemas/session.js.map +1 -0
  65. package/packages/api-types/dist/schemas/task.d.ts.map +1 -0
  66. package/packages/api-types/dist/schemas/task.js.map +1 -0
  67. package/packages/api-types/package.json +1 -1
  68. package/packages/api-types/src/index.ts +22 -0
  69. package/packages/api-types/src/schemas/agent.test.ts +164 -0
  70. package/packages/api-types/src/schemas/agent.ts +110 -0
  71. package/packages/api-types/src/schemas/api.test.ts +372 -0
  72. package/packages/api-types/src/schemas/api.ts +194 -0
  73. package/packages/api-types/src/schemas/decision.test.ts +324 -0
  74. package/packages/api-types/src/schemas/decision.ts +136 -0
  75. package/packages/api-types/src/schemas/fleet.test.ts +212 -0
  76. package/packages/api-types/src/schemas/fleet.ts +83 -0
  77. package/packages/api-types/src/schemas/history.test.ts +242 -0
  78. package/packages/api-types/src/schemas/history.ts +84 -0
  79. package/packages/api-types/src/schemas/index.ts +148 -0
  80. package/packages/api-types/src/schemas/message.test.ts +192 -0
  81. package/packages/api-types/src/schemas/message.ts +98 -0
  82. package/packages/api-types/src/schemas/session.test.ts +104 -0
  83. package/packages/api-types/src/schemas/session.ts +40 -0
  84. package/packages/api-types/src/schemas/task.test.ts +192 -0
  85. package/packages/api-types/src/schemas/task.ts +78 -0
  86. package/packages/api-types/tsconfig.json +19 -0
  87. package/packages/api-types/vitest.config.ts +9 -0
  88. package/packages/benchmark/README.md +200 -0
  89. package/packages/benchmark/datasets/coding-tasks.yaml +127 -0
  90. package/packages/benchmark/datasets/coordination-tasks.yaml +122 -0
  91. package/packages/benchmark/dist/benchmark.d.ts +47 -0
  92. package/packages/benchmark/dist/benchmark.d.ts.map +1 -0
  93. package/packages/benchmark/dist/benchmark.js +224 -0
  94. package/packages/benchmark/dist/benchmark.js.map +1 -0
  95. package/packages/benchmark/dist/cli.d.ts +8 -0
  96. package/packages/benchmark/dist/cli.d.ts.map +1 -0
  97. package/packages/benchmark/dist/cli.js +185 -0
  98. package/packages/benchmark/dist/cli.js.map +1 -0
  99. package/packages/benchmark/dist/harbor.d.ts +53 -0
  100. package/packages/benchmark/dist/harbor.d.ts.map +1 -0
  101. package/packages/benchmark/dist/harbor.js +127 -0
  102. package/packages/benchmark/dist/harbor.js.map +1 -0
  103. package/packages/benchmark/dist/index.d.ts +48 -0
  104. package/packages/benchmark/dist/index.d.ts.map +1 -0
  105. package/packages/benchmark/dist/index.js +50 -0
  106. package/packages/benchmark/dist/index.js.map +1 -0
  107. package/packages/benchmark/dist/runners/base.d.ts +63 -0
  108. package/packages/benchmark/dist/runners/base.d.ts.map +1 -0
  109. package/packages/benchmark/dist/runners/base.js +155 -0
  110. package/packages/benchmark/dist/runners/base.js.map +1 -0
  111. package/packages/benchmark/dist/runners/index.d.ts +10 -0
  112. package/packages/benchmark/dist/runners/index.d.ts.map +1 -0
  113. package/packages/benchmark/dist/runners/index.js +10 -0
  114. package/packages/benchmark/dist/runners/index.js.map +1 -0
  115. package/packages/benchmark/dist/runners/single.d.ts +19 -0
  116. package/packages/benchmark/dist/runners/single.d.ts.map +1 -0
  117. package/packages/benchmark/dist/runners/single.js +111 -0
  118. package/packages/benchmark/dist/runners/single.js.map +1 -0
  119. package/packages/benchmark/dist/runners/subagent.d.ts +32 -0
  120. package/packages/benchmark/dist/runners/subagent.d.ts.map +1 -0
  121. package/packages/benchmark/dist/runners/subagent.js +212 -0
  122. package/packages/benchmark/dist/runners/subagent.js.map +1 -0
  123. package/packages/benchmark/dist/runners/swarm.d.ts +36 -0
  124. package/packages/benchmark/dist/runners/swarm.d.ts.map +1 -0
  125. package/packages/benchmark/dist/runners/swarm.js +273 -0
  126. package/packages/benchmark/dist/runners/swarm.js.map +1 -0
  127. package/packages/benchmark/dist/types.d.ts +178 -0
  128. package/packages/benchmark/dist/types.d.ts.map +1 -0
  129. package/packages/benchmark/dist/types.js +16 -0
  130. package/packages/benchmark/dist/types.js.map +1 -0
  131. package/packages/benchmark/package.json +80 -0
  132. package/packages/benchmark/src/benchmark.ts +298 -0
  133. package/packages/benchmark/src/cli.ts +240 -0
  134. package/packages/benchmark/src/harbor.ts +170 -0
  135. package/packages/benchmark/src/index.ts +73 -0
  136. package/packages/benchmark/src/runners/base.ts +204 -0
  137. package/packages/benchmark/src/runners/index.ts +10 -0
  138. package/packages/benchmark/src/runners/single.ts +121 -0
  139. package/packages/benchmark/src/runners/subagent.ts +240 -0
  140. package/packages/benchmark/src/runners/swarm.ts +326 -0
  141. package/packages/benchmark/src/types.ts +205 -0
  142. package/packages/benchmark/tsconfig.json +20 -0
  143. package/packages/bridge/dist/index.d.ts.map +1 -0
  144. package/packages/bridge/dist/index.js.map +1 -0
  145. package/packages/bridge/dist/multi-project-client.d.ts.map +1 -0
  146. package/packages/bridge/dist/multi-project-client.js.map +1 -0
  147. package/packages/bridge/dist/shadow-cli.d.ts.map +1 -0
  148. package/packages/bridge/dist/shadow-cli.js.map +1 -0
  149. package/packages/bridge/dist/spawner.d.ts.map +1 -0
  150. package/packages/bridge/dist/spawner.js +15 -2
  151. package/packages/bridge/dist/spawner.js.map +1 -0
  152. package/packages/bridge/dist/types.d.ts.map +1 -0
  153. package/packages/bridge/dist/types.js.map +1 -0
  154. package/packages/bridge/dist/utils.d.ts.map +1 -0
  155. package/packages/bridge/dist/utils.js.map +1 -0
  156. package/packages/bridge/package.json +8 -8
  157. package/packages/bridge/src/index.ts +25 -0
  158. package/packages/bridge/src/multi-project-client.test.ts +340 -0
  159. package/packages/bridge/src/multi-project-client.ts +469 -0
  160. package/packages/bridge/src/shadow-cli.ts +95 -0
  161. package/packages/bridge/src/spawner-mcp.test.ts +505 -0
  162. package/packages/bridge/src/spawner.ts +1724 -0
  163. package/packages/bridge/src/types.ts +145 -0
  164. package/packages/bridge/src/utils.test.ts +98 -0
  165. package/packages/bridge/src/utils.ts +67 -0
  166. package/packages/bridge/tsconfig.json +29 -0
  167. package/packages/bridge/vitest.config.ts +9 -0
  168. package/packages/cli-tester/dist/index.d.ts.map +1 -0
  169. package/packages/cli-tester/dist/index.js.map +1 -0
  170. package/packages/cli-tester/dist/utils/credential-check.d.ts.map +1 -0
  171. package/packages/cli-tester/dist/utils/credential-check.js.map +1 -0
  172. package/packages/cli-tester/dist/utils/socket-client.d.ts.map +1 -0
  173. package/packages/cli-tester/dist/utils/socket-client.js.map +1 -0
  174. package/packages/cli-tester/docker/Dockerfile +61 -0
  175. package/packages/cli-tester/docker/docker-compose.yml +71 -0
  176. package/packages/cli-tester/package.json +1 -1
  177. package/packages/cli-tester/src/index.ts +40 -0
  178. package/packages/cli-tester/src/utils/credential-check.ts +284 -0
  179. package/packages/cli-tester/src/utils/socket-client.ts +211 -0
  180. package/packages/cli-tester/tests/credential-check.test.ts +56 -0
  181. package/packages/cli-tester/tsconfig.json +11 -0
  182. package/packages/config/dist/agent-config.d.ts.map +1 -0
  183. package/packages/config/dist/agent-config.js.map +1 -0
  184. package/packages/config/dist/bridge-config.d.ts.map +1 -0
  185. package/packages/config/dist/bridge-config.js.map +1 -0
  186. package/packages/config/dist/bridge-utils.d.ts.map +1 -0
  187. package/packages/config/dist/bridge-utils.js.map +1 -0
  188. package/packages/config/dist/cli-auth-config.d.ts.map +1 -0
  189. package/packages/config/dist/cli-auth-config.js.map +1 -0
  190. package/packages/config/dist/cloud-config.d.ts.map +1 -0
  191. package/packages/config/dist/cloud-config.js.map +1 -0
  192. package/packages/config/dist/index.d.ts.map +1 -0
  193. package/packages/config/dist/index.js.map +1 -0
  194. package/packages/config/dist/project-namespace.d.ts.map +1 -0
  195. package/packages/config/dist/project-namespace.js.map +1 -0
  196. package/packages/config/dist/relay-config.d.ts.map +1 -0
  197. package/packages/config/dist/relay-config.js.map +1 -0
  198. package/packages/config/dist/relay-file-writer.d.ts.map +1 -0
  199. package/packages/config/dist/relay-file-writer.js.map +1 -0
  200. package/packages/config/dist/schemas.d.ts.map +1 -0
  201. package/packages/config/dist/schemas.js.map +1 -0
  202. package/packages/config/dist/shadow-config.d.ts.map +1 -0
  203. package/packages/config/dist/shadow-config.js.map +1 -0
  204. package/packages/config/dist/teams-config.d.ts.map +1 -0
  205. package/packages/config/dist/teams-config.js.map +1 -0
  206. package/packages/config/dist/trajectory-config.d.ts.map +1 -0
  207. package/packages/config/dist/trajectory-config.js.map +1 -0
  208. package/packages/config/package.json +2 -2
  209. package/packages/config/src/agent-config.test.ts +245 -0
  210. package/packages/config/src/agent-config.ts +160 -0
  211. package/packages/config/src/bridge-config.test.ts +132 -0
  212. package/packages/config/src/bridge-config.ts +189 -0
  213. package/packages/config/src/bridge-utils.ts +59 -0
  214. package/packages/config/src/cli-auth-config.ts +548 -0
  215. package/packages/config/src/cloud-config.ts +208 -0
  216. package/packages/config/src/index.ts +12 -0
  217. package/packages/config/src/project-namespace.ts +344 -0
  218. package/packages/config/src/relay-config.test.ts +51 -0
  219. package/packages/config/src/relay-config.ts +36 -0
  220. package/packages/config/src/relay-file-writer.test.ts +351 -0
  221. package/packages/config/src/relay-file-writer.ts +508 -0
  222. package/packages/config/src/schemas.test.ts +59 -0
  223. package/packages/config/src/schemas.ts +201 -0
  224. package/packages/config/src/shadow-config.ts +205 -0
  225. package/packages/config/src/teams-config.ts +135 -0
  226. package/packages/config/src/trajectory-config.ts +222 -0
  227. package/packages/config/tsconfig.json +21 -0
  228. package/packages/config/vitest.config.ts +9 -0
  229. package/packages/continuity/dist/formatter.d.ts.map +1 -0
  230. package/packages/continuity/dist/formatter.js.map +1 -0
  231. package/packages/continuity/dist/handoff-store.d.ts.map +1 -0
  232. package/packages/continuity/dist/handoff-store.js.map +1 -0
  233. package/packages/continuity/dist/index.d.ts.map +1 -0
  234. package/packages/continuity/dist/index.js.map +1 -0
  235. package/packages/continuity/dist/ledger-store.d.ts.map +1 -0
  236. package/packages/continuity/dist/ledger-store.js.map +1 -0
  237. package/packages/continuity/dist/manager.d.ts.map +1 -0
  238. package/packages/continuity/dist/manager.js.map +1 -0
  239. package/packages/continuity/dist/parser.d.ts.map +1 -0
  240. package/packages/continuity/dist/parser.js.map +1 -0
  241. package/packages/continuity/dist/types.d.ts.map +1 -0
  242. package/packages/continuity/dist/types.js.map +1 -0
  243. package/packages/continuity/package.json +1 -1
  244. package/packages/continuity/src/formatter.ts +371 -0
  245. package/packages/continuity/src/handoff-store.ts +523 -0
  246. package/packages/continuity/src/index.ts +9 -0
  247. package/packages/continuity/src/ledger-store.ts +594 -0
  248. package/packages/continuity/src/manager.test.ts +291 -0
  249. package/packages/continuity/src/manager.ts +774 -0
  250. package/packages/continuity/src/parser.test.ts +292 -0
  251. package/packages/continuity/src/parser.ts +680 -0
  252. package/packages/continuity/src/types.ts +211 -0
  253. package/packages/continuity/tsconfig.json +21 -0
  254. package/packages/continuity/vitest.config.ts +9 -0
  255. package/packages/daemon/dist/agent-manager.d.ts.map +1 -0
  256. package/packages/daemon/dist/agent-manager.js.map +1 -0
  257. package/packages/daemon/dist/agent-registry.d.ts.map +1 -0
  258. package/packages/daemon/dist/agent-registry.js.map +1 -0
  259. package/packages/daemon/dist/agent-signing.d.ts.map +1 -0
  260. package/packages/daemon/dist/agent-signing.js.map +1 -0
  261. package/packages/daemon/dist/api.d.ts.map +1 -0
  262. package/packages/daemon/dist/api.js.map +1 -0
  263. package/packages/daemon/dist/auth.d.ts.map +1 -0
  264. package/packages/daemon/dist/auth.js.map +1 -0
  265. package/packages/daemon/dist/channel-membership-store.d.ts.map +1 -0
  266. package/packages/daemon/dist/channel-membership-store.js.map +1 -0
  267. package/packages/daemon/dist/cli-auth.d.ts.map +1 -0
  268. package/packages/daemon/dist/cli-auth.js.map +1 -0
  269. package/packages/daemon/dist/cloud-sync.d.ts.map +1 -0
  270. package/packages/daemon/dist/cloud-sync.js.map +1 -0
  271. package/packages/daemon/dist/connection.d.ts.map +1 -0
  272. package/packages/daemon/dist/connection.js.map +1 -0
  273. package/packages/daemon/dist/consensus-integration.d.ts.map +1 -0
  274. package/packages/daemon/dist/consensus-integration.js.map +1 -0
  275. package/packages/daemon/dist/consensus.d.ts.map +1 -0
  276. package/packages/daemon/dist/consensus.js.map +1 -0
  277. package/packages/daemon/dist/delivery-tracker.d.ts.map +1 -0
  278. package/packages/daemon/dist/delivery-tracker.js.map +1 -0
  279. package/packages/daemon/dist/enhanced-features.d.ts.map +1 -0
  280. package/packages/daemon/dist/enhanced-features.js.map +1 -0
  281. package/packages/daemon/dist/index.d.ts.map +1 -0
  282. package/packages/daemon/dist/index.js.map +1 -0
  283. package/packages/daemon/dist/migrations/index.d.ts.map +1 -0
  284. package/packages/daemon/dist/migrations/index.js.map +1 -0
  285. package/packages/daemon/dist/orchestrator.d.ts.map +1 -0
  286. package/packages/daemon/dist/orchestrator.js.map +1 -0
  287. package/packages/daemon/dist/rate-limiter.d.ts.map +1 -0
  288. package/packages/daemon/dist/rate-limiter.js.map +1 -0
  289. package/packages/daemon/dist/registry.d.ts.map +1 -0
  290. package/packages/daemon/dist/registry.js.map +1 -0
  291. package/packages/daemon/dist/relay-ledger.d.ts.map +1 -0
  292. package/packages/daemon/dist/relay-ledger.js.map +1 -0
  293. package/packages/daemon/dist/relay-watchdog.d.ts.map +1 -0
  294. package/packages/daemon/dist/relay-watchdog.js.map +1 -0
  295. package/packages/daemon/dist/repo-manager.d.ts.map +1 -0
  296. package/packages/daemon/dist/repo-manager.js.map +1 -0
  297. package/packages/daemon/dist/router.d.ts.map +1 -0
  298. package/packages/daemon/dist/router.js.map +1 -0
  299. package/packages/daemon/dist/server.d.ts +1 -0
  300. package/packages/daemon/dist/server.d.ts.map +1 -0
  301. package/packages/daemon/dist/server.js +46 -16
  302. package/packages/daemon/dist/server.js.map +1 -0
  303. package/packages/daemon/dist/spawn-manager.d.ts.map +1 -0
  304. package/packages/daemon/dist/spawn-manager.js.map +1 -0
  305. package/packages/daemon/dist/sync-queue.d.ts.map +1 -0
  306. package/packages/daemon/dist/sync-queue.js.map +1 -0
  307. package/packages/daemon/dist/types.d.ts.map +1 -0
  308. package/packages/daemon/dist/types.js.map +1 -0
  309. package/packages/daemon/dist/workspace-manager.d.ts.map +1 -0
  310. package/packages/daemon/dist/workspace-manager.js.map +1 -0
  311. package/packages/daemon/package.json +12 -12
  312. package/packages/daemon/src/agent-manager.ts +679 -0
  313. package/packages/daemon/src/agent-registry.ts +284 -0
  314. package/packages/daemon/src/agent-signing.ts +707 -0
  315. package/packages/daemon/src/api.ts +1012 -0
  316. package/packages/daemon/src/auth.ts +276 -0
  317. package/packages/daemon/src/channel-membership-store.ts +217 -0
  318. package/packages/daemon/src/cli-auth.ts +906 -0
  319. package/packages/daemon/src/cloud-sync.ts +902 -0
  320. package/packages/daemon/src/connection.ts +534 -0
  321. package/packages/daemon/src/consensus-integration.ts +510 -0
  322. package/packages/daemon/src/consensus.ts +848 -0
  323. package/packages/daemon/src/delivery-tracker.ts +145 -0
  324. package/packages/daemon/src/enhanced-features.ts +390 -0
  325. package/packages/daemon/src/index.ts +52 -0
  326. package/packages/daemon/src/migrations/0001_initial.sql +72 -0
  327. package/packages/daemon/src/migrations/index.test.ts +195 -0
  328. package/packages/daemon/src/migrations/index.ts +286 -0
  329. package/packages/daemon/src/orchestrator.test.ts +231 -0
  330. package/packages/daemon/src/orchestrator.ts +1376 -0
  331. package/packages/daemon/src/rate-limiter.ts +172 -0
  332. package/packages/daemon/src/registry.ts +8 -0
  333. package/packages/daemon/src/relay-ledger.test.ts +358 -0
  334. package/packages/daemon/src/relay-ledger.ts +713 -0
  335. package/packages/daemon/src/relay-watchdog.test.ts +881 -0
  336. package/packages/daemon/src/relay-watchdog.ts +785 -0
  337. package/packages/daemon/src/repo-manager.ts +468 -0
  338. package/packages/daemon/src/router.test.ts +149 -0
  339. package/packages/daemon/src/router.ts +1885 -0
  340. package/packages/daemon/src/server.ts +1871 -0
  341. package/packages/daemon/src/spawn-manager.ts +275 -0
  342. package/packages/daemon/src/sync-queue.ts +477 -0
  343. package/packages/daemon/src/types.ts +158 -0
  344. package/packages/daemon/src/workspace-manager.ts +371 -0
  345. package/packages/daemon/tsconfig.json +21 -0
  346. package/packages/hooks/dist/browser.d.ts.map +1 -0
  347. package/packages/hooks/dist/browser.js.map +1 -0
  348. package/packages/hooks/dist/emitter.d.ts.map +1 -0
  349. package/packages/hooks/dist/emitter.js.map +1 -0
  350. package/packages/hooks/dist/inbox-check/hook.d.ts.map +1 -0
  351. package/packages/hooks/dist/inbox-check/hook.js.map +1 -0
  352. package/packages/hooks/dist/inbox-check/index.d.ts.map +1 -0
  353. package/packages/hooks/dist/inbox-check/index.js.map +1 -0
  354. package/packages/hooks/dist/inbox-check/types.d.ts.map +1 -0
  355. package/packages/hooks/dist/inbox-check/types.js.map +1 -0
  356. package/packages/hooks/dist/inbox-check/utils.d.ts.map +1 -0
  357. package/packages/hooks/dist/inbox-check/utils.js.map +1 -0
  358. package/packages/hooks/dist/index.d.ts.map +1 -0
  359. package/packages/hooks/dist/index.js.map +1 -0
  360. package/packages/hooks/dist/registry.d.ts.map +1 -0
  361. package/packages/hooks/dist/registry.js.map +1 -0
  362. package/packages/hooks/dist/trajectory-hooks.d.ts.map +1 -0
  363. package/packages/hooks/dist/trajectory-hooks.js.map +1 -0
  364. package/packages/hooks/dist/types.d.ts.map +1 -0
  365. package/packages/hooks/dist/types.js.map +1 -0
  366. package/packages/hooks/package.json +4 -4
  367. package/packages/hooks/src/browser.ts +2 -0
  368. package/packages/hooks/src/emitter.ts +84 -0
  369. package/packages/hooks/src/inbox-check/hook.ts +114 -0
  370. package/packages/hooks/src/inbox-check/index.ts +8 -0
  371. package/packages/hooks/src/inbox-check/types.ts +39 -0
  372. package/packages/hooks/src/inbox-check/utils.test.ts +287 -0
  373. package/packages/hooks/src/inbox-check/utils.ts +125 -0
  374. package/packages/hooks/src/index.ts +11 -0
  375. package/packages/hooks/src/registry.ts +614 -0
  376. package/packages/hooks/src/shims.d.ts +3 -0
  377. package/packages/hooks/src/trajectory-hooks.ts +251 -0
  378. package/packages/hooks/src/types.ts +342 -0
  379. package/packages/hooks/tsconfig.json +21 -0
  380. package/packages/hooks/vitest.config.ts +9 -0
  381. package/packages/mcp/dist/bin.d.ts.map +1 -0
  382. package/packages/mcp/dist/bin.js.map +1 -0
  383. package/packages/mcp/dist/client.d.ts +9 -15
  384. package/packages/mcp/dist/client.d.ts.map +1 -0
  385. package/packages/mcp/dist/client.js +42 -74
  386. package/packages/mcp/dist/client.js.map +1 -0
  387. package/packages/mcp/dist/cloud.d.ts.map +1 -0
  388. package/packages/mcp/dist/cloud.js.map +1 -0
  389. package/packages/mcp/dist/errors.d.ts.map +1 -0
  390. package/packages/mcp/dist/errors.js.map +1 -0
  391. package/packages/mcp/dist/file-transport.d.ts.map +1 -0
  392. package/packages/mcp/dist/file-transport.js.map +1 -0
  393. package/packages/mcp/dist/hybrid-client.d.ts.map +1 -0
  394. package/packages/mcp/dist/hybrid-client.js.map +1 -0
  395. package/packages/mcp/dist/index.d.ts.map +1 -0
  396. package/packages/mcp/dist/index.js.map +1 -0
  397. package/packages/mcp/dist/install-cli.d.ts.map +1 -0
  398. package/packages/mcp/dist/install-cli.js.map +1 -0
  399. package/packages/mcp/dist/install.d.ts.map +1 -0
  400. package/packages/mcp/dist/install.js.map +1 -0
  401. package/packages/mcp/dist/prompts/index.d.ts.map +1 -0
  402. package/packages/mcp/dist/prompts/index.js.map +1 -0
  403. package/packages/mcp/dist/prompts/protocol.d.ts.map +1 -0
  404. package/packages/mcp/dist/prompts/protocol.js.map +1 -0
  405. package/packages/mcp/dist/resources/agents.d.ts.map +1 -0
  406. package/packages/mcp/dist/resources/agents.js.map +1 -0
  407. package/packages/mcp/dist/resources/inbox.d.ts.map +1 -0
  408. package/packages/mcp/dist/resources/inbox.js.map +1 -0
  409. package/packages/mcp/dist/resources/index.d.ts.map +1 -0
  410. package/packages/mcp/dist/resources/index.js.map +1 -0
  411. package/packages/mcp/dist/resources/project.d.ts.map +1 -0
  412. package/packages/mcp/dist/resources/project.js.map +1 -0
  413. package/packages/mcp/dist/server.d.ts.map +1 -0
  414. package/packages/mcp/dist/server.js.map +1 -0
  415. package/packages/mcp/dist/simple.d.ts +2 -5
  416. package/packages/mcp/dist/simple.d.ts.map +1 -0
  417. package/packages/mcp/dist/simple.js.map +1 -0
  418. package/packages/mcp/dist/tools/index.d.ts.map +1 -0
  419. package/packages/mcp/dist/tools/index.js.map +1 -0
  420. package/packages/mcp/dist/tools/relay-broadcast.d.ts.map +1 -0
  421. package/packages/mcp/dist/tools/relay-broadcast.js.map +1 -0
  422. package/packages/mcp/dist/tools/relay-channel.d.ts.map +1 -0
  423. package/packages/mcp/dist/tools/relay-channel.js.map +1 -0
  424. package/packages/mcp/dist/tools/relay-connected.d.ts.map +1 -0
  425. package/packages/mcp/dist/tools/relay-connected.js.map +1 -0
  426. package/packages/mcp/dist/tools/relay-consensus.d.ts.map +1 -0
  427. package/packages/mcp/dist/tools/relay-consensus.js.map +1 -0
  428. package/packages/mcp/dist/tools/relay-continuity.d.ts.map +1 -0
  429. package/packages/mcp/dist/tools/relay-continuity.js.map +1 -0
  430. package/packages/mcp/dist/tools/relay-health.d.ts.map +1 -0
  431. package/packages/mcp/dist/tools/relay-health.js.map +1 -0
  432. package/packages/mcp/dist/tools/relay-inbox.d.ts.map +1 -0
  433. package/packages/mcp/dist/tools/relay-inbox.js.map +1 -0
  434. package/packages/mcp/dist/tools/relay-logs.d.ts.map +1 -0
  435. package/packages/mcp/dist/tools/relay-logs.js.map +1 -0
  436. package/packages/mcp/dist/tools/relay-metrics.d.ts.map +1 -0
  437. package/packages/mcp/dist/tools/relay-metrics.js.map +1 -0
  438. package/packages/mcp/dist/tools/relay-release.d.ts.map +1 -0
  439. package/packages/mcp/dist/tools/relay-release.js.map +1 -0
  440. package/packages/mcp/dist/tools/relay-remove-agent.d.ts.map +1 -0
  441. package/packages/mcp/dist/tools/relay-remove-agent.js.map +1 -0
  442. package/packages/mcp/dist/tools/relay-send.d.ts.map +1 -0
  443. package/packages/mcp/dist/tools/relay-send.js +4 -2
  444. package/packages/mcp/dist/tools/relay-send.js.map +1 -0
  445. package/packages/mcp/dist/tools/relay-shadow.d.ts.map +1 -0
  446. package/packages/mcp/dist/tools/relay-shadow.js.map +1 -0
  447. package/packages/mcp/dist/tools/relay-spawn.d.ts.map +1 -0
  448. package/packages/mcp/dist/tools/relay-spawn.js.map +1 -0
  449. package/packages/mcp/dist/tools/relay-status.d.ts.map +1 -0
  450. package/packages/mcp/dist/tools/relay-status.js.map +1 -0
  451. package/packages/mcp/dist/tools/relay-subscribe.d.ts.map +1 -0
  452. package/packages/mcp/dist/tools/relay-subscribe.js.map +1 -0
  453. package/packages/mcp/dist/tools/relay-who.d.ts.map +1 -0
  454. package/packages/mcp/dist/tools/relay-who.js.map +1 -0
  455. package/packages/mcp/package.json +3 -3
  456. package/packages/mcp/src/bin.ts +149 -0
  457. package/packages/mcp/src/client.ts +400 -0
  458. package/packages/mcp/src/cloud.ts +523 -0
  459. package/packages/mcp/src/errors.ts +54 -0
  460. package/packages/mcp/src/file-transport.ts +268 -0
  461. package/packages/mcp/src/hybrid-client.ts +209 -0
  462. package/packages/mcp/src/index.ts +122 -0
  463. package/packages/mcp/src/install-cli.ts +210 -0
  464. package/packages/mcp/src/install.ts +745 -0
  465. package/packages/mcp/src/prompts/index.ts +1 -0
  466. package/packages/mcp/src/prompts/protocol.ts +164 -0
  467. package/packages/mcp/src/resources/agents.ts +21 -0
  468. package/packages/mcp/src/resources/inbox.ts +21 -0
  469. package/packages/mcp/src/resources/index.ts +3 -0
  470. package/packages/mcp/src/resources/project.ts +29 -0
  471. package/packages/mcp/src/server.ts +431 -0
  472. package/packages/mcp/src/simple.ts +214 -0
  473. package/packages/mcp/src/tools/index.ts +133 -0
  474. package/packages/mcp/src/tools/relay-broadcast.ts +32 -0
  475. package/packages/mcp/src/tools/relay-channel.ts +93 -0
  476. package/packages/mcp/src/tools/relay-connected.ts +52 -0
  477. package/packages/mcp/src/tools/relay-consensus.ts +92 -0
  478. package/packages/mcp/src/tools/relay-continuity.ts +127 -0
  479. package/packages/mcp/src/tools/relay-health.ts +148 -0
  480. package/packages/mcp/src/tools/relay-inbox.ts +70 -0
  481. package/packages/mcp/src/tools/relay-logs.ts +106 -0
  482. package/packages/mcp/src/tools/relay-metrics.ts +140 -0
  483. package/packages/mcp/src/tools/relay-release.ts +54 -0
  484. package/packages/mcp/src/tools/relay-remove-agent.ts +58 -0
  485. package/packages/mcp/src/tools/relay-send.ts +84 -0
  486. package/packages/mcp/src/tools/relay-shadow.ts +67 -0
  487. package/packages/mcp/src/tools/relay-spawn.ts +87 -0
  488. package/packages/mcp/src/tools/relay-status.ts +57 -0
  489. package/packages/mcp/src/tools/relay-subscribe.ts +61 -0
  490. package/packages/mcp/src/tools/relay-who.ts +59 -0
  491. package/packages/mcp/tests/client.test.ts +476 -0
  492. package/packages/mcp/tests/discover.test.ts +195 -0
  493. package/packages/mcp/tests/install.test.ts +123 -0
  494. package/packages/mcp/tests/prompts.test.ts +12 -0
  495. package/packages/mcp/tests/resources.test.ts +53 -0
  496. package/packages/mcp/tests/tools.test.ts +1242 -0
  497. package/packages/mcp/tsconfig.json +22 -0
  498. package/packages/mcp/vitest.config.ts +9 -0
  499. package/packages/memory/dist/adapters/index.d.ts.map +1 -0
  500. package/packages/memory/dist/adapters/index.js.map +1 -0
  501. package/packages/memory/dist/adapters/inmemory.d.ts.map +1 -0
  502. package/packages/memory/dist/adapters/inmemory.js.map +1 -0
  503. package/packages/memory/dist/adapters/supermemory.d.ts.map +1 -0
  504. package/packages/memory/dist/adapters/supermemory.js.map +1 -0
  505. package/packages/memory/dist/context-compaction.d.ts.map +1 -0
  506. package/packages/memory/dist/context-compaction.js.map +1 -0
  507. package/packages/memory/dist/factory.d.ts.map +1 -0
  508. package/packages/memory/dist/factory.js.map +1 -0
  509. package/packages/memory/dist/index.d.ts.map +1 -0
  510. package/packages/memory/dist/index.js.map +1 -0
  511. package/packages/memory/dist/memory-hooks.d.ts.map +1 -0
  512. package/packages/memory/dist/memory-hooks.js.map +1 -0
  513. package/packages/memory/dist/service.d.ts.map +1 -0
  514. package/packages/memory/dist/service.js.map +1 -0
  515. package/packages/memory/dist/types.d.ts.map +1 -0
  516. package/packages/memory/dist/types.js.map +1 -0
  517. package/packages/memory/package.json +2 -2
  518. package/packages/memory/src/adapters/index.ts +8 -0
  519. package/packages/memory/src/adapters/inmemory.ts +265 -0
  520. package/packages/memory/src/adapters/supermemory.ts +449 -0
  521. package/packages/memory/src/context-compaction.test.ts +660 -0
  522. package/packages/memory/src/context-compaction.ts +612 -0
  523. package/packages/memory/src/factory.ts +170 -0
  524. package/packages/memory/src/index.ts +33 -0
  525. package/packages/memory/src/memory-hooks.ts +410 -0
  526. package/packages/memory/src/service.ts +194 -0
  527. package/packages/memory/src/types.ts +211 -0
  528. package/packages/memory/tsconfig.json +21 -0
  529. package/packages/memory/vitest.config.ts +9 -0
  530. package/packages/policy/dist/agent-policy.d.ts.map +1 -0
  531. package/packages/policy/dist/agent-policy.js.map +1 -0
  532. package/packages/policy/dist/cloud-policy-fetcher.d.ts.map +1 -0
  533. package/packages/policy/dist/cloud-policy-fetcher.js.map +1 -0
  534. package/packages/policy/dist/index.d.ts.map +1 -0
  535. package/packages/policy/dist/index.js.map +1 -0
  536. package/packages/policy/package.json +2 -2
  537. package/packages/policy/src/agent-policy.ts +866 -0
  538. package/packages/policy/src/cloud-policy-fetcher.ts +78 -0
  539. package/packages/policy/src/index.ts +21 -0
  540. package/packages/policy/tsconfig.json +21 -0
  541. package/packages/policy/vitest.config.ts +9 -0
  542. package/packages/protocol/dist/channels.d.ts.map +1 -0
  543. package/packages/protocol/dist/channels.js.map +1 -0
  544. package/packages/protocol/dist/framing.d.ts.map +1 -0
  545. package/packages/protocol/dist/framing.js.map +1 -0
  546. package/packages/protocol/dist/id-generator.d.ts.map +1 -0
  547. package/packages/protocol/dist/id-generator.js.map +1 -0
  548. package/packages/protocol/dist/index.d.ts.map +1 -0
  549. package/packages/protocol/dist/index.js.map +1 -0
  550. package/packages/protocol/dist/relay-pty-schemas.d.ts +70 -2
  551. package/packages/protocol/dist/relay-pty-schemas.d.ts.map +1 -0
  552. package/packages/protocol/dist/relay-pty-schemas.js.map +1 -0
  553. package/packages/protocol/dist/types.d.ts +8 -0
  554. package/packages/protocol/dist/types.d.ts.map +1 -0
  555. package/packages/protocol/dist/types.js.map +1 -0
  556. package/packages/protocol/package.json +1 -1
  557. package/packages/protocol/src/channels.test.ts +330 -0
  558. package/packages/protocol/src/channels.ts +270 -0
  559. package/packages/protocol/src/framing.test.ts +164 -0
  560. package/packages/protocol/src/framing.ts +242 -0
  561. package/packages/protocol/src/id-generator.ts +69 -0
  562. package/packages/protocol/src/index.ts +4 -0
  563. package/packages/protocol/src/relay-pty-schemas.ts +400 -0
  564. package/packages/protocol/src/types.test.ts +271 -0
  565. package/packages/protocol/src/types.ts +846 -0
  566. package/packages/protocol/tsconfig.json +21 -0
  567. package/packages/protocol/vitest.config.ts +9 -0
  568. package/packages/resiliency/dist/cgroup-manager.d.ts.map +1 -0
  569. package/packages/resiliency/dist/cgroup-manager.js.map +1 -0
  570. package/packages/resiliency/dist/context-persistence.d.ts.map +1 -0
  571. package/packages/resiliency/dist/context-persistence.js.map +1 -0
  572. package/packages/resiliency/dist/crash-insights.d.ts.map +1 -0
  573. package/packages/resiliency/dist/crash-insights.js.map +1 -0
  574. package/packages/resiliency/dist/gossip-health.d.ts.map +1 -0
  575. package/packages/resiliency/dist/gossip-health.js.map +1 -0
  576. package/packages/resiliency/dist/health-monitor.d.ts.map +1 -0
  577. package/packages/resiliency/dist/health-monitor.js.map +1 -0
  578. package/packages/resiliency/dist/index.d.ts.map +1 -0
  579. package/packages/resiliency/dist/index.js.map +1 -0
  580. package/packages/resiliency/dist/leader-watchdog.d.ts.map +1 -0
  581. package/packages/resiliency/dist/leader-watchdog.js.map +1 -0
  582. package/packages/resiliency/dist/logger.d.ts.map +1 -0
  583. package/packages/resiliency/dist/logger.js.map +1 -0
  584. package/packages/resiliency/dist/memory-monitor.d.ts.map +1 -0
  585. package/packages/resiliency/dist/memory-monitor.js.map +1 -0
  586. package/packages/resiliency/dist/metrics.d.ts.map +1 -0
  587. package/packages/resiliency/dist/metrics.js.map +1 -0
  588. package/packages/resiliency/dist/provider-context.d.ts.map +1 -0
  589. package/packages/resiliency/dist/provider-context.js.map +1 -0
  590. package/packages/resiliency/dist/stateless-lead.d.ts.map +1 -0
  591. package/packages/resiliency/dist/stateless-lead.js.map +1 -0
  592. package/packages/resiliency/dist/supervisor.d.ts.map +1 -0
  593. package/packages/resiliency/dist/supervisor.js.map +1 -0
  594. package/packages/resiliency/package.json +1 -1
  595. package/packages/resiliency/src/cgroup-manager.ts +468 -0
  596. package/packages/resiliency/src/context-persistence.ts +538 -0
  597. package/packages/resiliency/src/crash-insights.test.ts +620 -0
  598. package/packages/resiliency/src/crash-insights.ts +660 -0
  599. package/packages/resiliency/src/gossip-health.ts +333 -0
  600. package/packages/resiliency/src/health-monitor.ts +371 -0
  601. package/packages/resiliency/src/index.ts +157 -0
  602. package/packages/resiliency/src/leader-watchdog.ts +260 -0
  603. package/packages/resiliency/src/logger.ts +320 -0
  604. package/packages/resiliency/src/memory-monitor.test.ts +637 -0
  605. package/packages/resiliency/src/memory-monitor.ts +740 -0
  606. package/packages/resiliency/src/metrics.ts +311 -0
  607. package/packages/resiliency/src/provider-context.ts +452 -0
  608. package/packages/resiliency/src/stateless-lead.ts +408 -0
  609. package/packages/resiliency/src/supervisor.ts +578 -0
  610. package/packages/resiliency/tsconfig.json +21 -0
  611. package/packages/resiliency/vitest.config.ts +9 -0
  612. package/packages/sdk/dist/client.d.ts.map +1 -0
  613. package/packages/sdk/dist/client.js.map +1 -0
  614. package/packages/sdk/dist/index.d.ts.map +1 -0
  615. package/packages/sdk/dist/index.js.map +1 -0
  616. package/packages/sdk/dist/logs.d.ts.map +1 -0
  617. package/packages/sdk/dist/logs.js.map +1 -0
  618. package/packages/sdk/dist/protocol/index.d.ts.map +1 -0
  619. package/packages/sdk/dist/protocol/index.js.map +1 -0
  620. package/packages/sdk/dist/standalone.d.ts.map +1 -0
  621. package/packages/sdk/dist/standalone.js.map +1 -0
  622. package/packages/sdk/examples/SWARM_CAPABILITIES.md +498 -0
  623. package/packages/sdk/examples/SWARM_PATTERNS.md +541 -0
  624. package/packages/sdk/package.json +2 -2
  625. package/packages/sdk/src/client.test.ts +568 -0
  626. package/packages/sdk/src/client.ts +1418 -0
  627. package/packages/sdk/src/index.ts +103 -0
  628. package/packages/sdk/src/logs.test.ts +98 -0
  629. package/packages/sdk/src/logs.ts +126 -0
  630. package/packages/sdk/src/protocol/framing.test.ts +164 -0
  631. package/packages/sdk/src/protocol/index.ts +8 -0
  632. package/packages/sdk/src/standalone.ts +176 -0
  633. package/packages/sdk/tsconfig.json +22 -0
  634. package/packages/sdk/vitest.config.ts +9 -0
  635. package/packages/spawner/.trajectories/index.json +5 -0
  636. package/packages/spawner/dist/index.d.ts.map +1 -0
  637. package/packages/spawner/dist/index.js.map +1 -0
  638. package/packages/spawner/dist/types.d.ts.map +1 -0
  639. package/packages/spawner/dist/types.js.map +1 -0
  640. package/packages/spawner/package.json +1 -1
  641. package/packages/spawner/src/index.ts +8 -0
  642. package/packages/spawner/src/types.test.ts +385 -0
  643. package/packages/spawner/src/types.ts +228 -0
  644. package/packages/spawner/tsconfig.json +19 -0
  645. package/packages/spawner/vitest.config.ts +9 -0
  646. package/packages/state/dist/agent-state.d.ts.map +1 -0
  647. package/packages/state/dist/agent-state.js.map +1 -0
  648. package/packages/state/dist/index.d.ts.map +1 -0
  649. package/packages/state/dist/index.js.map +1 -0
  650. package/packages/state/package.json +1 -1
  651. package/packages/state/src/agent-state.test.ts +335 -0
  652. package/packages/state/src/agent-state.ts +153 -0
  653. package/packages/state/src/index.ts +12 -0
  654. package/packages/state/tsconfig.json +21 -0
  655. package/packages/state/vitest.config.ts +9 -0
  656. package/packages/storage/dist/adapter.d.ts +28 -1
  657. package/packages/storage/dist/adapter.d.ts.map +1 -0
  658. package/packages/storage/dist/adapter.js +104 -10
  659. package/packages/storage/dist/adapter.js.map +1 -0
  660. package/packages/storage/dist/batched-sqlite-adapter.d.ts.map +1 -0
  661. package/packages/storage/dist/batched-sqlite-adapter.js.map +1 -0
  662. package/packages/storage/dist/dead-letter-queue.d.ts.map +1 -0
  663. package/packages/storage/dist/dead-letter-queue.js.map +1 -0
  664. package/packages/storage/dist/dlq-adapter.d.ts.map +1 -0
  665. package/packages/storage/dist/dlq-adapter.js.map +1 -0
  666. package/packages/storage/dist/index.d.ts +1 -0
  667. package/packages/storage/dist/index.d.ts.map +1 -0
  668. package/packages/storage/dist/index.js +1 -0
  669. package/packages/storage/dist/index.js.map +1 -0
  670. package/packages/storage/dist/jsonl-adapter.d.ts +77 -0
  671. package/packages/storage/dist/jsonl-adapter.d.ts.map +1 -0
  672. package/packages/storage/dist/jsonl-adapter.js +505 -0
  673. package/packages/storage/dist/jsonl-adapter.js.map +1 -0
  674. package/packages/storage/dist/sqlite-adapter.d.ts +6 -1
  675. package/packages/storage/dist/sqlite-adapter.d.ts.map +1 -0
  676. package/packages/storage/dist/sqlite-adapter.js +47 -0
  677. package/packages/storage/dist/sqlite-adapter.js.map +1 -0
  678. package/packages/storage/package.json +2 -2
  679. package/packages/storage/src/adapter.ts +438 -0
  680. package/packages/storage/src/batched-sqlite-adapter.test.ts +240 -0
  681. package/packages/storage/src/batched-sqlite-adapter.ts +239 -0
  682. package/packages/storage/src/dead-letter-queue.ts +643 -0
  683. package/packages/storage/src/dlq-adapter.test.ts +492 -0
  684. package/packages/storage/src/dlq-adapter.ts +954 -0
  685. package/packages/storage/src/index.ts +6 -0
  686. package/packages/storage/src/jsonl-adapter.test.ts +200 -0
  687. package/packages/storage/src/jsonl-adapter.ts +618 -0
  688. package/packages/storage/src/memory-adapter.test.ts +36 -0
  689. package/packages/storage/src/sqlite-adapter.test.ts +562 -0
  690. package/packages/storage/src/sqlite-adapter.ts +1058 -0
  691. package/packages/storage/tsconfig.json +21 -0
  692. package/packages/storage/vitest.config.ts +9 -0
  693. package/packages/telemetry/dist/client.d.ts.map +1 -0
  694. package/packages/telemetry/dist/client.js.map +1 -0
  695. package/packages/telemetry/dist/config.d.ts.map +1 -0
  696. package/packages/telemetry/dist/config.js.map +1 -0
  697. package/packages/telemetry/dist/events.d.ts.map +1 -0
  698. package/packages/telemetry/dist/events.js.map +1 -0
  699. package/packages/telemetry/dist/index.d.ts.map +1 -0
  700. package/packages/telemetry/dist/index.js.map +1 -0
  701. package/packages/telemetry/dist/machine-id.d.ts.map +1 -0
  702. package/packages/telemetry/dist/machine-id.js.map +1 -0
  703. package/packages/telemetry/dist/posthog-config.d.ts.map +1 -0
  704. package/packages/telemetry/dist/posthog-config.js.map +1 -0
  705. package/packages/telemetry/package.json +1 -1
  706. package/packages/telemetry/src/client.ts +158 -0
  707. package/packages/telemetry/src/config.ts +110 -0
  708. package/packages/telemetry/src/events.ts +137 -0
  709. package/packages/telemetry/src/index.ts +46 -0
  710. package/packages/telemetry/src/machine-id.ts +63 -0
  711. package/packages/telemetry/src/posthog-config.ts +39 -0
  712. package/packages/telemetry/tsconfig.json +21 -0
  713. package/packages/trajectory/dist/index.d.ts.map +1 -0
  714. package/packages/trajectory/dist/index.js.map +1 -0
  715. package/packages/trajectory/dist/integration.d.ts.map +1 -0
  716. package/packages/trajectory/dist/integration.js.map +1 -0
  717. package/packages/trajectory/package.json +2 -2
  718. package/packages/trajectory/src/index.ts +1 -0
  719. package/packages/trajectory/src/integration.ts +1268 -0
  720. package/packages/trajectory/tsconfig.json +21 -0
  721. package/packages/trajectory/vitest.config.ts +9 -0
  722. package/packages/user-directory/dist/index.d.ts.map +1 -0
  723. package/packages/user-directory/dist/index.js.map +1 -0
  724. package/packages/user-directory/dist/user-directory.d.ts.map +1 -0
  725. package/packages/user-directory/dist/user-directory.js.map +1 -0
  726. package/packages/user-directory/package.json +2 -2
  727. package/packages/user-directory/src/index.ts +12 -0
  728. package/packages/user-directory/src/user-directory.ts +393 -0
  729. package/packages/user-directory/tsconfig.json +21 -0
  730. package/packages/user-directory/vitest.config.ts +9 -0
  731. package/packages/utils/dist/cjs/client-helpers.js +127 -0
  732. package/packages/utils/dist/cjs/command-resolver.js +89 -0
  733. package/packages/utils/dist/cjs/error-tracking.js +106 -0
  734. package/packages/utils/dist/cjs/git-remote.js +120 -0
  735. package/packages/utils/dist/cjs/index.js +40 -0
  736. package/packages/utils/dist/cjs/logger.js +105 -0
  737. package/packages/utils/dist/cjs/model-mapping.js +54 -0
  738. package/packages/utils/dist/cjs/name-generator.js +179 -0
  739. package/packages/utils/dist/cjs/package.json +3 -0
  740. package/packages/utils/dist/cjs/precompiled-patterns.js +271 -0
  741. package/packages/utils/dist/cjs/relay-pty-path.js +143 -0
  742. package/packages/utils/dist/cjs/update-checker.js +185 -0
  743. package/packages/utils/dist/client-helpers.d.ts +73 -0
  744. package/packages/utils/dist/client-helpers.d.ts.map +1 -0
  745. package/packages/utils/dist/client-helpers.js +130 -0
  746. package/packages/utils/dist/client-helpers.js.map +1 -0
  747. package/packages/utils/dist/command-resolver.d.ts.map +1 -0
  748. package/packages/utils/dist/command-resolver.js.map +1 -0
  749. package/packages/utils/dist/error-tracking.d.ts.map +1 -0
  750. package/packages/utils/dist/error-tracking.js.map +1 -0
  751. package/packages/utils/dist/git-remote.d.ts.map +1 -0
  752. package/packages/utils/dist/git-remote.js.map +1 -0
  753. package/packages/utils/dist/index.d.ts +1 -0
  754. package/packages/utils/dist/index.d.ts.map +1 -0
  755. package/packages/utils/dist/index.js +1 -0
  756. package/packages/utils/dist/index.js.map +1 -0
  757. package/packages/utils/dist/logger.d.ts.map +1 -0
  758. package/packages/utils/dist/logger.js.map +1 -0
  759. package/packages/utils/dist/model-mapping.d.ts.map +1 -0
  760. package/packages/utils/dist/model-mapping.js.map +1 -0
  761. package/packages/utils/dist/name-generator.d.ts.map +1 -0
  762. package/packages/utils/dist/name-generator.js.map +1 -0
  763. package/packages/utils/dist/precompiled-patterns.d.ts.map +1 -0
  764. package/packages/utils/dist/precompiled-patterns.js.map +1 -0
  765. package/packages/utils/dist/relay-pty-path.d.ts +11 -5
  766. package/packages/utils/dist/relay-pty-path.d.ts.map +1 -0
  767. package/packages/utils/dist/relay-pty-path.js +60 -5
  768. package/packages/utils/dist/relay-pty-path.js.map +1 -0
  769. package/packages/utils/dist/update-checker.d.ts.map +1 -0
  770. package/packages/utils/dist/update-checker.js.map +1 -0
  771. package/packages/utils/package.json +37 -14
  772. package/packages/utils/scripts/build-cjs.mjs +24 -0
  773. package/packages/utils/src/client-helpers.ts +221 -0
  774. package/packages/utils/src/command-resolver.ts +82 -0
  775. package/packages/utils/src/error-tracking.ts +189 -0
  776. package/packages/utils/src/git-remote.ts +143 -0
  777. package/packages/utils/src/index.ts +10 -0
  778. package/packages/utils/src/logger.ts +107 -0
  779. package/packages/utils/src/model-mapping.test.ts +122 -0
  780. package/packages/utils/src/model-mapping.ts +58 -0
  781. package/packages/utils/src/name-generator.test.ts +259 -0
  782. package/packages/utils/src/name-generator.ts +56 -0
  783. package/packages/utils/src/precompiled-patterns.test.ts +452 -0
  784. package/packages/utils/src/precompiled-patterns.ts +395 -0
  785. package/packages/utils/src/relay-pty-path.ts +196 -0
  786. package/packages/utils/src/update-checker.test.ts +260 -0
  787. package/packages/utils/src/update-checker.ts +211 -0
  788. package/packages/utils/tsconfig.json +21 -0
  789. package/packages/utils/vitest.config.ts +9 -0
  790. package/packages/wrapper/dist/__fixtures__/claude-outputs.d.ts.map +1 -0
  791. package/packages/wrapper/dist/__fixtures__/claude-outputs.js.map +1 -0
  792. package/packages/wrapper/dist/__fixtures__/codex-outputs.d.ts.map +1 -0
  793. package/packages/wrapper/dist/__fixtures__/codex-outputs.js.map +1 -0
  794. package/packages/wrapper/dist/__fixtures__/gemini-outputs.d.ts.map +1 -0
  795. package/packages/wrapper/dist/__fixtures__/gemini-outputs.js.map +1 -0
  796. package/packages/wrapper/dist/__fixtures__/index.d.ts.map +1 -0
  797. package/packages/wrapper/dist/__fixtures__/index.js.map +1 -0
  798. package/packages/wrapper/dist/auth-detection.d.ts.map +1 -0
  799. package/packages/wrapper/dist/auth-detection.js.map +1 -0
  800. package/packages/wrapper/dist/base-wrapper.d.ts.map +1 -0
  801. package/packages/wrapper/dist/base-wrapper.js.map +1 -0
  802. package/packages/wrapper/dist/client.d.ts.map +1 -0
  803. package/packages/wrapper/dist/client.js.map +1 -0
  804. package/packages/wrapper/dist/id-generator.d.ts.map +1 -0
  805. package/packages/wrapper/dist/id-generator.js.map +1 -0
  806. package/packages/wrapper/dist/idle-detector.d.ts.map +1 -0
  807. package/packages/wrapper/dist/idle-detector.js.map +1 -0
  808. package/packages/wrapper/dist/inbox.d.ts.map +1 -0
  809. package/packages/wrapper/dist/inbox.js.map +1 -0
  810. package/packages/wrapper/dist/index.d.ts.map +1 -0
  811. package/packages/wrapper/dist/index.js.map +1 -0
  812. package/packages/wrapper/dist/parser.d.ts.map +1 -0
  813. package/packages/wrapper/dist/parser.js.map +1 -0
  814. package/packages/wrapper/dist/prompt-composer.d.ts.map +1 -0
  815. package/packages/wrapper/dist/prompt-composer.js.map +1 -0
  816. package/packages/wrapper/dist/relay-pty-orchestrator.d.ts +10 -0
  817. package/packages/wrapper/dist/relay-pty-orchestrator.d.ts.map +1 -0
  818. package/packages/wrapper/dist/relay-pty-orchestrator.js +69 -0
  819. package/packages/wrapper/dist/relay-pty-orchestrator.js.map +1 -0
  820. package/packages/wrapper/dist/shared.d.ts.map +1 -0
  821. package/packages/wrapper/dist/shared.js.map +1 -0
  822. package/packages/wrapper/dist/stuck-detector.d.ts.map +1 -0
  823. package/packages/wrapper/dist/stuck-detector.js.map +1 -0
  824. package/packages/wrapper/dist/tmux-resolver.d.ts.map +1 -0
  825. package/packages/wrapper/dist/tmux-resolver.js.map +1 -0
  826. package/packages/wrapper/dist/tmux-wrapper.d.ts.map +1 -0
  827. package/packages/wrapper/dist/tmux-wrapper.js.map +1 -0
  828. package/packages/wrapper/dist/trajectory-integration.d.ts.map +1 -0
  829. package/packages/wrapper/dist/trajectory-integration.js.map +1 -0
  830. package/packages/wrapper/dist/wrapper-types.d.ts.map +1 -0
  831. package/packages/wrapper/dist/wrapper-types.js.map +1 -0
  832. package/packages/wrapper/package.json +6 -9
  833. package/packages/wrapper/src/__fixtures__/claude-outputs.ts +471 -0
  834. package/packages/wrapper/src/__fixtures__/codex-outputs.ts +99 -0
  835. package/packages/wrapper/src/__fixtures__/gemini-outputs.ts +151 -0
  836. package/packages/wrapper/src/__fixtures__/index.ts +47 -0
  837. package/packages/wrapper/src/auth-detection.ts +244 -0
  838. package/packages/wrapper/src/base-wrapper.test.ts +589 -0
  839. package/packages/wrapper/src/base-wrapper.ts +810 -0
  840. package/packages/wrapper/src/client.test.ts +262 -0
  841. package/packages/wrapper/src/client.ts +984 -0
  842. package/packages/wrapper/src/id-generator.test.ts +71 -0
  843. package/packages/wrapper/src/id-generator.ts +69 -0
  844. package/packages/wrapper/src/idle-detector.test.ts +418 -0
  845. package/packages/wrapper/src/idle-detector.ts +384 -0
  846. package/packages/wrapper/src/inbox.test.ts +233 -0
  847. package/packages/wrapper/src/inbox.ts +89 -0
  848. package/packages/wrapper/src/index.ts +170 -0
  849. package/packages/wrapper/src/parser.regression.test.ts +251 -0
  850. package/packages/wrapper/src/parser.test.ts +1359 -0
  851. package/packages/wrapper/src/parser.ts +1477 -0
  852. package/packages/wrapper/src/prompt-composer.test.ts +219 -0
  853. package/packages/wrapper/src/prompt-composer.ts +231 -0
  854. package/packages/wrapper/src/relay-pty-orchestrator.test.ts +1204 -0
  855. package/packages/wrapper/src/relay-pty-orchestrator.ts +2626 -0
  856. package/packages/wrapper/src/shared.test.ts +322 -0
  857. package/packages/wrapper/src/shared.ts +495 -0
  858. package/packages/wrapper/src/stuck-detector.test.ts +303 -0
  859. package/packages/wrapper/src/stuck-detector.ts +511 -0
  860. package/packages/wrapper/src/tmux-resolver.test.ts +104 -0
  861. package/packages/wrapper/src/tmux-resolver.ts +207 -0
  862. package/packages/wrapper/src/tmux-wrapper.test.ts +316 -0
  863. package/packages/wrapper/src/tmux-wrapper.ts +2095 -0
  864. package/packages/wrapper/src/trajectory-detection.test.ts +151 -0
  865. package/packages/wrapper/src/trajectory-integration.ts +1261 -0
  866. package/packages/wrapper/src/wrapper-types.ts +45 -0
  867. package/packages/wrapper/tsconfig.json +19 -0
  868. package/packages/wrapper/vitest.config.ts +9 -0
  869. package/scripts/build-cjs.mjs +23 -0
  870. package/scripts/postinstall.js +132 -0
  871. package/.cursor/mcp.json +0 -11
  872. package/.gitattributes +0 -3
  873. package/.gitleaks.toml +0 -26
  874. package/.mcp.json +0 -11
  875. package/.nvmrc +0 -1
  876. package/ARCHITECTURE.md +0 -1245
  877. package/CHANGELOG.md +0 -231
  878. package/TESTING.md +0 -278
  879. package/TRAIL_GIT_AUTH_FIX.md +0 -113
  880. package/scripts/demos/README.md +0 -79
  881. package/scripts/demos/server-capacity.sh +0 -69
  882. package/scripts/demos/sprint-planning.sh +0 -73
  883. package/scripts/hooks/install.sh +0 -16
  884. package/scripts/hooks/pre-commit +0 -60
  885. package/scripts/post-publish-verify/README.md +0 -80
  886. package/scripts/post-publish-verify/run-verify.sh +0 -127
  887. package/scripts/post-publish-verify/verify-install.sh +0 -249
  888. package/scripts/stress-test-orchestrator-integration.mts +0 -1366
  889. package/scripts/stress-test-orchestrator.mjs +0 -584
  890. package/scripts/stress-test-relay-pty.sh +0 -452
  891. package/scripts/test-interactive-terminal.sh +0 -248
  892. package/specs/PRIMITIVES_ROADMAP.md +0 -2154
  893. package/tests/benchmarks/protocol.bench.ts +0 -310
  894. package/turbo.json +0 -37
@@ -0,0 +1,2095 @@
1
+ /**
2
+ * TmuxWrapper - Attach-based tmux wrapper
3
+ *
4
+ * Architecture:
5
+ * 1. Start agent in detached tmux session
6
+ * 2. Attach user to tmux (they see real terminal)
7
+ * 3. Background: poll capture-pane silently (no stdout writes)
8
+ * 4. Background: parse ->relay commands, send to daemon
9
+ * 5. Background: inject messages via send-keys
10
+ *
11
+ * The key insight: user sees the REAL tmux session, not a proxy.
12
+ * We just do background parsing and injection.
13
+ */
14
+
15
+ import { exec, execSync, spawn, ChildProcess } from 'node:child_process';
16
+ import crypto from 'node:crypto';
17
+ import { promisify } from 'node:util';
18
+ import { BaseWrapper, type BaseWrapperConfig } from './base-wrapper.js';
19
+ import { OutputParser, type ParsedCommand, type ParsedSummary, parseSummaryWithDetails, parseSessionEndFromOutput } from './parser.js';
20
+ import {
21
+ hasContinuityCommand,
22
+ parseContinuityCommand,
23
+ } from '@agent-relay/continuity';
24
+ import { InboxManager } from './inbox.js';
25
+ import type { SendPayload, SendMeta } from '@agent-relay/protocol/types';
26
+ import { SqliteStorageAdapter } from '@agent-relay/storage/sqlite-adapter';
27
+ import { getProjectPaths } from '@agent-relay/config/project-namespace';
28
+ import { getTmuxPath } from '@agent-relay/wrapper';
29
+ import { findAgentConfig } from '@agent-relay/config/agent-config';
30
+ import {
31
+ TrajectoryIntegration,
32
+ getTrajectoryIntegration,
33
+ detectPhaseFromContent,
34
+ detectToolCalls,
35
+ detectErrors,
36
+ getCompactTrailInstructions,
37
+ getTrailEnvVars,
38
+ type PDEROPhase,
39
+ } from '@agent-relay/wrapper';
40
+ import { escapeForShell } from '@agent-relay/config/bridge-utils';
41
+ import { detectProviderAuthRevocation } from './auth-detection.js';
42
+ import {
43
+ type CliType,
44
+ type InjectionCallbacks,
45
+ stripAnsi,
46
+ sleep,
47
+ getDefaultRelayPrefix,
48
+ buildInjectionString,
49
+ injectWithRetry as sharedInjectWithRetry,
50
+ INJECTION_CONSTANTS,
51
+ CLI_QUIRKS,
52
+ AdaptiveThrottle,
53
+ sortByPriority,
54
+ getPriorityFromImportance,
55
+ } from './shared.js';
56
+ import { getTmuxPanePid } from './idle-detector.js';
57
+ import { DEFAULT_TMUX_WRAPPER_CONFIG } from '@agent-relay/config/relay-config';
58
+
59
+ const execAsync = promisify(exec);
60
+
61
+ // Constants for cursor stability detection in waitForClearInput
62
+ /** Number of consecutive polls with stable cursor before assuming input is clear */
63
+ const STABLE_CURSOR_THRESHOLD = 3;
64
+ /** Maximum cursor X position that indicates a prompt (typical prompts are 1-4 chars) */
65
+ const MAX_PROMPT_CURSOR_POSITION = 4;
66
+ /** Maximum characters to show in debug log truncation */
67
+ const DEBUG_LOG_TRUNCATE_LENGTH = 40;
68
+ /** Maximum characters to show in relay command log truncation */
69
+ const RELAY_LOG_TRUNCATE_LENGTH = 50;
70
+
71
+ export interface TmuxWrapperConfig extends BaseWrapperConfig {
72
+ cols?: number;
73
+ rows?: number;
74
+ /** Optional program identifier (e.g., 'claude', 'gpt-4o') */
75
+ program?: string;
76
+ /** Optional model identifier (e.g., 'claude-3-opus') */
77
+ model?: string;
78
+ /** Use file-based inbox in addition to injection */
79
+ useInbox?: boolean;
80
+ /** Custom inbox directory */
81
+ inboxDir?: string;
82
+ /** Polling interval for capture-pane (ms) */
83
+ pollInterval?: number;
84
+ /** Enable debug logging to stderr */
85
+ debug?: boolean;
86
+ /** Throttle debug logs (ms) */
87
+ debugLogIntervalMs?: number;
88
+ /** Idle time after last output before injecting (ms) */
89
+ idleBeforeInjectMs?: number;
90
+ /** Retry interval while waiting for idle window (ms) */
91
+ injectRetryMs?: number;
92
+ /** How long with no output before marking session idle (ms) */
93
+ activityIdleThresholdMs?: number;
94
+ /** Max time to wait for clear input before injecting (ms) */
95
+ inputWaitTimeoutMs?: number;
96
+ /** Polling interval when waiting for clear input (ms) */
97
+ inputWaitPollMs?: number;
98
+ /** Enable tmux mouse mode for scroll passthrough (default: true) */
99
+ mouseMode?: boolean;
100
+ /** Max time to wait for stable pane output before injection (ms) */
101
+ outputStabilityTimeoutMs?: number;
102
+ /** Poll interval when checking pane stability before injection (ms) */
103
+ outputStabilityPollMs?: number;
104
+ }
105
+
106
+ /**
107
+ * Get the default relay prefix for a given CLI type.
108
+ * All agents now use '->relay:' as the unified prefix.
109
+ * @deprecated Use getDefaultRelayPrefix() from shared.js instead
110
+ */
111
+ export function getDefaultPrefix(_cliType: CliType): string {
112
+ return getDefaultRelayPrefix();
113
+ }
114
+
115
+ export class TmuxWrapper extends BaseWrapper {
116
+ protected override config: TmuxWrapperConfig;
117
+ private sessionName: string;
118
+ private parser: OutputParser;
119
+ private inbox?: InboxManager;
120
+ private storage?: SqliteStorageAdapter;
121
+ private storageReady: Promise<boolean>; // Resolves true if storage initialized, false if failed
122
+ private pollTimer?: NodeJS.Timeout;
123
+ private attachProcess?: ChildProcess;
124
+ private lastCapturedOutput = '';
125
+ private lastOutputTime = 0;
126
+ private lastActivityTime = Date.now();
127
+ private activityState: 'active' | 'idle' | 'disconnected' = 'disconnected';
128
+ private recentlySentMessages: Map<string, number> = new Map();
129
+ // Track processed output to avoid re-parsing
130
+ private processedOutputLength = 0;
131
+ private lastLoggedLength = 0; // Track length for incremental log streaming
132
+ private lastDebugLog = 0;
133
+ private lastSummaryHash = ''; // Dedup summary saves
134
+ private pendingRelayCommands: ParsedCommand[] = [];
135
+ private queuedMessageHashes: Set<string> = new Set(); // For offline queue dedup
136
+ private readonly MAX_PENDING_RELAY_COMMANDS = 50;
137
+ private receivedMessageIdSet: Set<string> = new Set();
138
+ private receivedMessageIdOrder: string[] = [];
139
+ private readonly MAX_RECEIVED_MESSAGES = 2000;
140
+ private tmuxPath: string; // Resolved path to tmux binary (system or bundled)
141
+ private trajectory?: TrajectoryIntegration; // Trajectory tracking via trail
142
+ private lastDetectedPhase?: PDEROPhase; // Track last auto-detected PDERO phase
143
+ private seenToolCalls: Set<string> = new Set(); // Dedup tool call trajectory events
144
+ private seenErrors: Set<string> = new Set(); // Dedup error trajectory events
145
+ private authRevoked = false; // Track if auth has been revoked
146
+ private lastAuthCheck = 0; // Timestamp of last auth check (throttle)
147
+ private readonly AUTH_CHECK_INTERVAL = 5000; // Check auth status every 5 seconds max
148
+
149
+ // Adaptive throttle for message queue - adjusts delay based on success/failure
150
+ private throttle = new AdaptiveThrottle();
151
+
152
+ constructor(config: TmuxWrapperConfig) {
153
+ // Merge defaults with config
154
+ const mergedConfig: TmuxWrapperConfig = {
155
+ cols: process.stdout.columns || 120,
156
+ rows: process.stdout.rows || 40,
157
+ ...DEFAULT_TMUX_WRAPPER_CONFIG,
158
+ ...config,
159
+ };
160
+
161
+ // Call parent constructor (initializes client, cliType, relayPrefix, continuity)
162
+ super(mergedConfig);
163
+ this.config = mergedConfig;
164
+
165
+ // Session name (one agent per name - starting a duplicate kills the existing one)
166
+ this.sessionName = `relay-${config.name}`;
167
+
168
+ // Resolve tmux path early so we fail fast if tmux isn't available
169
+ this.tmuxPath = getTmuxPath();
170
+
171
+ // Auto-detect agent role from .claude/agents/ or .openagents/ if task not provided
172
+ let detectedTask = this.config.task;
173
+ if (!detectedTask) {
174
+ const agentConfig = findAgentConfig(config.name, this.config.cwd);
175
+ if (agentConfig?.description) {
176
+ detectedTask = agentConfig.description;
177
+ this.logStderr(`Auto-detected role: ${detectedTask.substring(0, 60)}...`, true);
178
+ }
179
+ }
180
+
181
+ this.parser = new OutputParser({ prefix: this.relayPrefix });
182
+
183
+ // Initialize inbox if using file-based messaging
184
+ if (config.useInbox) {
185
+ this.inbox = new InboxManager({
186
+ agentName: config.name,
187
+ inboxDir: config.inboxDir,
188
+ });
189
+ }
190
+
191
+ // Initialize storage for session/summary persistence
192
+ const projectPaths = getProjectPaths();
193
+ this.storage = new SqliteStorageAdapter({ dbPath: projectPaths.dbPath });
194
+ // Initialize asynchronously (don't block constructor) - methods await storageReady
195
+ this.storageReady = this.storage.init().then(() => true).catch(err => {
196
+ this.logStderr(`Failed to initialize storage: ${err.message}`, true);
197
+ this.storage = undefined;
198
+ return false;
199
+ });
200
+
201
+ // Initialize trajectory tracking via trail CLI
202
+ this.trajectory = getTrajectoryIntegration(projectPaths.projectId, config.name);
203
+
204
+ this.client.onStateChange = (state) => {
205
+ // Only log to stderr, never stdout (user is in tmux)
206
+ if (state === 'READY') {
207
+ this.logStderr('Connected to relay daemon');
208
+ this.flushQueuedRelayCommands();
209
+ } else if (state === 'BACKOFF') {
210
+ this.logStderr('Relay unavailable, will retry (backoff)');
211
+ } else if (state === 'DISCONNECTED') {
212
+ this.logStderr('Relay disconnected (offline mode)');
213
+ } else if (state === 'CONNECTING') {
214
+ this.logStderr('Connecting to relay daemon...');
215
+ }
216
+ };
217
+ }
218
+
219
+ // =========================================================================
220
+ // Abstract method implementations
221
+ // =========================================================================
222
+
223
+ /**
224
+ * Inject content into the tmux session via paste
225
+ */
226
+ protected async performInjection(content: string): Promise<void> {
227
+ await this.pasteLiteral(content);
228
+ }
229
+
230
+ /**
231
+ * Get cleaned output for parsing (strip ANSI codes)
232
+ */
233
+ protected getCleanOutput(): string {
234
+ return stripAnsi(this.lastCapturedOutput);
235
+ }
236
+
237
+ /**
238
+ * Log to stderr (safe - doesn't interfere with tmux display)
239
+ */
240
+ private logStderr(msg: string, force = false): void {
241
+ if (!force && !this.config.debug) return;
242
+
243
+ const now = Date.now();
244
+ if (!force && this.config.debugLogIntervalMs && this.config.debugLogIntervalMs > 0) {
245
+ if (now - this.lastDebugLog < this.config.debugLogIntervalMs) {
246
+ return;
247
+ }
248
+ this.lastDebugLog = now;
249
+ }
250
+
251
+ // Prefix with newline to avoid corrupting tmux status line
252
+ process.stderr.write(`\r[relay:${this.config.name}] ${msg}\n`);
253
+ }
254
+
255
+ /**
256
+ * Detect PDERO phase from output content and auto-transition if needed.
257
+ * Also detects tool calls and errors, recording them to the trajectory.
258
+ */
259
+ private detectAndTransitionPhase(content: string): void {
260
+ if (!this.trajectory) return;
261
+
262
+ // Detect phase transitions
263
+ const detectedPhase = detectPhaseFromContent(content);
264
+ if (detectedPhase && detectedPhase !== this.lastDetectedPhase) {
265
+ const currentPhase = this.trajectory.getPhase();
266
+ if (detectedPhase !== currentPhase) {
267
+ this.trajectory.transition(detectedPhase, 'Auto-detected from output');
268
+ this.lastDetectedPhase = detectedPhase;
269
+ this.logStderr(`Phase transition: ${currentPhase || 'none'} → ${detectedPhase}`);
270
+ }
271
+ }
272
+
273
+ // Detect and record tool calls
274
+ // Note: We deduplicate by tool+status to record each unique tool type once per session
275
+ // (e.g., "Read" started, "Read" completed). This provides a summary of tools used
276
+ // without flooding the trajectory with every individual invocation.
277
+ const tools = detectToolCalls(content);
278
+ for (const tool of tools) {
279
+ const key = `${tool.tool}:${tool.status || 'started'}`;
280
+ if (!this.seenToolCalls.has(key)) {
281
+ this.seenToolCalls.add(key);
282
+ const statusLabel = tool.status === 'completed' ? ' (completed)' : '';
283
+ this.trajectory.event(`Tool: ${tool.tool}${statusLabel}`, 'tool_call');
284
+ }
285
+ }
286
+
287
+ // Detect and record errors
288
+ const errors = detectErrors(content);
289
+ for (const error of errors) {
290
+ if (!this.seenErrors.has(error.message)) {
291
+ this.seenErrors.add(error.message);
292
+ const prefix = error.type === 'warning' ? 'Warning' : 'Error';
293
+ this.trajectory.event(`${prefix}: ${error.message}`, 'error');
294
+ }
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Build the full command with proper quoting
300
+ * Args containing spaces need to be quoted
301
+ */
302
+ private buildCommand(): string {
303
+ if (!this.config.args || this.config.args.length === 0) {
304
+ return this.config.command;
305
+ }
306
+
307
+ // Quote any argument that contains spaces, quotes, or shell special chars
308
+ // Must handle: spaces, quotes, $, <, >, |, &, ;, (, ), `, etc.
309
+ const quotedArgs = this.config.args.map(arg => {
310
+ if (/[\s"'$<>|&;()`,!\\]/.test(arg)) {
311
+ // Use double quotes and escape internal quotes and special chars
312
+ const escaped = arg
313
+ .replace(/\\/g, '\\\\')
314
+ .replace(/"/g, '\\"')
315
+ .replace(/\$/g, '\\$')
316
+ .replace(/`/g, '\\`')
317
+ .replace(/!/g, '\\!');
318
+ return `"${escaped}"`;
319
+ }
320
+ return arg;
321
+ });
322
+
323
+ return `${this.config.command} ${quotedArgs.join(' ')}`;
324
+ }
325
+
326
+ /**
327
+ * Check if tmux session exists
328
+ */
329
+ private async sessionExists(): Promise<boolean> {
330
+ try {
331
+ await execAsync(`"${this.tmuxPath}" has-session -t ${this.sessionName} 2>/dev/null`);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Start the wrapped agent process
340
+ */
341
+ async start(): Promise<void> {
342
+ if (this.running) return;
343
+
344
+ // Initialize inbox if enabled
345
+ if (this.inbox) {
346
+ this.inbox.init();
347
+ }
348
+
349
+ // Connect to relay daemon (in background, don't block)
350
+ this.client.connect()
351
+ .then(() => {
352
+ this.logStderr(`Relay connected (state: ${this.client.state})`, true);
353
+ })
354
+ .catch((err: Error) => {
355
+ // Connection failures will retry via client backoff; surface once to stderr.
356
+ this.logStderr(`Relay connect failed: ${err.message}. Will retry if enabled.`, true);
357
+ this.logStderr(`Relay client state: ${this.client.state}`, true);
358
+ });
359
+
360
+ // Kill any existing session with this name
361
+ try {
362
+ execSync(`"${this.tmuxPath}" kill-session -t ${this.sessionName} 2>/dev/null`);
363
+ } catch {
364
+ // Session doesn't exist, that's fine
365
+ }
366
+
367
+ // Build the command - properly quote args that contain spaces
368
+ const fullCommand = this.buildCommand();
369
+ this.logStderr(`Command: ${fullCommand}`);
370
+ this.logStderr(`Prefix: ${this.relayPrefix} (use ${this.relayPrefix}AgentName to send)`);
371
+
372
+ // Create tmux session
373
+ try {
374
+ execSync(`"${this.tmuxPath}" new-session -d -s ${this.sessionName} -x ${this.config.cols} -y ${this.config.rows}`, {
375
+ cwd: this.config.cwd ?? process.cwd(),
376
+ stdio: 'pipe',
377
+ });
378
+
379
+ // Configure tmux for seamless scrolling
380
+ // Mouse mode passes scroll events to the application when in alternate screen
381
+ const tmuxSettings = [
382
+ 'set -g set-clipboard on', // Enable clipboard
383
+ 'set -g history-limit 50000', // Large scrollback for when needed
384
+ 'setw -g alternate-screen on', // Ensure alternate screen works
385
+ // Pass through mouse scroll to application in alternate screen mode
386
+ 'set -ga terminal-overrides ",xterm*:Tc"',
387
+ 'set -g status-left-length 100', // Provide ample space for agent name in status bar
388
+ 'set -g mode-keys vi', // Predictable key table (avoid copy-mode surprises)
389
+ ];
390
+
391
+ // Add mouse mode if enabled (allows scroll passthrough to CLI apps)
392
+ if (this.config.mouseMode) {
393
+ tmuxSettings.unshift('set -g mouse on');
394
+ this.logStderr('Mouse mode enabled (scroll should work in app)');
395
+ }
396
+
397
+ for (const setting of tmuxSettings) {
398
+ try {
399
+ execSync(`"${this.tmuxPath}" ${setting}`, { stdio: 'pipe' });
400
+ } catch {
401
+ // Some settings may not be available in older tmux versions
402
+ }
403
+ }
404
+
405
+ // Mouse scroll should work for both TUIs (alternate screen) and plain shells.
406
+ // If the pane is in alternate screen, pass scroll to the app; otherwise enter copy-mode and scroll tmux history.
407
+ const tmuxMouseBindings = [
408
+ 'unbind -T root WheelUpPane',
409
+ 'unbind -T root WheelDownPane',
410
+ 'unbind -T root MouseDrag1Pane',
411
+ 'bind -T root WheelUpPane if-shell -F "#{alternate_on}" "send-keys -M" "copy-mode -e; send-keys -X scroll-up"',
412
+ 'bind -T root WheelDownPane if-shell -F "#{alternate_on}" "send-keys -M" "send-keys -X scroll-down"',
413
+ 'bind -T root MouseDrag1Pane if-shell -F "#{alternate_on}" "send-keys -M" "copy-mode -e"',
414
+ ];
415
+
416
+ for (const setting of tmuxMouseBindings) {
417
+ try {
418
+ execSync(`"${this.tmuxPath}" ${setting}`, { stdio: 'pipe' });
419
+ } catch {
420
+ // Ignore on older tmux versions lacking these key tables
421
+ }
422
+ }
423
+
424
+ // Set environment variables including trail/trajectory vars
425
+ const projectPaths = getProjectPaths();
426
+ const trailEnvVars = getTrailEnvVars(projectPaths.projectId, this.config.name, projectPaths.dataDir);
427
+
428
+ for (const [key, value] of Object.entries({
429
+ ...this.config.env,
430
+ ...trailEnvVars,
431
+ AGENT_RELAY_NAME: this.config.name,
432
+ TERM: 'xterm-256color',
433
+ })) {
434
+ // Use proper shell escaping to prevent command injection via env var values
435
+ const escaped = escapeForShell(value);
436
+ execSync(`"${this.tmuxPath}" setenv -t ${this.sessionName} ${key} "${escaped}"`);
437
+ }
438
+
439
+ // Wait for shell to be ready (look for prompt)
440
+ await this.waitForShellReady();
441
+
442
+ // Send the command to run
443
+ this.logStderr('Sending command to tmux...');
444
+ await this.sendKeysLiteral(fullCommand);
445
+ await sleep(300); // Give shell time to process the command literal
446
+ this.logStderr('Sending Enter...');
447
+ await this.sendKeys('Enter');
448
+ await sleep(500); // Ensure Enter is processed and command starts before we continue
449
+ this.logStderr('Command sent');
450
+
451
+ } catch (err: any) {
452
+ throw new Error(`Failed to create tmux session: ${err.message}`);
453
+ }
454
+
455
+ // Wait for session to be ready
456
+ await this.waitForSession();
457
+
458
+ this.running = true;
459
+ this.lastActivityTime = Date.now();
460
+ this.activityState = 'active';
461
+
462
+ // Initialize trajectory tracking (auto-start if task provided)
463
+ this.initializeTrajectory();
464
+
465
+ // Initialize continuity and get/create agentId
466
+ this.initializeAgentId();
467
+
468
+ // Start background polling (silent - no stdout writes)
469
+ this.startSilentPolling();
470
+
471
+ // Initialize idle detector with the tmux pane PID for process state inspection
472
+ this.initializeIdleDetectorPid();
473
+ this.startStuckDetection();
474
+
475
+ // Wait for agent to be ready, then inject instructions
476
+ // This replaces the fixed 3-second delay with actual readiness detection
477
+ this.waitForAgentReady().then(() => {
478
+ this.injectInstructions();
479
+ }).catch(err => {
480
+ this.logStderr(`Failed to wait for agent ready: ${err.message}`, true);
481
+ // Fall back to injecting after a delay
482
+ setTimeout(() => this.injectInstructions(), 3000);
483
+ });
484
+
485
+ // Attach user to tmux session
486
+ // This takes over stdin/stdout - user sees the real terminal
487
+ this.attachToSession();
488
+ }
489
+
490
+ /**
491
+ * Initialize trajectory tracking
492
+ * Auto-starts a trajectory if task is provided in config
493
+ */
494
+ private async initializeTrajectory(): Promise<void> {
495
+ if (!this.trajectory) return;
496
+
497
+ // Auto-start trajectory if task is provided
498
+ if (this.config.task) {
499
+ const success = await this.trajectory.initialize(this.config.task);
500
+ if (success) {
501
+ this.logStderr(`Trajectory started for task: ${this.config.task}`);
502
+ }
503
+ } else {
504
+ // Just initialize without starting a trajectory
505
+ await this.trajectory.initialize();
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Initialize agent ID for continuity/resume functionality (uses logStderr for tmux)
511
+ */
512
+ protected override async initializeAgentId(): Promise<void> {
513
+ if (!this.continuity) return;
514
+
515
+ try {
516
+ let ledger;
517
+
518
+ // If resuming from a previous agent ID, try to find that ledger
519
+ if (this.config.resumeAgentId) {
520
+ ledger = await this.continuity.findLedgerByAgentId(this.config.resumeAgentId);
521
+ if (ledger) {
522
+ this.logStderr(`Resuming agent ID: ${ledger.agentId} (from previous session)`);
523
+ } else {
524
+ this.logStderr(`Resume agent ID ${this.config.resumeAgentId} not found, creating new`, true);
525
+ }
526
+ }
527
+
528
+ // If not resuming or resume ID not found, get or create ledger
529
+ if (!ledger) {
530
+ ledger = await this.continuity.getOrCreateLedger(
531
+ this.config.name,
532
+ this.cliType
533
+ );
534
+ this.logStderr(`Agent ID: ${ledger.agentId} (use this to resume if agent dies)`);
535
+ }
536
+
537
+ this.agentId = ledger.agentId;
538
+ } catch (err: any) {
539
+ this.logStderr(`Failed to initialize agent ID: ${err.message}`, true);
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Initialize the idle detector with the tmux pane PID.
545
+ * This enables process state inspection on Linux for more reliable idle detection.
546
+ */
547
+ private async initializeIdleDetectorPid(): Promise<void> {
548
+ try {
549
+ const pid = await getTmuxPanePid(this.tmuxPath, this.sessionName);
550
+ if (pid) {
551
+ this.setIdleDetectorPid(pid);
552
+ this.logStderr(`Idle detector initialized with PID ${pid}`);
553
+ } else {
554
+ this.logStderr('Could not get pane PID for idle detection (will use output analysis)');
555
+ }
556
+ } catch (err: any) {
557
+ this.logStderr(`Failed to initialize idle detector PID: ${err.message}`);
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Wait for the agent to be ready for input.
563
+ * Uses idle detection instead of a fixed delay.
564
+ */
565
+ private async waitForAgentReady(): Promise<void> {
566
+ // Minimum wait to ensure the CLI process has started
567
+ await sleep(500);
568
+
569
+ // Wait for agent to become idle (CLI fully initialized)
570
+ const result = await this.waitForIdleState(10000, 200);
571
+
572
+ if (result.isIdle) {
573
+ this.logStderr(`Agent ready (confidence: ${(result.confidence * 100).toFixed(0)}%)`);
574
+ } else {
575
+ this.logStderr('Agent readiness timeout, proceeding anyway');
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Inject usage instructions for the agent including persistence protocol
581
+ */
582
+ private async injectInstructions(): Promise<void> {
583
+ if (!this.running) return;
584
+ if (this.config.skipInstructions) return;
585
+
586
+ // Use escaped prefix (\->relay:) in examples to prevent parser from treating them as real commands
587
+ const escapedPrefix = '\\' + this.relayPrefix;
588
+
589
+ // Build instructions including relay and trail
590
+ const relayInstructions = [
591
+ `[Agent Relay] You are "${this.config.name}" - connected for real-time messaging.`,
592
+ `SEND: ${escapedPrefix}AgentName message`,
593
+ `MULTI-LINE: ${escapedPrefix}AgentName <<<(newline)content(newline)>>> - ALWAYS end with >>> on its own line!`,
594
+ `IMPORTANT: Do NOT include self-identification or preamble in messages. Start with your actual response content.`,
595
+ `PERSIST: Output [[SUMMARY]]{"currentTask":"...","context":"..."}[[/SUMMARY]] after major work.`,
596
+ `END: Output [[SESSION_END]]{"summary":"..."}[[/SESSION_END]] when session complete.`,
597
+ ].join(' | ');
598
+
599
+ // Add trail instructions if available
600
+ const trailInstructions = getCompactTrailInstructions();
601
+
602
+ try {
603
+ await this.sendKeysLiteral(relayInstructions);
604
+ await sleep(50);
605
+ await this.sendKeys('Enter');
606
+
607
+ // Inject trail instructions
608
+ if (this.trajectory?.isTrailInstalledSync()) {
609
+ await sleep(100);
610
+ await this.sendKeysLiteral(trailInstructions);
611
+ await sleep(50);
612
+ await this.sendKeys('Enter');
613
+ }
614
+
615
+ // Inject continuity context from previous session
616
+ await this.injectContinuityContext();
617
+ } catch {
618
+ // Silent fail - instructions are nice-to-have
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Inject continuity context from previous session
624
+ */
625
+ private async injectContinuityContext(): Promise<void> {
626
+ if (!this.continuity || !this.running) return;
627
+
628
+ try {
629
+ const context = await this.continuity.getStartupContext(this.config.name);
630
+ if (context && context.formatted) {
631
+ // Inject a brief notification about loaded context
632
+ const notification = `[Continuity] Previous session context loaded. ${
633
+ context.ledger ? `Task: ${context.ledger.currentTask?.slice(0, 50) || 'unknown'}` : ''
634
+ }${context.handoff ? ` | Last handoff: ${context.handoff.createdAt.toISOString().split('T')[0]}` : ''}`;
635
+
636
+ await sleep(200);
637
+ await this.sendKeysLiteral(notification);
638
+ await sleep(50);
639
+ await this.sendKeys('Enter');
640
+
641
+ // Queue the full context for injection when agent is ready
642
+ this.messageQueue.push({
643
+ from: 'system',
644
+ body: context.formatted,
645
+ messageId: `continuity-startup-${Date.now()}`,
646
+ });
647
+ this.checkForInjectionOpportunity();
648
+
649
+ if (this.config.debug) {
650
+ this.logStderr(`[CONTINUITY] Loaded context for ${this.config.name}`);
651
+ }
652
+ }
653
+ } catch (err: any) {
654
+ this.logStderr(`[CONTINUITY] Failed to load context: ${err.message}`, true);
655
+ }
656
+ }
657
+
658
+ /**
659
+ * Wait for tmux session to be ready
660
+ */
661
+ private async waitForSession(maxWaitMs = 5000): Promise<void> {
662
+ const startTime = Date.now();
663
+
664
+ while (Date.now() - startTime < maxWaitMs) {
665
+ if (await this.sessionExists()) {
666
+ await new Promise(r => setTimeout(r, 200));
667
+ return;
668
+ }
669
+ await new Promise(r => setTimeout(r, 100));
670
+ }
671
+
672
+ throw new Error('Timeout waiting for tmux session');
673
+ }
674
+
675
+ /**
676
+ * Wait for shell prompt to appear (shell is ready for input)
677
+ */
678
+ private async waitForShellReady(maxWaitMs = 10000): Promise<void> {
679
+ const startTime = Date.now();
680
+ // Common prompt endings: $, %, >, ➜, #
681
+ const promptPatterns = /[$%>#➜]\s*$/;
682
+
683
+ this.logStderr('Waiting for shell to initialize...');
684
+
685
+ while (Date.now() - startTime < maxWaitMs) {
686
+ try {
687
+ const { stdout } = await execAsync(
688
+ // -J joins wrapped lines so long prompts/messages stay intact
689
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J 2>/dev/null`
690
+ );
691
+
692
+ // Check if the last non-empty line looks like a prompt
693
+ const lines = stdout.split('\n').filter(l => l.trim());
694
+ const lastLine = lines[lines.length - 1] || '';
695
+
696
+ if (promptPatterns.test(lastLine)) {
697
+ this.logStderr('Shell ready');
698
+ // Extra delay to ensure shell is fully ready
699
+ await sleep(200);
700
+ return;
701
+ }
702
+ } catch {
703
+ // Session might not be ready yet
704
+ }
705
+
706
+ await sleep(200);
707
+ }
708
+
709
+ // Fallback: proceed anyway after timeout
710
+ this.logStderr('Shell ready timeout, proceeding anyway');
711
+ }
712
+
713
+ /**
714
+ * Attach user to tmux session
715
+ * This spawns tmux attach and lets it take over stdin/stdout
716
+ */
717
+ private attachToSession(): void {
718
+ this.attachProcess = spawn(this.tmuxPath, ['attach-session', '-t', this.sessionName], {
719
+ stdio: 'inherit', // User's terminal connects directly to tmux
720
+ });
721
+
722
+ this.attachProcess.on('exit', (code) => {
723
+ this.logStderr(`Session ended (code: ${code})`, true);
724
+ this.stop();
725
+ process.exit(code ?? 0);
726
+ });
727
+
728
+ this.attachProcess.on('error', (err) => {
729
+ this.logStderr(`Attach error: ${err.message}`, true);
730
+ this.stop();
731
+ process.exit(1);
732
+ });
733
+
734
+ // Handle signals
735
+ const cleanup = () => {
736
+ this.stop();
737
+ };
738
+ process.on('SIGINT', cleanup);
739
+ process.on('SIGTERM', cleanup);
740
+ }
741
+
742
+ /**
743
+ * Start silent polling for ->relay commands
744
+ * Does NOT write to stdout - just parses and sends to daemon
745
+ */
746
+ private startSilentPolling(): void {
747
+ this.pollTimer = setInterval(() => {
748
+ this.pollForRelayCommands().catch(() => {
749
+ // Ignore poll errors
750
+ });
751
+ }, this.config.pollInterval);
752
+ }
753
+
754
+ /**
755
+ * Poll for ->relay commands in output (silent)
756
+ */
757
+ private async pollForRelayCommands(): Promise<void> {
758
+ if (!this.running) return;
759
+
760
+ try {
761
+ // Capture scrollback
762
+ const { stdout } = await execAsync(
763
+ // -J joins wrapped lines to avoid truncating ->relay commands mid-line
764
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J -S - 2>/dev/null`
765
+ );
766
+
767
+ // Always parse the FULL capture for ->relay commands
768
+ // This handles terminal UIs that rewrite content in place
769
+ const cleanContent = stripAnsi(stdout);
770
+ // Join continuation lines that TUIs split across multiple lines
771
+ const joinedContent = this.joinContinuationLines(cleanContent);
772
+ const { commands, output: filteredOutput } = this.parser.parse(joinedContent);
773
+
774
+ // Debug: log relay commands being parsed
775
+ if (commands.length > 0 && this.config.debug) {
776
+ for (const cmd of commands) {
777
+ const bodyPreview = cmd.body.substring(0, 80).replace(/\n/g, '\\n');
778
+ this.logStderr(`[RELAY_PARSED] to=${cmd.to}, body="${bodyPreview}...", lines=${cmd.body.split('\n').length}`);
779
+ }
780
+ }
781
+
782
+ // Track last output time for injection timing
783
+ if (stdout.length !== this.processedOutputLength) {
784
+ this.lastOutputTime = Date.now();
785
+ this.markActivity();
786
+
787
+ // Feed new output to idle detector for more robust idle detection
788
+ const newOutput = stdout.substring(this.processedOutputLength);
789
+ this.feedIdleDetectorOutput(newOutput);
790
+
791
+ this.processedOutputLength = stdout.length;
792
+
793
+ // Stream new output to daemon for dashboard log viewing
794
+ // Use filtered output to exclude thinking blocks and relay commands
795
+ if (this.config.streamLogs && this.client.state === 'READY') {
796
+ // Send incremental filtered output since last log
797
+ const newContent = filteredOutput.substring(this.lastLoggedLength);
798
+ if (newContent.length > 0) {
799
+ this.client.sendLog(newContent);
800
+ this.lastLoggedLength = filteredOutput.length;
801
+ }
802
+ }
803
+ }
804
+
805
+ // Send any commands found (deduplication handles repeats)
806
+ for (const cmd of commands) {
807
+ this.sendRelayCommand(cmd);
808
+ }
809
+
810
+ // Check for [[SUMMARY]] blocks and save to storage
811
+ this.parseSummaryAndSave(cleanContent);
812
+
813
+ // Detect PDERO phase transitions from output content
814
+ this.detectAndTransitionPhase(cleanContent);
815
+
816
+ // Parse and handle continuity commands (->continuity:save, ->continuity:load, etc.)
817
+ await this.parseContinuityCommands(joinedContent);
818
+
819
+ // Check for [[SESSION_END]] blocks to explicitly close session
820
+ this.parseSessionEndAndClose(cleanContent);
821
+
822
+ // Check for ->relay:spawn and ->relay:release commands (any agent can spawn)
823
+ // Use joinedContent to handle multi-line output from TUIs like Claude Code
824
+ this.parseSpawnReleaseCommands(joinedContent);
825
+
826
+ // Check for auth revocation (limited sessions scenario)
827
+ this.checkAuthRevocation(cleanContent);
828
+
829
+ this.updateActivityState();
830
+
831
+ // Also check for injection opportunity
832
+ this.checkForInjectionOpportunity();
833
+
834
+ } catch (err: any) {
835
+ if (err.message?.includes('no such session')) {
836
+ this.stop();
837
+ }
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Record recent activity and transition back to active if needed.
843
+ */
844
+ private markActivity(): void {
845
+ this.lastActivityTime = Date.now();
846
+ if (this.activityState === 'idle') {
847
+ this.activityState = 'active';
848
+ this.logStderr('Session active');
849
+ }
850
+ }
851
+
852
+ /**
853
+ * Update activity state based on idle threshold and trigger injections when idle.
854
+ */
855
+ private updateActivityState(): void {
856
+ if (this.activityState === 'disconnected') return;
857
+
858
+ const now = Date.now();
859
+ const idleThreshold = this.config.activityIdleThresholdMs ?? 30000;
860
+ const timeSinceActivity = now - this.lastActivityTime;
861
+
862
+ if (timeSinceActivity > idleThreshold && this.activityState === 'active') {
863
+ this.activityState = 'idle';
864
+ this.logStderr('Session went idle');
865
+ this.checkForInjectionOpportunity();
866
+ } else if (timeSinceActivity <= idleThreshold && this.activityState === 'idle') {
867
+ this.activityState = 'active';
868
+ this.logStderr('Session active');
869
+ }
870
+ }
871
+
872
+ /**
873
+ * Check if the CLI output indicates auth has been revoked.
874
+ * This can happen when the user authenticates elsewhere (limited sessions).
875
+ */
876
+ private checkAuthRevocation(output: string): void {
877
+ // Don't check if already revoked or if we checked recently
878
+ if (this.authRevoked) return;
879
+ const now = Date.now();
880
+ if (now - this.lastAuthCheck < this.AUTH_CHECK_INTERVAL) return;
881
+ this.lastAuthCheck = now;
882
+
883
+ // Get the CLI type/provider from config
884
+ const provider = this.config.program || this.cliType || 'claude';
885
+
886
+ // Check for auth revocation patterns in recent output
887
+ const result = detectProviderAuthRevocation(output, provider);
888
+
889
+ if (result.detected && result.confidence !== 'low') {
890
+ this.authRevoked = true;
891
+ this.logStderr(`[AUTH] Auth revocation detected (${result.confidence} confidence): ${result.message}`);
892
+
893
+ // Send auth status message to daemon
894
+ if (this.client.state === 'READY') {
895
+ const authPayload = JSON.stringify({
896
+ type: 'auth_revoked',
897
+ agent: this.config.name,
898
+ provider,
899
+ message: result.message,
900
+ confidence: result.confidence,
901
+ timestamp: new Date().toISOString(),
902
+ });
903
+ this.client.sendMessage('#system', authPayload, 'message');
904
+ }
905
+
906
+ // Emit event for listeners
907
+ this.emit('auth_revoked', {
908
+ agent: this.config.name,
909
+ provider,
910
+ message: result.message,
911
+ confidence: result.confidence,
912
+ });
913
+ }
914
+ }
915
+
916
+ /**
917
+ * Reset auth revocation state (called after successful re-authentication)
918
+ */
919
+ public resetAuthState(): void {
920
+ this.authRevoked = false;
921
+ this.lastAuthCheck = 0;
922
+ this.logStderr('[AUTH] Auth state reset');
923
+ }
924
+
925
+ /**
926
+ * Check if auth has been revoked
927
+ */
928
+ public isAuthRevoked(): boolean {
929
+ return this.authRevoked;
930
+ }
931
+
932
+ /**
933
+ * Send relay command to daemon (overrides BaseWrapper for offline queue support)
934
+ */
935
+ protected override sendRelayCommand(cmd: ParsedCommand): void {
936
+ const msgHash = `${cmd.to}:${cmd.body}`;
937
+
938
+ // Permanent dedup - never send the same message twice
939
+ if (this.sentMessageHashes.has(msgHash)) {
940
+ this.logStderr(`[DEDUP] Skipped duplicate message to ${cmd.to} (hash already sent)`);
941
+ return;
942
+ }
943
+
944
+ // If client not ready, queue for later and return
945
+ if (this.client.state !== 'READY') {
946
+ if (this.queuedMessageHashes.has(msgHash)) {
947
+ return; // Already queued
948
+ }
949
+ if (this.pendingRelayCommands.length >= this.MAX_PENDING_RELAY_COMMANDS) {
950
+ this.logStderr('Relay offline queue full, dropping oldest');
951
+ const dropped = this.pendingRelayCommands.shift();
952
+ if (dropped) {
953
+ this.queuedMessageHashes.delete(`${dropped.to}:${dropped.body}`);
954
+ }
955
+ }
956
+ this.pendingRelayCommands.push(cmd);
957
+ this.queuedMessageHashes.add(msgHash);
958
+ this.logStderr(`Relay offline; queued message to ${cmd.to}`);
959
+ return;
960
+ }
961
+
962
+ // Convert ParsedMessageMetadata to SendMeta if present
963
+ let sendMeta: SendMeta | undefined;
964
+ if (cmd.meta) {
965
+ sendMeta = {
966
+ importance: cmd.meta.importance,
967
+ replyTo: cmd.meta.replyTo,
968
+ requires_ack: cmd.meta.ackRequired,
969
+ };
970
+ }
971
+
972
+ // Check if target is a channel (starts with #)
973
+ if (cmd.to.startsWith('#')) {
974
+ // Use CHANNEL_MESSAGE protocol for channel targets
975
+ this.logStderr(`→ [channel] ${cmd.to}: ${cmd.body.substring(0, Math.min(RELAY_LOG_TRUNCATE_LENGTH, cmd.body.length))}...`);
976
+ const success = this.client.sendChannelMessage(cmd.to, cmd.body, {
977
+ thread: cmd.thread,
978
+ data: cmd.data,
979
+ });
980
+ if (success) {
981
+ this.sentMessageHashes.add(msgHash);
982
+ this.queuedMessageHashes.delete(msgHash);
983
+ this.trajectory?.message('sent', this.config.name, cmd.to, cmd.body);
984
+ }
985
+ return;
986
+ }
987
+
988
+ // Use SEND protocol for direct messages and broadcasts
989
+ if (cmd.sync?.blocking) {
990
+ this.client.sendAndWait(cmd.to, cmd.body, {
991
+ timeoutMs: cmd.sync.timeoutMs,
992
+ kind: cmd.kind,
993
+ data: cmd.data,
994
+ thread: cmd.thread,
995
+ }).then(() => {
996
+ this.sentMessageHashes.add(msgHash);
997
+ this.queuedMessageHashes.delete(msgHash);
998
+ }).catch((err) => {
999
+ this.logStderr(`sendAndWait failed for ${cmd.to}: ${err.message}`, true);
1000
+ });
1001
+ return;
1002
+ }
1003
+
1004
+ const success = this.client.sendMessage(cmd.to, cmd.body, cmd.kind, cmd.data, cmd.thread, sendMeta);
1005
+ if (success) {
1006
+ this.sentMessageHashes.add(msgHash);
1007
+ this.queuedMessageHashes.delete(msgHash);
1008
+ const truncatedBody = cmd.body.substring(0, Math.min(RELAY_LOG_TRUNCATE_LENGTH, cmd.body.length));
1009
+ this.logStderr(`→ ${cmd.to}: ${truncatedBody}...`);
1010
+
1011
+ // Record in trajectory via trail
1012
+ this.trajectory?.message('sent', this.config.name, cmd.to, cmd.body);
1013
+ } else if (this.client.state !== 'READY') {
1014
+ // Only log failure once per state change
1015
+ this.logStderr(`Send failed (client ${this.client.state})`);
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * Flush any queued relay commands when the client reconnects.
1021
+ */
1022
+ private flushQueuedRelayCommands(): void {
1023
+ if (this.pendingRelayCommands.length === 0) return;
1024
+
1025
+ const queued = [...this.pendingRelayCommands];
1026
+ this.pendingRelayCommands = [];
1027
+ this.queuedMessageHashes.clear();
1028
+
1029
+ for (const cmd of queued) {
1030
+ this.sendRelayCommand(cmd);
1031
+ }
1032
+ }
1033
+
1034
+ /**
1035
+ * Parse [[SUMMARY]] blocks from output and save to storage.
1036
+ * Agents can output summaries to maintain running context:
1037
+ *
1038
+ * [[SUMMARY]]
1039
+ * {"currentTask": "Implementing auth", "context": "Completed login flow"}
1040
+ * [[/SUMMARY]]
1041
+ */
1042
+ private parseSummaryAndSave(content: string): void {
1043
+ const result = parseSummaryWithDetails(content);
1044
+
1045
+ // No SUMMARY block found
1046
+ if (!result.found) return;
1047
+
1048
+ // Dedup based on raw content - prevents repeated error logging for same invalid JSON
1049
+ if (result.rawContent === this.lastSummaryRawContent) return;
1050
+ this.lastSummaryRawContent = result.rawContent || '';
1051
+
1052
+ // Invalid JSON - log error once (deduped above)
1053
+ if (!result.valid) {
1054
+ this.logStderr('[parser] Invalid JSON in SUMMARY block');
1055
+ return;
1056
+ }
1057
+
1058
+ const summary = result.summary!;
1059
+
1060
+ // Dedup valid summaries - don't save same summary twice
1061
+ const summaryHash = JSON.stringify(summary);
1062
+ if (summaryHash === this.lastSummaryHash) return;
1063
+ this.lastSummaryHash = summaryHash;
1064
+
1065
+ // Save to continuity ledger for session recovery
1066
+ // This ensures the ledger has actual data instead of placeholders
1067
+ if (this.continuity) {
1068
+ this.saveSummaryToLedger(summary).catch(err => {
1069
+ this.logStderr(`Failed to save summary to ledger: ${err.message}`, true);
1070
+ });
1071
+ }
1072
+
1073
+ // Wait for storage to be ready before saving to project storage
1074
+ this.storageReady.then(ready => {
1075
+ if (!ready || !this.storage) {
1076
+ this.logStderr('Cannot save summary: storage not initialized');
1077
+ return;
1078
+ }
1079
+
1080
+ const projectPaths = getProjectPaths();
1081
+ this.storage.saveAgentSummary({
1082
+ agentName: this.config.name,
1083
+ projectId: projectPaths.projectId,
1084
+ currentTask: summary.currentTask,
1085
+ completedTasks: summary.completedTasks,
1086
+ decisions: summary.decisions,
1087
+ context: summary.context,
1088
+ files: summary.files,
1089
+ }).then(() => {
1090
+ this.logStderr(`Saved agent summary: ${summary.currentTask || 'updated context'}`);
1091
+ }).catch(err => {
1092
+ this.logStderr(`Failed to save summary: ${err.message}`, true);
1093
+ });
1094
+ });
1095
+ }
1096
+
1097
+ /**
1098
+ * Save a parsed summary to the continuity ledger (uses logStderr for tmux).
1099
+ * Maps summary fields to ledger fields for session recovery.
1100
+ */
1101
+ protected override async saveSummaryToLedger(summary: ParsedSummary): Promise<void> {
1102
+ if (!this.continuity) return;
1103
+
1104
+ const updates: Record<string, unknown> = {};
1105
+
1106
+ // Map summary fields to ledger fields
1107
+ if (summary.currentTask) {
1108
+ updates.currentTask = summary.currentTask;
1109
+ }
1110
+
1111
+ if (summary.completedTasks && summary.completedTasks.length > 0) {
1112
+ updates.completed = summary.completedTasks;
1113
+ }
1114
+
1115
+ if (summary.context) {
1116
+ // Store context in inProgress as "next steps" hint
1117
+ updates.inProgress = [summary.context];
1118
+ }
1119
+
1120
+ if (summary.files && summary.files.length > 0) {
1121
+ updates.fileContext = summary.files.map((f: string) => ({ path: f }));
1122
+ }
1123
+
1124
+ // Only save if we have meaningful updates
1125
+ if (Object.keys(updates).length > 0) {
1126
+ await this.continuity.saveLedger(this.config.name, updates);
1127
+ this.logStderr('Saved summary to continuity ledger');
1128
+ }
1129
+ }
1130
+
1131
+ /**
1132
+ * Parse ->continuity: commands from output and handle them.
1133
+ * Supported commands:
1134
+ * ->continuity:save <<<...>>> - Save session state to ledger
1135
+ * ->continuity:load - Request context injection
1136
+ * ->continuity:search "query" - Search past handoffs
1137
+ * ->continuity:uncertain "..." - Mark item as uncertain
1138
+ * ->continuity:handoff <<<...>>> - Create explicit handoff
1139
+ */
1140
+ protected override async parseContinuityCommands(content: string): Promise<void> {
1141
+ if (!this.continuity) return;
1142
+ if (!hasContinuityCommand(content)) return;
1143
+
1144
+ const command = parseContinuityCommand(content);
1145
+ if (!command) return;
1146
+
1147
+ // Create a hash for deduplication
1148
+ // For commands with content (save, handoff, uncertain), use content hash
1149
+ // For commands without content (load, search), allow each unique call
1150
+ const hasContent = command.content || command.query || command.item;
1151
+ const cmdHash = hasContent
1152
+ ? `${command.type}:${command.content || command.query || command.item}`
1153
+ : `${command.type}:${Date.now()}`; // Allow load/search to run each time
1154
+ if (hasContent && this.processedContinuityCommands.has(cmdHash)) return;
1155
+ this.processedContinuityCommands.add(cmdHash);
1156
+
1157
+ // Limit dedup set size
1158
+ if (this.processedContinuityCommands.size > 100) {
1159
+ const oldest = this.processedContinuityCommands.values().next().value;
1160
+ if (oldest) this.processedContinuityCommands.delete(oldest);
1161
+ }
1162
+
1163
+ try {
1164
+ if (this.config.debug) {
1165
+ this.logStderr(`[CONTINUITY] Processing ${command.type} command`);
1166
+ }
1167
+
1168
+ const response = await this.continuity.handleCommand(this.config.name, command);
1169
+
1170
+ // If there's a response (e.g., from load or search), inject it
1171
+ if (response) {
1172
+ this.messageQueue.push({
1173
+ from: 'system',
1174
+ body: response,
1175
+ messageId: `continuity-${Date.now()}`,
1176
+ });
1177
+ this.checkForInjectionOpportunity();
1178
+ }
1179
+ } catch (err: any) {
1180
+ this.logStderr(`[CONTINUITY] Error: ${err.message}`, true);
1181
+ }
1182
+ }
1183
+
1184
+ /**
1185
+ * Parse [[SESSION_END]] blocks from output and close session explicitly.
1186
+ * Agents output this to mark their work session as complete:
1187
+ *
1188
+ * [[SESSION_END]]
1189
+ * {"summary": "Completed auth module", "completedTasks": ["login", "logout"]}
1190
+ * [[/SESSION_END]]
1191
+ *
1192
+ * Also stores the data for use in autoSave to populate handoff (fixes empty handoff issue).
1193
+ */
1194
+ private parseSessionEndAndClose(content: string): void {
1195
+ if (this.sessionEndProcessed) return; // Only process once per session
1196
+
1197
+ const sessionEnd = parseSessionEndFromOutput(content);
1198
+ if (!sessionEnd) return;
1199
+
1200
+ // Store SESSION_END data for use in autoSave (fixes empty handoff issue)
1201
+ this.sessionEndData = sessionEnd;
1202
+
1203
+ // Get session ID from client connection - if not available yet, don't set flag
1204
+ // so we can retry when sessionId becomes available
1205
+ const sessionId = this.client.currentSessionId;
1206
+ if (!sessionId) {
1207
+ this.logStderr('Cannot close session: no session ID yet, will retry');
1208
+ return;
1209
+ }
1210
+
1211
+ this.sessionEndProcessed = true;
1212
+
1213
+ // Wait for storage to be ready before attempting to close session
1214
+ this.storageReady.then(ready => {
1215
+ if (!ready || !this.storage) {
1216
+ this.logStderr('Cannot close session: storage not initialized');
1217
+ return;
1218
+ }
1219
+
1220
+ this.storage.endSession(sessionId, {
1221
+ summary: sessionEnd.summary,
1222
+ closedBy: 'agent',
1223
+ }).then(() => {
1224
+ this.logStderr(`Session closed by agent: ${sessionEnd.summary || 'complete'}`);
1225
+ }).catch(err => {
1226
+ this.logStderr(`Failed to close session: ${err.message}`, true);
1227
+ });
1228
+ });
1229
+ }
1230
+
1231
+ /**
1232
+ * Execute spawn via API (if dashboardPort set) or callback.
1233
+ * After spawning, waits for the agent to come online and sends the task via relay.
1234
+ */
1235
+ protected override async executeSpawn(name: string, cli: string, task: string): Promise<void> {
1236
+ let spawned = false;
1237
+
1238
+ if (this.config.dashboardPort) {
1239
+ // Use dashboard API for spawning (works from any context, no terminal required)
1240
+ try {
1241
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/spawn`, {
1242
+ method: 'POST',
1243
+ headers: { 'Content-Type': 'application/json' },
1244
+ body: JSON.stringify({ name, cli }), // No task - we send it after agent is online
1245
+ });
1246
+ const result = await response.json() as { success: boolean; error?: string };
1247
+ if (result.success) {
1248
+ this.logStderr(`Spawned ${name} via API`);
1249
+ spawned = true;
1250
+ } else {
1251
+ this.logStderr(`Spawn failed: ${result.error}`, true);
1252
+ }
1253
+ } catch (err: any) {
1254
+ this.logStderr(`Spawn API call failed: ${err.message}`, true);
1255
+ }
1256
+ } else if (this.config.onSpawn) {
1257
+ // Fall back to callback
1258
+ try {
1259
+ await this.config.onSpawn(name, cli, task);
1260
+ spawned = true;
1261
+ } catch (err: any) {
1262
+ this.logStderr(`Spawn failed: ${err.message}`, true);
1263
+ }
1264
+ }
1265
+
1266
+ // If spawn succeeded and we have a task, wait for agent to come online and send it
1267
+ if (spawned && task && task.trim() && this.config.dashboardPort) {
1268
+ await this.waitAndSendTask(name, task);
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * Wait for a spawned agent to come online, then send the task via relay.
1274
+ * Uses the wrapper's own relay client so the message comes "from" this agent,
1275
+ * not from the dashboard's relay client.
1276
+ */
1277
+ private async waitAndSendTask(agentName: string, task: string): Promise<void> {
1278
+ const maxWaitMs = 30000;
1279
+ const pollIntervalMs = 500;
1280
+ const startTime = Date.now();
1281
+
1282
+ this.logStderr(`Waiting for ${agentName} to come online...`);
1283
+
1284
+ // Poll for agent to be online using dedicated status endpoint
1285
+ while (Date.now() - startTime < maxWaitMs) {
1286
+ try {
1287
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/agents/${encodeURIComponent(agentName)}/online`);
1288
+ const data = await response.json() as { name: string; online: boolean };
1289
+
1290
+ if (data.online) {
1291
+ this.logStderr(`${agentName} is online, sending task...`);
1292
+
1293
+ // Send task directly via our relay client (not dashboard API)
1294
+ // This ensures the message comes "from" this agent, not from _DashboardUI
1295
+ if (this.client.state === 'READY') {
1296
+ const sent = this.client.sendMessage(agentName, task, 'message');
1297
+ if (sent) {
1298
+ this.logStderr(`Task sent to ${agentName}`);
1299
+ } else {
1300
+ this.logStderr(`Failed to send task to ${agentName}: sendMessage returned false`, true);
1301
+ }
1302
+ } else {
1303
+ this.logStderr(`Failed to send task to ${agentName}: relay client not ready (state: ${this.client.state})`, true);
1304
+ }
1305
+ return;
1306
+ }
1307
+ } catch (_err: unknown) {
1308
+ // Ignore poll errors, keep trying
1309
+ }
1310
+
1311
+ await sleep(pollIntervalMs);
1312
+ }
1313
+
1314
+ this.logStderr(`Timeout waiting for ${agentName} to come online`, true);
1315
+ }
1316
+
1317
+ /**
1318
+ * Execute release via API (if dashboardPort set) or callback
1319
+ */
1320
+ protected override async executeRelease(name: string): Promise<void> {
1321
+ if (this.config.dashboardPort) {
1322
+ // Use dashboard API for release (works from any context, no terminal required)
1323
+ try {
1324
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/spawned/${encodeURIComponent(name)}`, {
1325
+ method: 'DELETE',
1326
+ });
1327
+ const result = await response.json() as { success: boolean; error?: string };
1328
+ if (result.success) {
1329
+ this.logStderr(`Released ${name} via API`);
1330
+ } else {
1331
+ this.logStderr(`Release failed: ${result.error}`, true);
1332
+ }
1333
+ } catch (err: any) {
1334
+ this.logStderr(`Release API call failed: ${err.message}`, true);
1335
+ }
1336
+ } else if (this.config.onRelease) {
1337
+ // Fall back to callback
1338
+ try {
1339
+ await this.config.onRelease(name);
1340
+ } catch (err: any) {
1341
+ this.logStderr(`Release failed: ${err.message}`, true);
1342
+ }
1343
+ }
1344
+ }
1345
+
1346
+ /**
1347
+ * Parse ->relay:spawn and ->relay:release commands from output.
1348
+ * Supports two formats:
1349
+ * Single-line: ->relay:spawn WorkerName cli "task description"
1350
+ * Multi-line (fenced): ->relay:spawn WorkerName cli <<<
1351
+ * task description here
1352
+ * can span multiple lines>>>
1353
+ * ->relay:release WorkerName
1354
+ */
1355
+ protected override parseSpawnReleaseCommands(content: string): void {
1356
+ // Only process if we have API or callbacks configured
1357
+ const canSpawn = this.config.dashboardPort || this.config.onSpawn;
1358
+ const canRelease = this.config.dashboardPort || this.config.onRelease;
1359
+
1360
+ // Debug: Log spawn capability status
1361
+ if (content.includes('->relay:spawn')) {
1362
+ this.logStderr(`[spawn-debug] canSpawn=${!!canSpawn} dashboardPort=${this.config.dashboardPort} hasOnSpawn=${!!this.config.onSpawn}`);
1363
+ }
1364
+
1365
+ if (!canSpawn && !canRelease) return;
1366
+
1367
+ const lines = content.split('\n');
1368
+
1369
+ // Pattern to strip common line prefixes (bullets, prompts, etc.)
1370
+ // Must include ● (U+25CF BLACK CIRCLE) used by Claude's TUI
1371
+ const linePrefixPattern = /^(?:[>$%#→➜›»●•◦‣⁃\-*⏺◆◇○□■│┃┆┇┊┋╎╏✦]\s*)+/;
1372
+
1373
+ for (const line of lines) {
1374
+ let trimmed = line.trim();
1375
+
1376
+ // Strip common line prefixes (bullets, prompts) before checking for commands
1377
+ trimmed = trimmed.replace(linePrefixPattern, '');
1378
+
1379
+ // Fix for over-stripping: the linePrefixPattern includes - and > characters,
1380
+ // which can accidentally strip the -> from ->relay:spawn, leaving just relay:spawn.
1381
+ // If we detect this happened, restore the -> prefix.
1382
+ if (/^(relay|thinking|continuity):/.test(trimmed)) {
1383
+ trimmed = '->' + trimmed;
1384
+ }
1385
+
1386
+ // If we're in fenced spawn mode, accumulate lines until we see >>>
1387
+ if (this.pendingFencedSpawn) {
1388
+ // Check for fence close (>>> at end of line or on its own line)
1389
+ const closeIdx = trimmed.indexOf('>>>');
1390
+ if (closeIdx !== -1) {
1391
+ // Add content before >>> to task
1392
+ const contentBeforeClose = trimmed.substring(0, closeIdx);
1393
+ if (contentBeforeClose) {
1394
+ this.pendingFencedSpawn.taskLines.push(contentBeforeClose);
1395
+ }
1396
+
1397
+ // Execute the spawn with accumulated task
1398
+ const { name, cli, taskLines } = this.pendingFencedSpawn;
1399
+ const taskStr = taskLines.join('\n').trim();
1400
+ const spawnKey = `${name}:${cli}`;
1401
+
1402
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1403
+ this.processedSpawnCommands.add(spawnKey);
1404
+ if (taskStr) {
1405
+ this.logStderr(`Spawn command (fenced): ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1406
+ } else {
1407
+ this.logStderr(`Spawn command (fenced): ${name} (${cli}) - no task`);
1408
+ }
1409
+ this.executeSpawn(name, cli, taskStr);
1410
+ }
1411
+
1412
+ this.pendingFencedSpawn = null;
1413
+ } else {
1414
+ // Accumulate line as part of task
1415
+ this.pendingFencedSpawn.taskLines.push(line);
1416
+ }
1417
+ continue;
1418
+ }
1419
+
1420
+ // Check for fenced spawn start: ->relay:spawn Name [cli] <<< (CLI optional, defaults to 'claude')
1421
+ // Prefixes are stripped above, so we just look for the command at start of line
1422
+ const fencedSpawnMatch = trimmed.match(/^->relay:spawn\s+(\S+)(?:\s+(\S+))?\s+<<<(.*)$/);
1423
+ if (fencedSpawnMatch && canSpawn) {
1424
+ const [, name, cliOrUndefined, inlineContent] = fencedSpawnMatch;
1425
+ const cli = cliOrUndefined || 'claude';
1426
+
1427
+ // Validate name
1428
+ if (name.length < 2) {
1429
+ this.logStderr(`Fenced spawn has invalid name, skipping: name=${name}`);
1430
+ continue;
1431
+ }
1432
+
1433
+ // Check if fence closes on same line (e.g., ->relay:spawn Worker cli <<<task>>>)
1434
+ const inlineCloseIdx = inlineContent.indexOf('>>>');
1435
+ if (inlineCloseIdx !== -1) {
1436
+ // Single line fenced: extract task between <<< and >>>
1437
+ const taskStr = inlineContent.substring(0, inlineCloseIdx).trim();
1438
+ const spawnKey = `${name}:${cli}`;
1439
+
1440
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1441
+ this.processedSpawnCommands.add(spawnKey);
1442
+ if (taskStr) {
1443
+ this.logStderr(`Spawn command: ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1444
+ } else {
1445
+ this.logStderr(`Spawn command: ${name} (${cli}) - no task`);
1446
+ }
1447
+ this.executeSpawn(name, cli, taskStr);
1448
+ }
1449
+ } else {
1450
+ // Start multi-line fenced mode
1451
+ this.pendingFencedSpawn = {
1452
+ name,
1453
+ cli,
1454
+ taskLines: inlineContent.trim() ? [inlineContent.trim()] : [],
1455
+ };
1456
+ this.logStderr(`Starting fenced spawn capture: ${name} (${cli})`);
1457
+ }
1458
+ continue;
1459
+ }
1460
+
1461
+ // Match single-line spawn: ->relay:spawn WorkerName [cli] ["task"]
1462
+ // CLI is optional - defaults to 'claude'. Task is also optional.
1463
+ // Prefixes are stripped above, so we just look for the command at start of line
1464
+ const spawnMatch = trimmed.match(/^->relay:spawn\s+(\S+)(?:\s+(\S+))?(?:\s+["'](.+?)["'])?\s*$/);
1465
+ if (spawnMatch && canSpawn) {
1466
+ const [, name, cliOrUndefined, task] = spawnMatch;
1467
+ const cli = cliOrUndefined || 'claude';
1468
+
1469
+ // Validate the parsed values
1470
+ if (cli === '<<<' || cli === '>>>' || name === '<<<' || name === '>>>') {
1471
+ this.logStderr(`Invalid spawn command (fence markers), skipping: name=${name}, cli=${cli}`);
1472
+ continue;
1473
+ }
1474
+ if (name.length < 2) {
1475
+ this.logStderr(`Spawn command has suspiciously short name, skipping: name=${name}`);
1476
+ continue;
1477
+ }
1478
+
1479
+ const taskStr = task || '';
1480
+ const spawnKey = `${name}:${cli}`;
1481
+
1482
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1483
+ this.processedSpawnCommands.add(spawnKey);
1484
+ if (taskStr) {
1485
+ this.logStderr(`Spawn command: ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1486
+ } else {
1487
+ this.logStderr(`Spawn command: ${name} (${cli}) - no task`);
1488
+ }
1489
+ this.executeSpawn(name, cli, taskStr);
1490
+ }
1491
+ continue;
1492
+ }
1493
+
1494
+ // Match ->relay:release WorkerName
1495
+ // Prefixes are stripped above, so we just look for the command at start of line
1496
+ const releaseMatch = trimmed.match(/^->relay:release\s+(\S+)\s*$/);
1497
+ if (releaseMatch && canRelease) {
1498
+ const [, name] = releaseMatch;
1499
+
1500
+ if (!this.processedReleaseCommands.has(name)) {
1501
+ this.processedReleaseCommands.add(name);
1502
+ this.logStderr(`Release command: ${name}`);
1503
+ this.executeRelease(name);
1504
+ }
1505
+ }
1506
+ }
1507
+ }
1508
+
1509
+ /**
1510
+ * Handle incoming message from relay
1511
+ * @param originalTo - The original 'to' field from sender. '*' indicates this was a broadcast message.
1512
+ * Agents should reply to originalTo to maintain channel routing (e.g., respond to #general, not DM).
1513
+ */
1514
+ protected override handleIncomingMessage(from: string, payload: SendPayload, messageId: string, meta?: SendMeta, originalTo?: string): void {
1515
+ if (this.hasSeenIncoming(messageId)) {
1516
+ this.logStderr(`← ${from}: duplicate delivery (${messageId.substring(0, 8)})`);
1517
+ return;
1518
+ }
1519
+
1520
+ const truncatedBody = payload.body.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, payload.body.length));
1521
+ const channelInfo = originalTo === '*' ? ' [broadcast]' : '';
1522
+ this.logStderr(`← ${from}${channelInfo}: ${truncatedBody}...`);
1523
+
1524
+ // Record in trajectory via trail
1525
+ this.trajectory?.message('received', from, this.config.name, payload.body);
1526
+
1527
+ // Queue for injection - include originalTo so we can inform the agent how to route responses
1528
+ this.messageQueue.push({
1529
+ from,
1530
+ body: payload.body,
1531
+ messageId,
1532
+ thread: payload.thread,
1533
+ importance: meta?.importance,
1534
+ data: payload.data,
1535
+ sync: meta?.sync,
1536
+ originalTo,
1537
+ });
1538
+
1539
+ // Write to inbox if enabled
1540
+ if (this.inbox) {
1541
+ this.inbox.addMessage(from, payload.body);
1542
+ }
1543
+
1544
+ // Try to inject
1545
+ this.checkForInjectionOpportunity();
1546
+ }
1547
+
1548
+ /**
1549
+ * Handle incoming channel message from relay.
1550
+ * Channel messages include a channel indicator so the agent knows to reply to the channel.
1551
+ */
1552
+ protected override handleIncomingChannelMessage(
1553
+ from: string,
1554
+ channel: string,
1555
+ body: string,
1556
+ envelope: import('@agent-relay/protocol/types').Envelope<import('@agent-relay/protocol/channels').ChannelMessagePayload>
1557
+ ): void {
1558
+ const messageId = envelope.id;
1559
+
1560
+ if (this.hasSeenIncoming(messageId)) {
1561
+ this.logStderr(`← ${from} [${channel}]: duplicate delivery (${messageId.substring(0, 8)})`);
1562
+ return;
1563
+ }
1564
+
1565
+ const truncatedBody = body.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, body.length));
1566
+ this.logStderr(`← ${from} [${channel}]: ${truncatedBody}...`);
1567
+
1568
+ // Record in trajectory via trail
1569
+ this.trajectory?.message('received', from, this.config.name, body);
1570
+
1571
+ // Queue for injection - include channel as originalTo so we can inform the agent how to route responses
1572
+ this.messageQueue.push({
1573
+ from,
1574
+ body,
1575
+ messageId,
1576
+ thread: envelope.payload.thread,
1577
+ data: {
1578
+ _isChannelMessage: true,
1579
+ _channel: channel,
1580
+ _mentions: envelope.payload.mentions,
1581
+ },
1582
+ originalTo: channel, // Set channel as the reply target
1583
+ });
1584
+
1585
+ // Write to inbox if enabled
1586
+ if (this.inbox) {
1587
+ this.inbox.addMessage(from, body);
1588
+ }
1589
+
1590
+ // Try to inject
1591
+ this.checkForInjectionOpportunity();
1592
+ }
1593
+
1594
+ /**
1595
+ * Check if we should inject a message.
1596
+ * Uses UniversalIdleDetector (from BaseWrapper) for robust cross-CLI idle detection.
1597
+ * Processes messages by priority (urgent first).
1598
+ */
1599
+ private checkForInjectionOpportunity(): void {
1600
+ if (this.messageQueue.length === 0) return;
1601
+ if (this.isInjecting) return;
1602
+ if (!this.running) return;
1603
+
1604
+ // Sort queue by priority before processing (urgent messages first)
1605
+ if (this.messageQueue.length > 1) {
1606
+ this.messageQueue = sortByPriority(this.messageQueue);
1607
+ }
1608
+
1609
+ // Check the priority of the next message
1610
+ const nextMsg = this.messageQueue[0];
1611
+ const priority = getPriorityFromImportance(nextMsg?.importance);
1612
+
1613
+ // Use universal idle detector for more reliable detection (inherited from BaseWrapper)
1614
+ const idleResult = this.checkIdleForInjection();
1615
+
1616
+ // Urgent messages (priority 0) can proceed with lower idle confidence
1617
+ const idleThreshold = priority === 0 ? 0.5 : 0.7;
1618
+
1619
+ if (!idleResult.isIdle && idleResult.confidence < idleThreshold) {
1620
+ // Not idle yet, retry later (urgent messages retry faster)
1621
+ const baseRetryMs = this.config.injectRetryMs ?? 300;
1622
+ const retryMs = priority <= 1 ? Math.floor(baseRetryMs / 2) : baseRetryMs;
1623
+ setTimeout(() => this.checkForInjectionOpportunity(), retryMs);
1624
+ return;
1625
+ }
1626
+
1627
+ this.injectNextMessage();
1628
+ }
1629
+
1630
+ /**
1631
+ * Inject message via tmux send-keys.
1632
+ * Uses shared injection logic with tmux-specific callbacks.
1633
+ */
1634
+ private async injectNextMessage(): Promise<void> {
1635
+ const msg = this.messageQueue.shift();
1636
+ if (!msg) return;
1637
+
1638
+ this.isInjecting = true;
1639
+
1640
+ try {
1641
+ const shortId = msg.messageId.substring(0, 8);
1642
+
1643
+ // Wait for input to be clear before injecting
1644
+ // If input is not clear (human typing), re-queue and try later - never clear forcefully!
1645
+ const waitTimeoutMs = this.config.inputWaitTimeoutMs ?? 5000;
1646
+ const waitPollMs = this.config.inputWaitPollMs ?? 200;
1647
+ const inputClear = await this.waitForClearInput(waitTimeoutMs, waitPollMs);
1648
+ if (!inputClear) {
1649
+ // Input still has text after timeout - DON'T clear forcefully, re-queue instead
1650
+ this.logStderr('Input not clear, re-queuing injection');
1651
+ this.messageQueue.unshift(msg);
1652
+ this.isInjecting = false;
1653
+ setTimeout(() => this.checkForInjectionOpportunity(), this.config.injectRetryMs ?? 1000);
1654
+ return;
1655
+ }
1656
+
1657
+ // Ensure pane output is stable to avoid interleaving with active generation
1658
+ // Pass message priority for adaptive timeout (urgent messages wait less)
1659
+ const msgPriority = getPriorityFromImportance(msg.importance);
1660
+ const stablePane = await this.waitForStablePane(
1661
+ this.config.outputStabilityTimeoutMs ?? 800,
1662
+ this.config.outputStabilityPollMs ?? 150,
1663
+ 2,
1664
+ msgPriority
1665
+ );
1666
+ if (!stablePane) {
1667
+ this.logStderr('Output still active, re-queuing injection');
1668
+ this.messageQueue.unshift(msg);
1669
+ this.isInjecting = false;
1670
+ setTimeout(() => this.checkForInjectionOpportunity(), this.config.injectRetryMs ?? 300);
1671
+ return;
1672
+ }
1673
+
1674
+ // For Gemini: check if we're at a shell prompt ($) vs chat prompt (>)
1675
+ // If at shell prompt, skip injection to avoid shell command execution
1676
+ if (this.cliType === 'gemini') {
1677
+ const lastLine = await this.getLastLine();
1678
+ const cleanLine = stripAnsi(lastLine).trim();
1679
+ if (CLI_QUIRKS.isShellPrompt(cleanLine)) {
1680
+ this.logStderr('Gemini at shell prompt, skipping injection to avoid shell execution');
1681
+ // Re-queue the message for later
1682
+ this.messageQueue.unshift(msg);
1683
+ this.isInjecting = false;
1684
+ setTimeout(() => this.checkForInjectionOpportunity(), 2000);
1685
+ return;
1686
+ }
1687
+ }
1688
+
1689
+ // Build injection string using shared utility
1690
+ let injection = buildInjectionString(msg);
1691
+
1692
+ // Gemini-specific: wrap body in backticks to prevent shell keyword interpretation
1693
+ if (this.cliType === 'gemini') {
1694
+ const colonIdx = injection.indexOf(': ');
1695
+ if (colonIdx > 0) {
1696
+ const prefix = injection.substring(0, colonIdx + 2);
1697
+ const body = injection.substring(colonIdx + 2);
1698
+ injection = prefix + CLI_QUIRKS.wrapForGemini(body);
1699
+ }
1700
+ }
1701
+
1702
+ // Create callbacks for shared injection logic
1703
+ const callbacks: InjectionCallbacks = {
1704
+ getOutput: async () => {
1705
+ try {
1706
+ const { stdout } = await execAsync(
1707
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -S - 2>/dev/null`
1708
+ );
1709
+ return stdout;
1710
+ } catch {
1711
+ return '';
1712
+ }
1713
+ },
1714
+ performInjection: async (inj: string) => {
1715
+ // Use send-keys -l (literal) instead of paste-buffer
1716
+ // paste-buffer causes issues where Claude shows "[Pasted text]" but content doesn't appear
1717
+ await this.sendKeysLiteral(inj);
1718
+ await sleep(INJECTION_CONSTANTS.ENTER_DELAY_MS);
1719
+ await this.sendKeys('Enter');
1720
+ },
1721
+ log: (message: string) => this.logStderr(message),
1722
+ logError: (message: string) => this.logStderr(message, true),
1723
+ getMetrics: () => this.injectionMetrics,
1724
+ };
1725
+
1726
+ // Inject with retry and verification using shared logic
1727
+ const result = await sharedInjectWithRetry(injection, shortId, msg.from, callbacks);
1728
+
1729
+ if (result.success) {
1730
+ this.logStderr(`Injection complete (attempt ${result.attempts})`);
1731
+ // Record success for adaptive throttling
1732
+ this.throttle.recordSuccess();
1733
+ this.sendSyncAck(msg.messageId, msg.sync, 'OK');
1734
+ } else {
1735
+ // All retries failed - log and optionally fall back to inbox
1736
+ this.logStderr(
1737
+ `Message delivery failed after ${result.attempts} attempts: from=${msg.from} id=${shortId}`,
1738
+ true
1739
+ );
1740
+ // Record failure for adaptive throttling
1741
+ this.throttle.recordFailure();
1742
+
1743
+ // Write to inbox as fallback if enabled
1744
+ if (this.inbox) {
1745
+ this.inbox.addMessage(msg.from, msg.body);
1746
+ this.logStderr('Wrote message to inbox as fallback');
1747
+ }
1748
+ this.sendSyncAck(msg.messageId, msg.sync, 'ERROR', { error: 'injection_failed' });
1749
+ }
1750
+
1751
+ } catch (err: any) {
1752
+ this.logStderr(`Injection failed: ${err.message}`, true);
1753
+ // Record failure for adaptive throttling
1754
+ this.throttle.recordFailure();
1755
+ this.sendSyncAck(msg.messageId, msg.sync, 'ERROR', { error: err.message });
1756
+ } finally {
1757
+ this.isInjecting = false;
1758
+
1759
+ // Process next message after adaptive delay (faster when healthy, slower under stress)
1760
+ if (this.messageQueue.length > 0) {
1761
+ const delay = this.throttle.getDelay();
1762
+ setTimeout(() => this.checkForInjectionOpportunity(), delay);
1763
+ }
1764
+ }
1765
+ }
1766
+
1767
+ private hasSeenIncoming(messageId: string): boolean {
1768
+ if (this.receivedMessageIdSet.has(messageId)) {
1769
+ return true;
1770
+ }
1771
+
1772
+ this.receivedMessageIdSet.add(messageId);
1773
+ this.receivedMessageIdOrder.push(messageId);
1774
+
1775
+ if (this.receivedMessageIdOrder.length > this.MAX_RECEIVED_MESSAGES) {
1776
+ const oldest = this.receivedMessageIdOrder.shift();
1777
+ if (oldest) {
1778
+ this.receivedMessageIdSet.delete(oldest);
1779
+ }
1780
+ }
1781
+
1782
+ return false;
1783
+ }
1784
+
1785
+ /**
1786
+ * Send special keys to tmux
1787
+ */
1788
+ private async sendKeys(keys: string): Promise<void> {
1789
+ const cmd = `"${this.tmuxPath}" send-keys -t ${this.sessionName} ${keys}`;
1790
+ try {
1791
+ await execAsync(cmd);
1792
+ this.logStderr(`[sendKeys] Sent: ${keys}`);
1793
+ } catch (err: any) {
1794
+ this.logStderr(`[sendKeys] Failed to send ${keys}: ${err.message}`, true);
1795
+ throw err;
1796
+ }
1797
+ }
1798
+
1799
+ /**
1800
+ * Send literal text to tmux
1801
+ */
1802
+ private async sendKeysLiteral(text: string): Promise<void> {
1803
+ // Escape for shell and use -l for literal
1804
+ // Must escape: \ " $ ` ! and remove any newlines
1805
+ const escaped = text
1806
+ .replace(/[\r\n]+/g, ' ') // Remove any newlines first
1807
+ .replace(/\\/g, '\\\\')
1808
+ .replace(/"/g, '\\"')
1809
+ .replace(/\$/g, '\\$')
1810
+ .replace(/`/g, '\\`')
1811
+ .replace(/!/g, '\\!');
1812
+ try {
1813
+ await execAsync(`"${this.tmuxPath}" send-keys -t ${this.sessionName} -l "${escaped}"`);
1814
+ this.logStderr(`[sendKeysLiteral] Sent ${text.length} chars`);
1815
+ } catch (err: any) {
1816
+ this.logStderr(`[sendKeysLiteral] Failed: ${err.message}`, true);
1817
+ throw err;
1818
+ }
1819
+ }
1820
+
1821
+ /**
1822
+ * Paste text using tmux buffer with optional bracketed paste to avoid interleaving with ongoing output.
1823
+ * Some CLIs (like droid) don't handle bracketed paste sequences properly, so we skip -p for them.
1824
+ */
1825
+ private async pasteLiteral(text: string): Promise<void> {
1826
+ // Sanitize newlines to keep injection single-line inside paste buffer
1827
+ const sanitized = text.replace(/[\r\n]+/g, ' ');
1828
+ const escaped = sanitized
1829
+ .replace(/\\/g, '\\\\')
1830
+ .replace(/"/g, '\\"')
1831
+ .replace(/\$/g, '\\$')
1832
+ .replace(/`/g, '\\`')
1833
+ .replace(/!/g, '\\!');
1834
+
1835
+ // Set tmux buffer then paste
1836
+ const setBufferCmd = `"${this.tmuxPath}" set-buffer -- "${escaped}"`;
1837
+ await execAsync(setBufferCmd);
1838
+ await execAsync(`"${this.tmuxPath}" paste-buffer -t ${this.sessionName}`);
1839
+ }
1840
+
1841
+ /**
1842
+ * Reset session-specific state for wrapper reuse.
1843
+ * Call this when starting a new session with the same wrapper instance.
1844
+ */
1845
+ override resetSessionState(): void {
1846
+ super.resetSessionState();
1847
+ // TmuxWrapper-specific state
1848
+ this.lastSummaryHash = '';
1849
+ }
1850
+
1851
+ /**
1852
+ * Get the prompt pattern for the current CLI type.
1853
+ */
1854
+ private getPromptPattern(): RegExp {
1855
+ return CLI_QUIRKS.getPromptPattern(this.cliType);
1856
+ }
1857
+
1858
+ /**
1859
+ * Capture the last non-empty line from the tmux pane.
1860
+ */
1861
+ private async getLastLine(): Promise<string> {
1862
+ try {
1863
+ const { stdout } = await execAsync(
1864
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J 2>/dev/null`
1865
+ );
1866
+ const lines = stdout.split('\n').filter(l => l.length > 0);
1867
+ return lines[lines.length - 1] || '';
1868
+ } catch {
1869
+ return '';
1870
+ }
1871
+ }
1872
+
1873
+ /**
1874
+ * Detect if the provided line contains visible user input (beyond the prompt).
1875
+ */
1876
+ private hasVisibleInput(line: string): boolean {
1877
+ const cleanLine = stripAnsi(line).trimEnd();
1878
+ if (cleanLine === '') return false;
1879
+
1880
+ return !this.getPromptPattern().test(cleanLine);
1881
+ }
1882
+
1883
+ /**
1884
+ * Check if the input line is clear (no user-typed text after the prompt).
1885
+ * Returns true if the last visible line appears to be just a prompt.
1886
+ */
1887
+ private async isInputClear(lastLine?: string): Promise<boolean> {
1888
+ try {
1889
+ const lineToCheck = lastLine ?? await this.getLastLine();
1890
+ const cleanLine = stripAnsi(lineToCheck).trimEnd();
1891
+ const isClear = this.getPromptPattern().test(cleanLine);
1892
+
1893
+ if (this.config.debug) {
1894
+ const truncatedLine = cleanLine.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, cleanLine.length));
1895
+ this.logStderr(`isInputClear: lastLine="${truncatedLine}", clear=${isClear}`);
1896
+ }
1897
+
1898
+ return isClear;
1899
+ } catch {
1900
+ // If we can't capture, assume not clear (safer)
1901
+ return false;
1902
+ }
1903
+ }
1904
+
1905
+ /**
1906
+ * Get cursor X position to detect input length.
1907
+ * Returns the cursor column (0-indexed).
1908
+ */
1909
+ private async getCursorX(): Promise<number> {
1910
+ try {
1911
+ const { stdout } = await execAsync(
1912
+ `"${this.tmuxPath}" display-message -t ${this.sessionName} -p "#{cursor_x}" 2>/dev/null`
1913
+ );
1914
+ return parseInt(stdout.trim(), 10) || 0;
1915
+ } catch {
1916
+ return 0;
1917
+ }
1918
+ }
1919
+
1920
+ /**
1921
+ * Wait for the input line to be clear before injecting.
1922
+ * Polls until the input appears empty or timeout is reached.
1923
+ *
1924
+ * @param maxWaitMs Maximum time to wait (default 5000ms)
1925
+ * @param pollIntervalMs How often to check (default 200ms)
1926
+ * @returns true if input became clear, false if timed out
1927
+ */
1928
+ private async waitForClearInput(maxWaitMs = 5000, pollIntervalMs = 200): Promise<boolean> {
1929
+ const startTime = Date.now();
1930
+ let lastCursorX = -1;
1931
+ let stableCursorCount = 0;
1932
+
1933
+ while (Date.now() - startTime < maxWaitMs) {
1934
+ const lastLine = await this.getLastLine();
1935
+
1936
+ // Check if input line is just a prompt
1937
+ if (await this.isInputClear(lastLine)) {
1938
+ return true;
1939
+ }
1940
+
1941
+ const hasInput = this.hasVisibleInput(lastLine);
1942
+
1943
+ // Also check cursor stability - if cursor is moving, agent is typing
1944
+ const cursorX = await this.getCursorX();
1945
+ if (!hasInput && cursorX === lastCursorX) {
1946
+ stableCursorCount++;
1947
+ // If cursor has been stable for enough polls and at typical prompt position,
1948
+ // the agent might be done but we just can't match the prompt pattern
1949
+ if (stableCursorCount >= STABLE_CURSOR_THRESHOLD && cursorX <= MAX_PROMPT_CURSOR_POSITION) {
1950
+ this.logStderr(`waitForClearInput: cursor stable at x=${cursorX}, assuming clear`);
1951
+ return true;
1952
+ }
1953
+ } else {
1954
+ stableCursorCount = 0;
1955
+ lastCursorX = cursorX;
1956
+ }
1957
+
1958
+ await sleep(pollIntervalMs);
1959
+ }
1960
+
1961
+ this.logStderr(`waitForClearInput: timed out after ${maxWaitMs}ms`);
1962
+ return false;
1963
+ }
1964
+
1965
+ /**
1966
+ * Capture a signature of the current pane content for stability checks.
1967
+ * Uses hash+length to cheaply detect changes without storing full content.
1968
+ */
1969
+ private async capturePaneSignature(): Promise<string | null> {
1970
+ try {
1971
+ const { stdout } = await execAsync(
1972
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J -S - 2>/dev/null`
1973
+ );
1974
+ const hash = crypto.createHash('sha1').update(stdout).digest('hex');
1975
+ return `${stdout.length}:${hash}`;
1976
+ } catch {
1977
+ return null;
1978
+ }
1979
+ }
1980
+
1981
+ /**
1982
+ * Wait for pane output to stabilize before injecting to avoid interleaving with ongoing output.
1983
+ * Uses adaptive timeout based on idle detector confidence for faster injection when safe.
1984
+ *
1985
+ * @param maxWaitMs - Maximum time to wait (default from config)
1986
+ * @param pollIntervalMs - Polling interval (default from config)
1987
+ * @param requiredStablePolls - Consecutive stable polls needed (default 2)
1988
+ * @param priority - Message priority (lower = more urgent, can use shorter timeout)
1989
+ */
1990
+ private async waitForStablePane(
1991
+ maxWaitMs = 800,
1992
+ pollIntervalMs = 150,
1993
+ requiredStablePolls = 2,
1994
+ priority?: number
1995
+ ): Promise<boolean> {
1996
+ const start = Date.now();
1997
+
1998
+ // Adaptive timeout based on idle confidence and priority
1999
+ // If idle detector shows high confidence (process state), we can be more aggressive
2000
+ const idleResult = this.checkIdleForInjection();
2001
+ const highConfidence = idleResult.confidence >= 0.9;
2002
+
2003
+ // Priority-based timeout adjustment (urgent messages get shorter timeout)
2004
+ let effectiveMaxWait = maxWaitMs;
2005
+ if (priority !== undefined && priority <= 1) {
2006
+ // Urgent/high priority: reduce timeout by 50%
2007
+ effectiveMaxWait = Math.min(maxWaitMs, highConfidence ? 200 : 400);
2008
+ } else if (highConfidence) {
2009
+ // High confidence from process state: reduce timeout by 60%
2010
+ effectiveMaxWait = Math.floor(maxWaitMs * 0.4);
2011
+ }
2012
+
2013
+ let lastSig = await this.capturePaneSignature();
2014
+ if (!lastSig) return false;
2015
+
2016
+ let stableCount = 0;
2017
+
2018
+ // Fast initial check - if already stable, exit quickly
2019
+ await sleep(Math.min(pollIntervalMs, 50));
2020
+ const initialSig = await this.capturePaneSignature();
2021
+ if (initialSig && initialSig === lastSig) {
2022
+ stableCount = 1;
2023
+ // If high confidence and initial check stable, we're good
2024
+ if (highConfidence && stableCount >= 1) {
2025
+ this.logStderr(`waitForStablePane: fast exit (high confidence, ${Date.now() - start}ms)`);
2026
+ return true;
2027
+ }
2028
+ } else if (initialSig) {
2029
+ lastSig = initialSig;
2030
+ }
2031
+
2032
+ while (Date.now() - start < effectiveMaxWait) {
2033
+ await sleep(pollIntervalMs);
2034
+ const sig = await this.capturePaneSignature();
2035
+ if (!sig) continue;
2036
+
2037
+ if (sig === lastSig) {
2038
+ stableCount++;
2039
+ if (stableCount >= requiredStablePolls) {
2040
+ this.logStderr(`waitForStablePane: stable after ${Date.now() - start}ms`);
2041
+ return true;
2042
+ }
2043
+ } else {
2044
+ stableCount = 0;
2045
+ lastSig = sig;
2046
+ }
2047
+ }
2048
+
2049
+ // Even on timeout, if we had at least 1 stable poll and high confidence, proceed
2050
+ if (stableCount >= 1 && highConfidence) {
2051
+ this.logStderr(`waitForStablePane: proceeding with partial stability (high confidence)`);
2052
+ return true;
2053
+ }
2054
+
2055
+ this.logStderr(`waitForStablePane: timed out after ${Date.now() - start}ms`);
2056
+ return false;
2057
+ }
2058
+
2059
+ /**
2060
+ * Stop and cleanup
2061
+ */
2062
+ stop(): void {
2063
+ if (!this.running) return;
2064
+ this.running = false;
2065
+ this.activityState = 'disconnected';
2066
+ this.stopStuckDetection();
2067
+
2068
+ // Auto-save continuity state before shutdown (fire and forget)
2069
+ // Pass sessionEndData to populate handoff (fixes empty handoff issue)
2070
+ if (this.continuity) {
2071
+ this.continuity.autoSave(this.config.name, 'session_end', this.sessionEndData).catch((err) => {
2072
+ this.logStderr(`[CONTINUITY] Auto-save failed: ${err.message}`, true);
2073
+ });
2074
+ }
2075
+
2076
+ // Reset session state for potential reuse
2077
+ this.resetSessionState();
2078
+
2079
+ // Stop polling
2080
+ if (this.pollTimer) {
2081
+ clearInterval(this.pollTimer);
2082
+ this.pollTimer = undefined;
2083
+ }
2084
+
2085
+ // Kill tmux session
2086
+ try {
2087
+ execSync(`"${this.tmuxPath}" kill-session -t ${this.sessionName} 2>/dev/null`);
2088
+ } catch {
2089
+ // Ignore
2090
+ }
2091
+
2092
+ // Disconnect relay
2093
+ this.client.destroy();
2094
+ }
2095
+ }