agent-relay 17.2.1 → 18.1.0

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 (251) hide show
  1. package/README.md +74 -266
  2. package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
  3. package/dist/cli/agent-relay-mcp.js +6 -5
  4. package/dist/cli/agent-relay-mcp.js.map +1 -1
  5. package/dist/cli/bootstrap.d.ts +1 -1
  6. package/dist/cli/bootstrap.d.ts.map +1 -1
  7. package/dist/cli/bootstrap.js +11 -29
  8. package/dist/cli/bootstrap.js.map +1 -1
  9. package/dist/cli/commands/agent.d.ts.map +1 -1
  10. package/dist/cli/commands/agent.js +3 -2
  11. package/dist/cli/commands/agent.js.map +1 -1
  12. package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
  13. package/dist/cli/commands/cloud-integration.js +2 -1
  14. package/dist/cli/commands/cloud-integration.js.map +1 -1
  15. package/dist/cli/commands/cloud-room.d.ts.map +1 -1
  16. package/dist/cli/commands/cloud-room.js +2 -1
  17. package/dist/cli/commands/cloud-room.js.map +1 -1
  18. package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
  19. package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
  20. package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
  21. package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
  22. package/dist/cli/commands/cloud-worker.d.ts +6 -2
  23. package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
  24. package/dist/cli/commands/cloud-worker.js +74 -37
  25. package/dist/cli/commands/cloud-worker.js.map +1 -1
  26. package/dist/cli/commands/cloud.d.ts.map +1 -1
  27. package/dist/cli/commands/cloud.js +20 -18
  28. package/dist/cli/commands/cloud.js.map +1 -1
  29. package/dist/cli/commands/core.d.ts +3 -91
  30. package/dist/cli/commands/core.d.ts.map +1 -1
  31. package/dist/cli/commands/core.js +5 -254
  32. package/dist/cli/commands/core.js.map +1 -1
  33. package/dist/cli/commands/fleet-agent.d.ts +9 -54
  34. package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
  35. package/dist/cli/commands/fleet-agent.js +105 -314
  36. package/dist/cli/commands/fleet-agent.js.map +1 -1
  37. package/dist/cli/commands/fleet.d.ts +0 -3
  38. package/dist/cli/commands/fleet.d.ts.map +1 -1
  39. package/dist/cli/commands/fleet.js +48 -267
  40. package/dist/cli/commands/fleet.js.map +1 -1
  41. package/dist/cli/commands/init.js +1 -1
  42. package/dist/cli/commands/init.js.map +1 -1
  43. package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
  44. package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
  45. package/dist/cli/commands/integration-cleanup-journal.js +611 -134
  46. package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
  47. package/dist/cli/commands/integration-recipient.d.ts +0 -17
  48. package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
  49. package/dist/cli/commands/integration-recipient.js +1 -104
  50. package/dist/cli/commands/integration-recipient.js.map +1 -1
  51. package/dist/cli/commands/integration.d.ts +7 -3
  52. package/dist/cli/commands/integration.d.ts.map +1 -1
  53. package/dist/cli/commands/integration.js +37 -82
  54. package/dist/cli/commands/integration.js.map +1 -1
  55. package/dist/cli/commands/local-workflow.d.ts +1 -1
  56. package/dist/cli/commands/local-workflow.d.ts.map +1 -1
  57. package/dist/cli/commands/local-workflow.js +20 -6
  58. package/dist/cli/commands/local-workflow.js.map +1 -1
  59. package/dist/cli/commands/node.d.ts +18 -20
  60. package/dist/cli/commands/node.d.ts.map +1 -1
  61. package/dist/cli/commands/node.js +42 -272
  62. package/dist/cli/commands/node.js.map +1 -1
  63. package/dist/cli/commands/product-surfaces.js +2 -2
  64. package/dist/cli/commands/session.d.ts.map +1 -1
  65. package/dist/cli/commands/session.js +2 -1
  66. package/dist/cli/commands/session.js.map +1 -1
  67. package/dist/cli/commands/skills.d.ts.map +1 -1
  68. package/dist/cli/commands/skills.js +2 -1
  69. package/dist/cli/commands/skills.js.map +1 -1
  70. package/dist/cli/commands/status.d.ts +1 -7
  71. package/dist/cli/commands/status.d.ts.map +1 -1
  72. package/dist/cli/commands/status.js +2 -28
  73. package/dist/cli/commands/status.js.map +1 -1
  74. package/dist/cli/commands/workspace.d.ts.map +1 -1
  75. package/dist/cli/commands/workspace.js +2 -2
  76. package/dist/cli/commands/workspace.js.map +1 -1
  77. package/dist/cli/index.d.ts.map +1 -1
  78. package/dist/cli/index.js +1 -3
  79. package/dist/cli/index.js.map +1 -1
  80. package/dist/cli/lib/agent-relay-cli-reentry.d.ts +40 -0
  81. package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
  82. package/dist/cli/lib/agent-relay-cli-reentry.js +47 -0
  83. package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
  84. package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
  85. package/dist/cli/lib/agent-tools-mcp.js +3 -2
  86. package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
  87. package/dist/cli/lib/cloud-worker-authored-runtime.d.ts +3 -0
  88. package/dist/cli/lib/cloud-worker-authored-runtime.d.ts.map +1 -0
  89. package/dist/cli/lib/cloud-worker-authored-runtime.js +67 -0
  90. package/dist/cli/lib/cloud-worker-authored-runtime.js.map +1 -0
  91. package/dist/cli/lib/cloud-worker-enrollment-token.d.ts +13 -0
  92. package/dist/cli/lib/cloud-worker-enrollment-token.d.ts.map +1 -0
  93. package/dist/cli/lib/cloud-worker-enrollment-token.js +88 -0
  94. package/dist/cli/lib/cloud-worker-enrollment-token.js.map +1 -0
  95. package/dist/cli/lib/core-maintenance.d.ts +2 -3
  96. package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
  97. package/dist/cli/lib/core-maintenance.js +3 -37
  98. package/dist/cli/lib/core-maintenance.js.map +1 -1
  99. package/dist/cli/lib/desktop-presence.js +1 -1
  100. package/dist/cli/lib/desktop-presence.js.map +1 -1
  101. package/dist/cli/lib/install-paths.d.ts +100 -0
  102. package/dist/cli/lib/install-paths.d.ts.map +1 -0
  103. package/dist/cli/lib/install-paths.js +157 -0
  104. package/dist/cli/lib/install-paths.js.map +1 -0
  105. package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
  106. package/dist/cli/lib/product-surface-store.js +4 -1
  107. package/dist/cli/lib/product-surface-store.js.map +1 -1
  108. package/dist/cli/lib/relay-node.d.ts +7 -34
  109. package/dist/cli/lib/relay-node.d.ts.map +1 -1
  110. package/dist/cli/lib/relay-node.js +7 -182
  111. package/dist/cli/lib/relay-node.js.map +1 -1
  112. package/dist/cli/lib/removed-broker-command.d.ts +7 -0
  113. package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
  114. package/dist/cli/lib/removed-broker-command.js +13 -0
  115. package/dist/cli/lib/removed-broker-command.js.map +1 -0
  116. package/dist/cli/lib/sdk-client.d.ts +4 -4
  117. package/dist/cli/lib/sdk-client.js +4 -4
  118. package/dist/cli/lib/self-update.d.ts +8 -19
  119. package/dist/cli/lib/self-update.d.ts.map +1 -1
  120. package/dist/cli/lib/self-update.js +14 -28
  121. package/dist/cli/lib/self-update.js.map +1 -1
  122. package/dist/cli/lib/skills-install.d.ts.map +1 -1
  123. package/dist/cli/lib/skills-install.js +3 -2
  124. package/dist/cli/lib/skills-install.js.map +1 -1
  125. package/dist/cli/telemetry/events.d.ts +4 -1
  126. package/dist/cli/telemetry/events.d.ts.map +1 -1
  127. package/package.json +9 -14
  128. package/dist/auto/classifier.d.ts +0 -29
  129. package/dist/auto/classifier.d.ts.map +0 -1
  130. package/dist/auto/classifier.js +0 -126
  131. package/dist/auto/classifier.js.map +0 -1
  132. package/dist/auto/composer.d.ts +0 -105
  133. package/dist/auto/composer.d.ts.map +0 -1
  134. package/dist/auto/composer.js +0 -454
  135. package/dist/auto/composer.js.map +0 -1
  136. package/dist/auto/director-prompt.d.ts +0 -25
  137. package/dist/auto/director-prompt.d.ts.map +0 -1
  138. package/dist/auto/director-prompt.js +0 -53
  139. package/dist/auto/director-prompt.js.map +0 -1
  140. package/dist/auto/index.d.ts +0 -15
  141. package/dist/auto/index.d.ts.map +0 -1
  142. package/dist/auto/index.js +0 -13
  143. package/dist/auto/index.js.map +0 -1
  144. package/dist/cli/commands/local-agent.d.ts +0 -74
  145. package/dist/cli/commands/local-agent.d.ts.map +0 -1
  146. package/dist/cli/commands/local-agent.js +0 -969
  147. package/dist/cli/commands/local-agent.js.map +0 -1
  148. package/dist/cli/lib/attach-broker.d.ts +0 -17
  149. package/dist/cli/lib/attach-broker.d.ts.map +0 -1
  150. package/dist/cli/lib/attach-broker.js +0 -27
  151. package/dist/cli/lib/attach-broker.js.map +0 -1
  152. package/dist/cli/lib/attach-drive.d.ts +0 -376
  153. package/dist/cli/lib/attach-drive.d.ts.map +0 -1
  154. package/dist/cli/lib/attach-drive.js +0 -1212
  155. package/dist/cli/lib/attach-drive.js.map +0 -1
  156. package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
  157. package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
  158. package/dist/cli/lib/attach-fleet-node.js +0 -1347
  159. package/dist/cli/lib/attach-fleet-node.js.map +0 -1
  160. package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
  161. package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
  162. package/dist/cli/lib/attach-input-recovery.js +0 -559
  163. package/dist/cli/lib/attach-input-recovery.js.map +0 -1
  164. package/dist/cli/lib/attach-mode.d.ts +0 -2
  165. package/dist/cli/lib/attach-mode.d.ts.map +0 -1
  166. package/dist/cli/lib/attach-mode.js +0 -2
  167. package/dist/cli/lib/attach-mode.js.map +0 -1
  168. package/dist/cli/lib/attach-native.d.ts +0 -27
  169. package/dist/cli/lib/attach-native.d.ts.map +0 -1
  170. package/dist/cli/lib/attach-native.js +0 -267
  171. package/dist/cli/lib/attach-native.js.map +0 -1
  172. package/dist/cli/lib/attach-passthrough.d.ts +0 -193
  173. package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
  174. package/dist/cli/lib/attach-passthrough.js +0 -778
  175. package/dist/cli/lib/attach-passthrough.js.map +0 -1
  176. package/dist/cli/lib/attach-remote-node.d.ts +0 -21
  177. package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
  178. package/dist/cli/lib/attach-remote-node.js +0 -133
  179. package/dist/cli/lib/attach-remote-node.js.map +0 -1
  180. package/dist/cli/lib/attach-view.d.ts +0 -177
  181. package/dist/cli/lib/attach-view.d.ts.map +0 -1
  182. package/dist/cli/lib/attach-view.js +0 -455
  183. package/dist/cli/lib/attach-view.js.map +0 -1
  184. package/dist/cli/lib/attach.d.ts +0 -555
  185. package/dist/cli/lib/attach.d.ts.map +0 -1
  186. package/dist/cli/lib/attach.js +0 -1180
  187. package/dist/cli/lib/attach.js.map +0 -1
  188. package/dist/cli/lib/broker-connection.d.ts +0 -65
  189. package/dist/cli/lib/broker-connection.d.ts.map +0 -1
  190. package/dist/cli/lib/broker-connection.js +0 -144
  191. package/dist/cli/lib/broker-connection.js.map +0 -1
  192. package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
  193. package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
  194. package/dist/cli/lib/broker-lifecycle.js +0 -2290
  195. package/dist/cli/lib/broker-lifecycle.js.map +0 -1
  196. package/dist/cli/lib/broker-process-identity.d.ts +0 -38
  197. package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
  198. package/dist/cli/lib/broker-process-identity.js +0 -304
  199. package/dist/cli/lib/broker-process-identity.js.map +0 -1
  200. package/dist/cli/lib/client-factory.d.ts +0 -44
  201. package/dist/cli/lib/client-factory.d.ts.map +0 -1
  202. package/dist/cli/lib/client-factory.js +0 -64
  203. package/dist/cli/lib/client-factory.js.map +0 -1
  204. package/dist/cli/lib/collect-with-retry.d.ts +0 -24
  205. package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
  206. package/dist/cli/lib/collect-with-retry.js +0 -33
  207. package/dist/cli/lib/collect-with-retry.js.map +0 -1
  208. package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
  209. package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
  210. package/dist/cli/lib/fleet-attach-target.js +0 -57
  211. package/dist/cli/lib/fleet-attach-target.js.map +0 -1
  212. package/dist/cli/lib/fleet-hint.d.ts +0 -49
  213. package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
  214. package/dist/cli/lib/fleet-hint.js +0 -113
  215. package/dist/cli/lib/fleet-hint.js.map +0 -1
  216. package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
  217. package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
  218. package/dist/cli/lib/fleet-sidecar.js +0 -84
  219. package/dist/cli/lib/fleet-sidecar.js.map +0 -1
  220. package/dist/cli/lib/join-ticket.d.ts +0 -22
  221. package/dist/cli/lib/join-ticket.d.ts.map +0 -1
  222. package/dist/cli/lib/join-ticket.js +0 -96
  223. package/dist/cli/lib/join-ticket.js.map +0 -1
  224. package/dist/cli/lib/node-claim.d.ts +0 -468
  225. package/dist/cli/lib/node-claim.d.ts.map +0 -1
  226. package/dist/cli/lib/node-claim.js +0 -1349
  227. package/dist/cli/lib/node-claim.js.map +0 -1
  228. package/dist/cli/lib/node-definition-loader.d.ts +0 -19
  229. package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
  230. package/dist/cli/lib/node-definition-loader.js +0 -143
  231. package/dist/cli/lib/node-definition-loader.js.map +0 -1
  232. package/dist/cli/lib/node-provider-child.d.ts +0 -129
  233. package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
  234. package/dist/cli/lib/node-provider-child.js +0 -755
  235. package/dist/cli/lib/node-provider-child.js.map +0 -1
  236. package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
  237. package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
  238. package/dist/cli/lib/predictive-echo-screen.js +0 -74
  239. package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
  240. package/dist/cli/lib/project-broker-client.d.ts +0 -4
  241. package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
  242. package/dist/cli/lib/project-broker-client.js +0 -12
  243. package/dist/cli/lib/project-broker-client.js.map +0 -1
  244. package/dist/cli/lib/reflex-capture.d.ts +0 -41
  245. package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
  246. package/dist/cli/lib/reflex-capture.js +0 -128
  247. package/dist/cli/lib/reflex-capture.js.map +0 -1
  248. package/dist/cli/lib/workspace-env.d.ts +0 -8
  249. package/dist/cli/lib/workspace-env.d.ts.map +0 -1
  250. package/dist/cli/lib/workspace-env.js +0 -16
  251. package/dist/cli/lib/workspace-env.js.map +0 -1
@@ -1,969 +0,0 @@
1
- import { readTaskInput, validateTaskSize } from '../lib/task-input.js';
2
- import { AGENT37_RELAYCAST_ORIGIN } from '@agent-relay/cloud';
3
- import { findProjectRoot } from '@agent-relay/config';
4
- import { stripAnsiFast } from '@agent-relay/utils';
5
- import { classifyTask, composeTeam, buildDirectorPrompt } from '../../auto/index.js';
6
- import { createBrokerClient } from '../lib/attach-broker.js';
7
- import { attachDrive } from '../lib/attach-drive.js';
8
- import { attachNative, isNativeHarness } from '../lib/attach-native.js';
9
- import { attachPassthrough } from '../lib/attach-passthrough.js';
10
- import { attachRemoteNode } from '../lib/attach-remote-node.js';
11
- import { startFleetNodeAttachProxy, validateFleetAttachBaseUrl } from '../lib/attach-fleet-node.js';
12
- import { attachView } from '../lib/attach-view.js';
13
- import { createBackpressureAwareWriter } from '../lib/attach.js';
14
- import { defaultStateDir, describeMissingBrokerConnection, readConnectionFileFromDisk, resolveBrokerConnection, } from '../lib/broker-connection.js';
15
- import { resolvedSpawnRuntime, spawnAgentWithClient } from '../lib/client-factory.js';
16
- import { connectProjectBrokerClient } from '../lib/project-broker-client.js';
17
- import { describeError } from '../lib/describe-error.js';
18
- import { defaultExit } from '../lib/exit.js';
19
- import { resolveFleetAttachTarget } from '../lib/fleet-attach-target.js';
20
- import { redeemJoinTicket } from '../lib/join-ticket.js';
21
- import { describeClearedEnrollment, persistWorkspaceSession } from '../lib/workspace-session.js';
22
- // ── Auto-routing model resolution ─────────────────────────────────────────────
23
- // Maps the routing tier to a concrete Claude model ID.
24
- const CLAUDE_MODEL_IDS = {
25
- haiku: 'claude-haiku-4-5-20251001',
26
- sonnet: 'claude-sonnet-4-6',
27
- opus: 'claude-opus-4-8',
28
- };
29
- /**
30
- * If `model === 'auto'`, run the task classifier → team composer → Director
31
- * meta-prompt builder and return resolved spawn options.
32
- *
33
- * Only applies to the 'claude' provider — other CLIs use model=auto as a
34
- * passthrough until their routing tables are defined.
35
- */
36
- function resolveAutoSpawn(provider, name, task, model, runtime) {
37
- if (model !== 'auto' || provider !== 'claude' || !task) {
38
- return { name, task, model };
39
- }
40
- const assessment = classifyTask(task);
41
- const team = composeTeam(assessment, task);
42
- const directorPrompt = buildDirectorPrompt(task, team);
43
- // The Director prompt repeats the task, so it is what must fit.
44
- validateTaskSize(directorPrompt, { cli: provider, runtime });
45
- return {
46
- name: name === provider ? 'Director' : name,
47
- task: directorPrompt,
48
- model: CLAUDE_MODEL_IDS[team.lead.model],
49
- };
50
- }
51
- /** Dispatch `local agent attach --mode` to the drive/view/passthrough session runners. */
52
- export function runAttach(name, mode, options) {
53
- return isNativeHarness(name, options).then((nativeHarness) => {
54
- if (nativeHarness)
55
- return attachNative(name, mode, options);
56
- switch (mode) {
57
- case 'view':
58
- return attachView(name, options);
59
- case 'passthrough':
60
- return attachPassthrough(name, options);
61
- case 'drive':
62
- default:
63
- return attachDrive(name, options);
64
- }
65
- });
66
- }
67
- /**
68
- * Run an existing attach mode against the short-lived loopback adapter for a
69
- * remote fleet node. Deliberately bypasses native-harness detection: the proxy
70
- * represents a PTY byte stream, while native mode is an event protocol.
71
- */
72
- export async function attachFleetNode(name, mode, node, options) {
73
- const proxy = await startFleetNodeAttachProxy({
74
- agent: name,
75
- node,
76
- mode,
77
- ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),
78
- ...(options.workspaceKey === undefined ? {} : { workspaceKey: options.workspaceKey }),
79
- });
80
- const jsonWriter = options.json ? createBackpressureAwareWriter(process.stdout) : undefined;
81
- try {
82
- const connectionOptions = {
83
- brokerUrl: proxy.brokerUrl,
84
- apiKey: proxy.apiKey,
85
- requestTimeoutMs: proxy.requestTimeoutMs,
86
- };
87
- // Fleet agents expose a PTY stream rather than native-harness envelopes.
88
- // In JSON mode retain the machine-readable contract by serializing every
89
- // rendered stream chunk as NDJSON, including the initial snapshot.
90
- const jsonOutput = (chunk) => {
91
- jsonWriter?.write(`${JSON.stringify({ kind: 'worker_stream', name, stream: 'stdout', chunk })}\n`);
92
- };
93
- if (options.reasoning || options.diagnostics) {
94
- process.stderr.write('[node attach] reasoning and diagnostics are unavailable for remote PTY terminal sessions.\n');
95
- }
96
- switch (mode) {
97
- case 'view':
98
- return await attachView(name, connectionOptions, options.json ? { writeChunk: jsonOutput, stdoutIsTty: false } : {});
99
- case 'passthrough':
100
- return await attachPassthrough(name, connectionOptions, options.json
101
- ? {
102
- writeChunk: jsonOutput,
103
- // JSON mode is a non-terminal stream. Suppressing the local
104
- // status line and reset controls keeps only worker bytes in
105
- // the NDJSON records, matching SSH's no-TTY JSON behaviour.
106
- terminal: { getSize: () => null, onResize: () => () => undefined },
107
- }
108
- : {});
109
- case 'drive':
110
- default:
111
- return await attachDrive(name, connectionOptions, options.json
112
- ? {
113
- writeChunk: jsonOutput,
114
- terminal: { getSize: () => null, onResize: () => () => undefined },
115
- }
116
- : {});
117
- }
118
- }
119
- finally {
120
- // NDJSON is a data contract, unlike an interactive screen: queue every
121
- // locally buffered record before teardown so the shared CLI stdio drain
122
- // can carry it through a backpressured pipe.
123
- jsonWriter?.flush();
124
- jsonWriter?.dispose();
125
- await proxy.close();
126
- }
127
- }
128
- function withDefaults(overrides = {}) {
129
- const deps = {
130
- connect: async (cwd) => {
131
- try {
132
- return connectProjectBrokerClient(findProjectRoot(cwd));
133
- }
134
- catch (err) {
135
- const message = err instanceof Error ? err.message : String(err);
136
- if (!message.startsWith('No running broker found'))
137
- throw err;
138
- // The project file is only the default; a broker started with
139
- // --state-dir is alive elsewhere. Say so instead of implying it is down.
140
- throw new Error(`${message}\nThat is the project default location. If the broker was started with --state-dir, ` +
141
- 'pass the same --state-dir here (or --broker-url / RELAY_BROKER_URL).');
142
- }
143
- },
144
- cwd: () => process.cwd(),
145
- readConnectionFile: readConnectionFileFromDisk,
146
- getDefaultStateDir: defaultStateDir,
147
- env: process.env,
148
- fetch: globalThis.fetch,
149
- redeemJoinTicket,
150
- persistWorkspaceSession,
151
- attach: runAttach,
152
- attachRemote: attachRemoteNode,
153
- attachNode: attachFleetNode,
154
- resolveFleetAttachTarget,
155
- log: (...args) => console.log(...args),
156
- error: (...args) => console.error(...args),
157
- exit: defaultExit,
158
- now: () => new Date(),
159
- ...overrides,
160
- };
161
- deps.connectLocal ??= async (_cwd, options) => {
162
- const connection = resolveBrokerConnection(options, {
163
- readConnectionFile: deps.readConnectionFile,
164
- getDefaultStateDir: deps.getDefaultStateDir,
165
- env: deps.env,
166
- });
167
- if (!connection) {
168
- throw new Error(describeMissingBrokerConnection(options, deps));
169
- }
170
- return createBrokerClient(connection, deps.fetch);
171
- };
172
- return deps;
173
- }
174
- function resolveAttachCredentialSelection(rawWorkspaceKey, rawJoinTicket, node, sshHost) {
175
- const workspaceKey = rawWorkspaceKey?.trim() || undefined;
176
- const joinTicket = rawJoinTicket?.trim() || undefined;
177
- if (rawWorkspaceKey !== undefined && rawJoinTicket !== undefined) {
178
- return { ok: false, error: 'Error: --join-ticket cannot be combined with --workspace-key.' };
179
- }
180
- if (rawJoinTicket !== undefined && !joinTicket) {
181
- return { ok: false, error: 'Error: --join-ticket requires a non-empty ticket.' };
182
- }
183
- if (rawWorkspaceKey !== undefined && node === undefined) {
184
- return {
185
- ok: false,
186
- error: sshHost !== undefined
187
- ? 'Error: --workspace-key requires --node. The --ssh-host attach path reads the target broker connection.json — locate it with --state-dir instead.'
188
- : 'Error: --workspace-key requires --node. The local attach path uses --broker-url / --api-key or reads connection.json from --state-dir instead.',
189
- };
190
- }
191
- if (rawJoinTicket !== undefined && node === undefined) {
192
- return {
193
- ok: false,
194
- error: sshHost !== undefined
195
- ? 'Error: --join-ticket requires --node. The --ssh-host attach path reads the target broker connection.json — locate it with --state-dir instead.'
196
- : 'Error: --join-ticket requires --node. The local attach path uses --broker-url / --api-key or reads connection.json from --state-dir instead.',
197
- };
198
- }
199
- return { ok: true, workspaceKey, joinTicket };
200
- }
201
- async function redeemAndPersistAttachCredential(deps, options) {
202
- const redeemed = await deps.redeemJoinTicket({
203
- ticket: options.ticket,
204
- node: options.node,
205
- agent: options.agent,
206
- mode: options.mode,
207
- ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),
208
- env: deps.env,
209
- fetch: deps.fetch,
210
- });
211
- const persisted = deps.persistWorkspaceSession({
212
- workspaceKey: redeemed.workspaceKey,
213
- workspaceId: redeemed.workspaceId,
214
- ...(options.baseUrl
215
- ? {
216
- relaycastRoute: options.baseUrl === AGENT37_RELAYCAST_ORIGIN ? 'agent37-isolated' : 'canonical',
217
- relaycastBaseUrl: options.baseUrl,
218
- relaycastApiKey: redeemed.workspaceKey,
219
- }
220
- : {}),
221
- projectRoot: deps.cwd(),
222
- });
223
- const warning = describeClearedEnrollment(persisted);
224
- if (warning)
225
- deps.error(warning);
226
- return redeemed.workspaceKey;
227
- }
228
- const AGENT_STATE_DISPLAY = {
229
- working: { symbol: '●', label: 'working' },
230
- idle: { symbol: '○', label: 'idle' },
231
- blocked_on_send: { symbol: '◐', label: 'waiting' },
232
- };
233
- function formatRelativeTime(value, now) {
234
- if (!value)
235
- return 'unknown';
236
- const timestamp = Date.parse(value);
237
- if (Number.isNaN(timestamp))
238
- return 'unknown';
239
- const seconds = Math.max(0, Math.floor((now.getTime() - timestamp) / 1_000));
240
- if (seconds < 5)
241
- return 'now';
242
- if (seconds < 60)
243
- return `${seconds} seconds ago`;
244
- const minutes = Math.floor(seconds / 60);
245
- if (minutes < 60)
246
- return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;
247
- const hours = Math.floor(minutes / 60);
248
- if (hours < 24)
249
- return `${hours} hour${hours === 1 ? '' : 's'} ago`;
250
- const days = Math.floor(hours / 24);
251
- return `${days} day${days === 1 ? '' : 's'} ago`;
252
- }
253
- /**
254
- * Render the count of messages still waiting to reach the agent. Brokers older
255
- * than the field report nothing, which stays `-` rather than claiming an empty
256
- * queue.
257
- */
258
- function formatPendingCount(value) {
259
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
260
- return '-';
261
- return String(Math.floor(value));
262
- }
263
- /** Keep broker-provided text from escaping its table cell or controlling the terminal. */
264
- function sanitizeTerminalCell(value) {
265
- // eslint-disable-next-line no-control-regex
266
- return stripAnsiFast(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '�');
267
- }
268
- /** Fixed-width text table shared by the plain and delivery-status pretty views. */
269
- function renderTable(columns) {
270
- const widths = columns.map((column) => Math.max(column.header.length, ...column.values.map((value) => value.length)));
271
- const formatRow = (values) => values
272
- .map((value, index) => value.padEnd(widths[index]))
273
- .join(' ')
274
- .trimEnd();
275
- const rowCount = columns[0]?.values.length ?? 0;
276
- return [
277
- formatRow(columns.map((column) => column.header)),
278
- formatRow(columns.map((_, index) => '-'.repeat(widths[index]))),
279
- ...Array.from({ length: rowCount }, (_, rowIndex) => formatRow(columns.map((column) => column.values[rowIndex]))),
280
- ].join('\n');
281
- }
282
- /** Render a compact terminal view while retaining JSON as the script-friendly default. */
283
- export function formatPrettyAgentList(agents, now) {
284
- if (agents.length === 0)
285
- return 'No agents running.';
286
- const rows = agents.map((agent) => {
287
- const state = agent.current_state ? AGENT_STATE_DISPLAY[agent.current_state] : undefined;
288
- return {
289
- name: sanitizeTerminalCell(agent.name),
290
- cliModel: sanitizeTerminalCell([agent.cli ?? agent.provider ?? agent.runtime, agent.model].filter(Boolean).join(' / ')),
291
- state: sanitizeTerminalCell(state ? `${state.symbol} ${state.label}` : '· unknown'),
292
- pending: formatPendingCount(agent.pending_messages),
293
- lastActive: sanitizeTerminalCell(formatRelativeTime(agent.last_activity_at, now)),
294
- };
295
- });
296
- return renderTable([
297
- { header: 'NAME', values: rows.map((row) => row.name) },
298
- { header: 'CLI / MODEL', values: rows.map((row) => row.cliModel) },
299
- { header: 'STATE', values: rows.map((row) => row.state) },
300
- { header: 'PENDING', values: rows.map((row) => row.pending) },
301
- { header: 'LAST ACTIVE', values: rows.map((row) => row.lastActive) },
302
- ]);
303
- }
304
- /** Four agents at once means no more than eight concurrent broker reads. */
305
- const DELIVERY_STATUS_AGENT_CONCURRENCY = 4;
306
- /** Map in input order without allowing a fleet status read to overwhelm its broker. */
307
- async function mapWithConcurrency(values, concurrency, mapper) {
308
- const results = new Array(values.length);
309
- let nextIndex = 0;
310
- async function worker() {
311
- while (true) {
312
- const index = nextIndex;
313
- nextIndex += 1;
314
- if (index >= values.length)
315
- return;
316
- results[index] = await mapper(values[index]);
317
- }
318
- }
319
- await Promise.all(Array.from({ length: Math.min(concurrency, values.length) }, () => worker()));
320
- return results;
321
- }
322
- /**
323
- * Fetch delivery mode + pending-queue contents for every listed agent. A
324
- * status read costs one `/api/spawned` call plus two calls per agent, but we
325
- * limit enrichment to four agents at once so inspecting a busy fleet cannot
326
- * turn into an unbounded broker request fan-out.
327
- */
328
- export async function withDeliveryStatus(client, agents) {
329
- return mapWithConcurrency(agents, DELIVERY_STATUS_AGENT_CONCURRENCY, async (agent) => {
330
- const [delivery_mode, pending] = await Promise.all([
331
- client.getInboundDeliveryMode(agent.name).catch(() => undefined),
332
- client.getPending(agent.name).catch(() => undefined),
333
- ]);
334
- return { ...agent, delivery_mode, pending };
335
- });
336
- }
337
- /** A worker holding messages it cannot currently act on: parked in `manual_flush` with a non-empty queue. */
338
- function stuckStatus(agent) {
339
- // A failed status read is observability data, not proof that the queue is empty.
340
- if (agent.delivery_mode === undefined || agent.pending === undefined)
341
- return 'unknown';
342
- return agent.delivery_mode === 'manual_flush' && agent.pending.length > 0 ? 'yes' : 'no';
343
- }
344
- /** Render the `--status` pretty view: mode, pending depth, and the derived stuck signal, alongside last-activity. */
345
- export function formatPrettyAgentStatusList(agents, now) {
346
- if (agents.length === 0)
347
- return 'No agents running.';
348
- const rows = agents.map((agent) => ({
349
- name: sanitizeTerminalCell(agent.name),
350
- mode: sanitizeTerminalCell(agent.delivery_mode ?? 'unknown'),
351
- pending: agent.pending ? String(agent.pending.length) : '-',
352
- stuck: stuckStatus(agent),
353
- lastActive: sanitizeTerminalCell(formatRelativeTime(agent.last_activity_at, now)),
354
- }));
355
- return renderTable([
356
- { header: 'NAME', values: rows.map((row) => row.name) },
357
- { header: 'MODE', values: rows.map((row) => row.mode) },
358
- { header: 'PENDING', values: rows.map((row) => row.pending) },
359
- { header: 'STUCK', values: rows.map((row) => row.stuck) },
360
- { header: 'LAST ACTIVE', values: rows.map((row) => row.lastActive) },
361
- ]);
362
- }
363
- /**
364
- * Whether the caller chose a broker explicitly (`--broker-url` / `--api-key` /
365
- * `--state-dir`, or `RELAY_BROKER_URL` / `RELAY_BROKER_API_KEY`), matching the
366
- * selection `attach` and `message` honour. Without one, commands keep using the
367
- * enclosing project's broker.
368
- */
369
- function hasExplicitBrokerSelection(deps, options) {
370
- return Boolean(options.brokerUrl?.trim() ||
371
- options.apiKey?.trim() ||
372
- options.stateDir?.trim() ||
373
- deps.env.RELAY_BROKER_URL?.trim() ||
374
- deps.env.RELAY_BROKER_API_KEY?.trim());
375
- }
376
- async function run(deps, fn, brokerOptions = {}) {
377
- let client;
378
- try {
379
- client = hasExplicitBrokerSelection(deps, brokerOptions)
380
- ? await deps.connectLocal(deps.cwd(), brokerOptions)
381
- : await deps.connect(deps.cwd());
382
- await fn(client);
383
- }
384
- catch (err) {
385
- deps.error(err instanceof Error ? err.message : String(err));
386
- deps.exit(1);
387
- }
388
- finally {
389
- client?.disconnect?.();
390
- }
391
- }
392
- async function runLocalBroker(deps, options, fn) {
393
- try {
394
- await fn(await deps.connectLocal(deps.cwd(), options));
395
- }
396
- catch (err) {
397
- deps.error(err instanceof Error ? err.message : String(err));
398
- deps.exit(1);
399
- }
400
- }
401
- function addBrokerOptions(command) {
402
- return command
403
- .option('--broker-url <url>', 'Broker base URL (overrides RELAY_BROKER_URL and connection.json)')
404
- .option('--api-key <key>', 'Broker API key (overrides RELAY_BROKER_API_KEY and connection.json)')
405
- .option('--state-dir <dir>', 'Directory containing connection.json (default: .agentworkforce/relay/)');
406
- }
407
- function brokerOptionsFromOpts(opts) {
408
- return {
409
- brokerUrl: opts.brokerUrl,
410
- apiKey: opts.apiKey,
411
- stateDir: opts.stateDir,
412
- };
413
- }
414
- /** Bounded liveness probe so a stale `connection.json` cannot mask a real Fleet placement. */
415
- const LOCAL_BROKER_LIVENESS_TIMEOUT_MS = 750;
416
- /**
417
- * Whether a flag-free `attach`/`message flush|hold|auto` should skip fleet
418
- * auto-routing and go straight to the local broker.
419
- *
420
- * Originally checked only explicit `--broker-url` / `--api-key` / `--state-dir`
421
- * / env overrides — never whether `connection.json` itself auto-discovers. A
422
- * project with *both* a local broker and persisted Relaycast workspace
423
- * credentials (the common case: those credentials are needed for ordinary
424
- * local messaging, not just fleet routing) would skip straight past a
425
- * perfectly usable local broker into `resolveFleetAttachTarget`, which then
426
- * hard-errored with "has no live Fleet placement on the persisted remote
427
- * session" for every plain local PTY worker — the fleet lookup finding zero
428
- * matches is the *expected* case for a local-only agent, not a failure.
429
- *
430
- * The comment on this function's callers already states the intended
431
- * design — fleet lookup exists for "a sandbox worker has no local broker",
432
- * falling back to the local connection contract otherwise. Actually
433
- * resolving that local contract (not just checking for explicit flags) is
434
- * what makes the fallback real instead of aspirational.
435
- *
436
- * An explicit `--broker-url` / `--api-key` / `--state-dir` / env override is
437
- * trusted at face value, same as every other command in this file — the
438
- * caller named that broker on purpose, so no probe gates it. Only the
439
- * *auto-discovered* `connection.json` path is probed: after a broker crash
440
- * that left a stale file behind, treating it as "live" would route a
441
- * flag-free command to a dead local port instead of the Fleet placement that
442
- * might actually have the agent — a worse failure than the one this
443
- * function was written to fix. Bounded to
444
- * `LOCAL_BROKER_LIVENESS_TIMEOUT_MS` so a hung port cannot stall every
445
- * flag-free attach/message command.
446
- */
447
- async function hasLocalBrokerSelection(deps, opts) {
448
- if (opts.brokerUrl !== undefined ||
449
- opts.apiKey !== undefined ||
450
- opts.stateDir !== undefined ||
451
- deps.env.RELAY_BROKER_URL?.trim() ||
452
- deps.env.RELAY_BROKER_API_KEY?.trim()) {
453
- return true;
454
- }
455
- const connection = resolveBrokerConnection(brokerOptionsFromOpts(opts), {
456
- readConnectionFile: deps.readConnectionFile,
457
- getDefaultStateDir: deps.getDefaultStateDir,
458
- env: deps.env,
459
- });
460
- if (!connection)
461
- return false;
462
- const controller = new AbortController();
463
- const timeout = setTimeout(() => controller.abort(), LOCAL_BROKER_LIVENESS_TIMEOUT_MS);
464
- try {
465
- const response = await deps.fetch(`${connection.url}/health`, { signal: controller.signal });
466
- return response.ok;
467
- }
468
- catch {
469
- // Unreachable, timed out, or refused: the file is stale. Let the caller
470
- // fall through to Fleet routing rather than claiming a dead local broker.
471
- return false;
472
- }
473
- finally {
474
- clearTimeout(timeout);
475
- }
476
- }
477
- function parseRuntimeOption(deps, value) {
478
- const runtime = (value ?? 'auto');
479
- if (runtime === 'auto' || runtime === 'native' || runtime === 'pty')
480
- return runtime;
481
- deps.error(`Unknown runtime "${runtime}". Expected one of: auto, native, pty.`);
482
- deps.exit(1);
483
- return undefined;
484
- }
485
- function resolveRuntimeOption(deps, provider, value) {
486
- const requested = parseRuntimeOption(deps, value);
487
- if (!requested)
488
- return undefined;
489
- try {
490
- return { requested, selected: resolvedSpawnRuntime({ cli: provider, runtime: requested }) };
491
- }
492
- catch (error) {
493
- deps.error(error instanceof Error ? error.message : String(error));
494
- deps.exit(1);
495
- return undefined;
496
- }
497
- }
498
- function parseSpawnModeOption(deps, value) {
499
- const spawnMode = (value ?? 'interactive');
500
- if (spawnMode === 'interactive')
501
- return 'interactive';
502
- if (spawnMode === 'task-exit' || spawnMode === 'task_exit')
503
- return 'task_exit';
504
- deps.error(`Unknown spawn mode "${spawnMode}". Expected one of: interactive, task-exit.`);
505
- deps.exit(1);
506
- return undefined;
507
- }
508
- function validateNativeOptions(deps, options) {
509
- if (options.runtime !== 'native')
510
- return true;
511
- if (options.attachMode === 'passthrough') {
512
- deps.error('Native harnesses do not support passthrough attach mode; use drive or view.');
513
- deps.exit(1);
514
- return false;
515
- }
516
- if (options.spawnMode !== 'interactive') {
517
- deps.error('Native harnesses currently support only interactive spawn mode.');
518
- deps.exit(1);
519
- return false;
520
- }
521
- if (options.exitAfterTask) {
522
- deps.error('Native harnesses do not currently support --exit-after-task.');
523
- deps.exit(1);
524
- return false;
525
- }
526
- return true;
527
- }
528
- /**
529
- * Register the `local agent …` subtree (and `runtime tail`) onto the driver
530
- * group. List/spawn/release/kill talk to a running local broker.
531
- */
532
- /**
533
- * Run a delivery-mode command against an agent that may live on another node.
534
- *
535
- * `attach` has always accepted `--node` and reaches remote agents through the
536
- * fleet-node proxy; `message flush|hold|auto` did not, so they only ever saw
537
- * the *local* broker's worker registry. The result was that a name `node agent
538
- * list` and `attach` both resolved returned `agent_not_found` from `flush` —
539
- * two disjoint registries behind one CLI, and no way to wake a parked agent on
540
- * another machine without hand-driving its PTY (relay#1593 row 10).
541
- *
542
- * With `--node` the command is issued through the same authenticated fleet
543
- * proxy `attach --node` uses, so both surfaces resolve names the same way.
544
- * Without it the behaviour is unchanged: the local broker, as before.
545
- */
546
- async function withDeliveryModeClient(deps, name, opts, sessionMode, run) {
547
- let node = typeof opts.node === 'string' && opts.node.trim() ? opts.node.trim() : undefined;
548
- if (!node && opts.workspaceKey !== undefined) {
549
- deps.error('Error: --workspace-key requires an explicit --node. To target the local broker instead, use --broker-url / --api-key or read connection.json from --state-dir.');
550
- deps.exit(1);
551
- return undefined;
552
- }
553
- let targetBaseUrl;
554
- if (!node && !(await hasLocalBrokerSelection(deps, opts))) {
555
- const fleetTarget = await deps.resolveFleetAttachTarget(name);
556
- if (fleetTarget.error) {
557
- deps.error(`Error: ${fleetTarget.error}`);
558
- deps.exit(1);
559
- return undefined;
560
- }
561
- if (fleetTarget.target) {
562
- node = fleetTarget.target.node;
563
- targetBaseUrl = fleetTarget.target.baseUrl;
564
- }
565
- }
566
- if (!node) {
567
- let captured;
568
- await runLocalBroker(deps, brokerOptionsFromOpts(opts), async (client) => {
569
- captured = await run(client);
570
- });
571
- return captured;
572
- }
573
- const workspaceKey = typeof opts.workspaceKey === 'string' && opts.workspaceKey.trim() ? opts.workspaceKey.trim() : undefined;
574
- // A flush only drains an already-held queue, so it runs from the
575
- // least-privileged session that still establishes the tunnel. Changing
576
- // delivery mode is different: the broker refuses `terminal.set_delivery_mode`
577
- // from a view session ("view sessions cannot change delivery mode"), so
578
- // hold/auto must claim drive. That is honest — they take control of the
579
- // agent's inbound delivery — but it means they contend with an attached
580
- // driver, which a flush does not.
581
- // `startFleetNodeAttachProxy` throws `FleetNodeAttachError` for
582
- // node_not_found / node_unreachable / control_plane_timeout. Creating it
583
- // outside the try meant those rejected the Commander action directly and
584
- // bypassed the very error contract this block exists to honour — only
585
- // `agent_not_found`, raised inside `run`, was actually covered. It is now
586
- // created inside, and closed in `finally` only if it was created.
587
- let proxy;
588
- try {
589
- proxy = await startFleetNodeAttachProxy({
590
- agent: name,
591
- node,
592
- mode: sessionMode,
593
- env: deps.env,
594
- fetch: deps.fetch,
595
- ...(targetBaseUrl ? { baseUrl: targetBaseUrl } : {}),
596
- ...(workspaceKey ? { workspaceKey } : {}),
597
- });
598
- return await run(createBrokerClient({
599
- url: proxy.brokerUrl,
600
- apiKey: proxy.apiKey,
601
- // The proxy can legitimately spend its full reconnect/readiness
602
- // budget (162.5s) before a request reaches the loopback handler.
603
- // Without this the client used the harness driver's 30s default and
604
- // could report a timeout while the proxy went on to apply the
605
- // mutation — leaving the operator unsure whether the flush or mode
606
- // change actually happened.
607
- requestTimeoutMs: proxy.requestTimeoutMs,
608
- }, deps.fetch));
609
- }
610
- catch (error) {
611
- // The local path reports failures through deps.error/deps.exit inside
612
- // runLocalBroker. Without this the remote path rejected the Commander
613
- // action instead, so a remote `agent_not_found` or terminal-session
614
- // failure surfaced differently from the identical local failure.
615
- deps.error(`Error: ${describeError(error)}`);
616
- deps.exit(1);
617
- return undefined;
618
- }
619
- finally {
620
- if (proxy)
621
- await proxy.close();
622
- }
623
- }
624
- export function registerLocalAgentCommands(group, overrides = {}) {
625
- const deps = withDefaults(overrides);
626
- const agent = group.command('agent').description('Inspect and manage broker-spawned agents');
627
- addBrokerOptions(agent
628
- .command('list')
629
- .description('List agents running on the local broker')
630
- .option('--pretty', 'Show a compact human-readable list')
631
- .option('--status', 'Include each agent inbound delivery mode and pending-queue contents (relay#1387)')).action(async (opts) => {
632
- await run(deps, async (client) => {
633
- const agents = await client.listAgents();
634
- if (opts.status) {
635
- const withStatus = await withDeliveryStatus(client, agents);
636
- deps.log(opts.pretty
637
- ? formatPrettyAgentStatusList(withStatus, deps.now())
638
- : JSON.stringify(withStatus, null, 2));
639
- return;
640
- }
641
- deps.log(opts.pretty ? formatPrettyAgentList(agents, deps.now()) : JSON.stringify(agents, null, 2));
642
- }, brokerOptionsFromOpts(opts));
643
- });
644
- addBrokerOptions(agent.command('spawn'))
645
- .description('Spawn an agent with the given provider CLI')
646
- .argument('<provider>', 'CLI provider (claude, codex, gemini, droid, …); droid is high-risk for delegation/spawn tasks')
647
- .option('--name <name>', 'Agent name (defaults to the provider)')
648
- .option('--channels <channels...>', 'Channels to join', ['general'])
649
- .option('--task <task>', 'Initial task prompt')
650
- .option('--task-file <path>', 'Read the initial task from a local UTF-8 file')
651
- .option('--model <model>', 'Model override')
652
- .option('--runtime <runtime>', 'Harness runtime: auto | native | pty', 'auto')
653
- .option('--cwd <path>', 'Working directory for the spawned agent')
654
- .option('--spawn-mode <mode>', 'Spawn lifecycle: interactive | task-exit', 'interactive')
655
- .option('--exit-after-task', 'Exit the spawned agent after it completes the injected task')
656
- .action(async (provider, opts) => {
657
- const runtime = resolveRuntimeOption(deps, provider, opts.runtime);
658
- const spawnMode = parseSpawnModeOption(deps, opts.spawnMode);
659
- if (!runtime || !spawnMode)
660
- return;
661
- if (!validateNativeOptions(deps, {
662
- runtime: runtime.selected,
663
- spawnMode,
664
- exitAfterTask: Boolean(opts.exitAfterTask),
665
- }))
666
- return;
667
- await run(deps, async (client) => {
668
- const baseName = opts.name ?? provider;
669
- const resolved = resolveAutoSpawn(provider, baseName, await readTaskInput(opts.task, opts.taskFile, false, {
670
- cli: provider,
671
- runtime: runtime.selected,
672
- }), opts.model, runtime.selected);
673
- await spawnAgentWithClient(client, {
674
- name: resolved.name,
675
- cli: provider,
676
- channels: opts.channels ?? ['general'],
677
- task: resolved.task,
678
- model: resolved.model,
679
- cwd: opts.cwd ?? deps.cwd(),
680
- spawnMode,
681
- exitAfterTask: opts.exitAfterTask,
682
- runtime: runtime.requested,
683
- });
684
- const autoNote = opts.model === 'auto' ? ' (auto-routed)' : '';
685
- deps.log(`Spawned ${resolved.name} (${provider}, ${runtime.selected})${autoNote}.`);
686
- }, brokerOptionsFromOpts(opts));
687
- });
688
- addBrokerOptions(agent.command('new'))
689
- .description('Spawn an agent and attach to it')
690
- .argument('<provider>', 'CLI provider (claude, codex, gemini, droid, …); droid is high-risk for delegation/spawn tasks')
691
- .option('--name <name>', 'Agent name (defaults to the provider)')
692
- .option('--mode <mode>', 'Attach mode: drive | view | passthrough', 'drive')
693
- .option('--channels <channels...>', 'Channels to join', ['general'])
694
- .option('--task <task>', 'Initial task prompt')
695
- .option('--task-file <path>', 'Read the initial task from a local UTF-8 file')
696
- .option('--model <model>', 'Model override')
697
- .option('--runtime <runtime>', 'Harness runtime: auto | native | pty', 'auto')
698
- .option('--cwd <path>', 'Working directory for the spawned agent')
699
- .option('--spawn-mode <mode>', 'Spawn lifecycle: interactive | task-exit', 'interactive')
700
- .option('--exit-after-task', 'Exit the spawned agent after it completes the injected task')
701
- .action(async (provider, options) => {
702
- const mode = options.mode ?? 'drive';
703
- if (mode !== 'drive' && mode !== 'view' && mode !== 'passthrough') {
704
- deps.error(`Unknown attach mode "${mode}". Expected one of: drive, view, passthrough.`);
705
- deps.exit(1);
706
- return;
707
- }
708
- const runtime = resolveRuntimeOption(deps, provider, options.runtime);
709
- const spawnMode = parseSpawnModeOption(deps, options.spawnMode);
710
- if (!runtime || !spawnMode)
711
- return;
712
- if (!validateNativeOptions(deps, {
713
- runtime: runtime.selected,
714
- spawnMode,
715
- exitAfterTask: Boolean(options.exitAfterTask),
716
- attachMode: mode,
717
- }))
718
- return;
719
- const brokerOptions = brokerOptionsFromOpts(options);
720
- const baseName = options.name ?? provider;
721
- let resolved;
722
- try {
723
- resolved = resolveAutoSpawn(provider, baseName, await readTaskInput(options.task, options.taskFile, false, {
724
- cli: provider,
725
- runtime: runtime.selected,
726
- }), options.model, runtime.selected);
727
- }
728
- catch (err) {
729
- deps.error(err instanceof Error ? err.message : String(err));
730
- deps.exit(1);
731
- return;
732
- }
733
- await run(deps, async (client) => {
734
- await spawnAgentWithClient(client, {
735
- name: resolved.name,
736
- cli: provider,
737
- channels: options.channels ?? ['general'],
738
- task: resolved.task,
739
- model: resolved.model,
740
- cwd: options.cwd ?? deps.cwd(),
741
- spawnMode,
742
- exitAfterTask: options.exitAfterTask,
743
- runtime: runtime.requested,
744
- });
745
- const autoNote = options.model === 'auto' ? ' (auto-routed)' : '';
746
- deps.log(`Spawned ${resolved.name} (${provider}, ${runtime.selected}). Attaching (${mode})${autoNote}…`);
747
- }, brokerOptions);
748
- // Attach to the same broker the agent was just spawned on.
749
- const code = await deps.attach(resolved.name, mode, brokerOptions);
750
- if (code !== 0) {
751
- deps.exit(code);
752
- }
753
- });
754
- addBrokerOptions(agent.command('release'))
755
- .description('Release an agent (graceful stop)')
756
- .argument('<name>', 'Agent name')
757
- .action(async (name, opts) => {
758
- await run(deps, async (client) => {
759
- await client.release(name);
760
- deps.log(`Released ${name}.`);
761
- }, brokerOptionsFromOpts(opts));
762
- });
763
- addBrokerOptions(agent.command('set-model'))
764
- .description("Switch a running agent's model (sends `/model` to its TUI; best-effort)")
765
- .argument('<name>', 'Agent name')
766
- .argument('<model>', 'Model identifier to switch to')
767
- .action(async (name, model, opts) => {
768
- await run(deps, async (client) => {
769
- await client.setModel(name, model);
770
- deps.log(`Sent \`/model ${model}\` to ${name} (best-effort — the agent's TUI applies it).`);
771
- }, brokerOptionsFromOpts(opts));
772
- });
773
- agent
774
- .command('attach')
775
- .description('Attach to a running agent interactively (drive | view | passthrough)')
776
- .argument('<name>', 'Agent name')
777
- .option('--mode <mode>', 'drive | view | passthrough', 'view')
778
- .option('--node <node>', 'Canonical authenticated fleet-node terminal attach (physical or Daytona)')
779
- .option('--base-url <url>', 'Relaycast API base URL for --node (defaults to the selected workspace route)')
780
- .option('--ssh-host <host>', 'SSH host fallback for a physical fleet node')
781
- .option('--broker-url <url>', 'Broker base URL (overrides RELAY_BROKER_URL and connection.json)')
782
- .option('--api-key <key>', 'Broker API key (overrides RELAY_BROKER_API_KEY and connection.json)')
783
- .option('--state-dir <dir>', 'Directory containing connection.json (with --ssh-host: path on target; auto-discovered when omitted)')
784
- .option('--workspace-key <key>', 'Relaycast workspace key for --node (overrides RELAY_WORKSPACE_KEY, the project pin, and the machine-global active workspace)')
785
- .option('--join-ticket <ticket>', "Short-lived Relaycast join ticket for --node (redeemed and saved as this project's workspace credential)")
786
- .option('--json', 'Emit normalized agent events as NDJSON')
787
- .option('--reasoning', 'Include agent reasoning events')
788
- .option('--diagnostics', 'Include native harness diagnostics')
789
- .action(async (name, options) => {
790
- const mode = options.mode ?? 'view';
791
- if (mode !== 'drive' && mode !== 'view' && mode !== 'passthrough') {
792
- deps.error(`Unknown attach mode "${mode}". Expected one of: drive, view, passthrough.`);
793
- deps.exit(1);
794
- return;
795
- }
796
- const sshHost = options.sshHost;
797
- const node = options.node;
798
- const rawWorkspaceKey = options.workspaceKey;
799
- const rawJoinTicket = options.joinTicket;
800
- // Only the fleet path authenticates with a workspace key. The local and
801
- // SSH paths speak the broker contract, so accepting the flag there would
802
- // silently ignore it and send the caller to the wrong workspace. Gate on
803
- // the raw option rather than the normalized one: `--workspace-key "$KEY"`
804
- // with an unset variable is still a caller asking for a workspace, and
805
- // must be told so instead of being routed to a broker.
806
- const credential = resolveAttachCredentialSelection(rawWorkspaceKey, rawJoinTicket, node, sshHost);
807
- if (!credential.ok) {
808
- deps.error(credential.error);
809
- deps.exit(1);
810
- return;
811
- }
812
- if (node !== undefined && sshHost !== undefined) {
813
- deps.error('Error: --node cannot be combined with --ssh-host. Use --ssh-host only as the explicit SSH fallback.');
814
- deps.exit(1);
815
- return;
816
- }
817
- if (node !== undefined) {
818
- if (options.brokerUrl !== undefined ||
819
- options.apiKey !== undefined ||
820
- options.stateDir !== undefined) {
821
- deps.error('Error: --node cannot be combined with --broker-url, --api-key, or --state-dir. It opens an ephemeral authenticated loopback session.');
822
- deps.exit(1);
823
- return;
824
- }
825
- try {
826
- let attachWorkspaceKey = credential.workspaceKey;
827
- const validatedBaseUrl = credential.joinTicket && typeof options.baseUrl === 'string'
828
- ? validateFleetAttachBaseUrl(options.baseUrl)
829
- : undefined;
830
- if (credential.joinTicket) {
831
- // Pass the redeemed key explicitly into the first attach. Merely
832
- // writing the project pin would leave this process vulnerable to
833
- // a higher-precedence ambient workspace environment variable.
834
- attachWorkspaceKey = await redeemAndPersistAttachCredential(deps, {
835
- ticket: credential.joinTicket,
836
- node,
837
- agent: name,
838
- mode,
839
- baseUrl: validatedBaseUrl,
840
- });
841
- }
842
- const code = await deps.attachNode(name, mode, node, {
843
- baseUrl: options.baseUrl,
844
- workspaceKey: attachWorkspaceKey,
845
- json: options.json,
846
- reasoning: options.reasoning,
847
- diagnostics: options.diagnostics,
848
- });
849
- if (code !== 0)
850
- deps.exit(code);
851
- }
852
- catch (error) {
853
- const message = describeError(error);
854
- deps.error(message.startsWith('Error:') ? message : `Error: ${message}`);
855
- deps.exit(1);
856
- }
857
- return;
858
- }
859
- if (sshHost !== undefined) {
860
- if (options.brokerUrl !== undefined || options.apiKey !== undefined) {
861
- deps.error('Error: --ssh-host cannot be combined with --broker-url or --api-key.');
862
- deps.exit(1);
863
- return;
864
- }
865
- const code = await deps.attachRemote(name, mode, sshHost, {
866
- stateDir: options.stateDir,
867
- json: options.json,
868
- reasoning: options.reasoning,
869
- diagnostics: options.diagnostics,
870
- });
871
- if (code !== 0)
872
- deps.exit(code);
873
- return;
874
- }
875
- // A sandbox worker has no local broker. Resolve a unique live fleet
876
- // placement before falling back to the local connection contract so a
877
- // flag-free attach follows the worker automatically.
878
- if (!(await hasLocalBrokerSelection(deps, options))) {
879
- const fleetTarget = await deps.resolveFleetAttachTarget(name);
880
- if (fleetTarget.error) {
881
- deps.error(`Error: ${fleetTarget.error}`);
882
- deps.exit(1);
883
- return;
884
- }
885
- if (fleetTarget.target) {
886
- try {
887
- const code = await deps.attachNode(name, mode, fleetTarget.target.node, {
888
- baseUrl: fleetTarget.target.baseUrl,
889
- json: options.json,
890
- reasoning: options.reasoning,
891
- diagnostics: options.diagnostics,
892
- });
893
- if (code !== 0)
894
- deps.exit(code);
895
- }
896
- catch (error) {
897
- const message = describeError(error);
898
- deps.error(message.startsWith('Error:') ? message : `Error: ${message}`);
899
- deps.exit(1);
900
- }
901
- return;
902
- }
903
- }
904
- const code = await deps.attach(name, mode, {
905
- brokerUrl: options.brokerUrl,
906
- apiKey: options.apiKey,
907
- stateDir: options.stateDir,
908
- json: options.json,
909
- reasoning: options.reasoning,
910
- diagnostics: options.diagnostics,
911
- });
912
- if (code !== 0) {
913
- deps.exit(code);
914
- }
915
- });
916
- const message = agent.command('message').description('Control local broker message delivery for an agent');
917
- addBrokerOptions(message
918
- .command('flush')
919
- .description('Flush queued relay messages into a held agent')
920
- .argument('<name>', 'Agent name')
921
- .option('--node <node>', 'Target an agent on a fleet node instead of the local broker')
922
- .option('--workspace-key <key>', 'Workspace key for the fleet node (requires --node)')).action(async (name, opts) => {
923
- const result = await withDeliveryModeClient(deps, name, opts, 'view', (client) => client.flushPending(name));
924
- if (result !== undefined)
925
- deps.log(JSON.stringify({ name, ...result }, null, 2));
926
- });
927
- addBrokerOptions(message
928
- .command('hold')
929
- .description('Hold new relay messages for an agent until flushed')
930
- .argument('<name>', 'Agent name')
931
- .option('--node <node>', 'Target an agent on a fleet node instead of the local broker')
932
- .option('--workspace-key <key>', 'Workspace key for the fleet node (requires --node)')).action(async (name, opts) => {
933
- const result = await withDeliveryModeClient(deps, name, opts, 'drive', (client) => client.setInboundDeliveryMode(name, 'manual_flush'));
934
- if (result !== undefined)
935
- deps.log(JSON.stringify({ name, ...result }, null, 2));
936
- });
937
- addBrokerOptions(message
938
- .command('auto')
939
- .description('Resume automatic relay message injection for an agent')
940
- .argument('<name>', 'Agent name')
941
- .option('--node <node>', 'Target an agent on a fleet node instead of the local broker')
942
- .option('--workspace-key <key>', 'Workspace key for the fleet node (requires --node)')).action(async (name, opts) => {
943
- const result = await withDeliveryModeClient(deps, name, opts, 'drive', (client) => client.setInboundDeliveryMode(name, 'auto_inject'));
944
- if (result !== undefined)
945
- deps.log(JSON.stringify({ name, ...result }, null, 2));
946
- });
947
- addBrokerOptions(group.command('tail'))
948
- .description('Stream broker events (optionally filtered to one agent)')
949
- .option('--agent <name>', "Filter to a single agent's output stream")
950
- .action(async (options) => {
951
- await run(deps, async (client) => {
952
- if (options.agent) {
953
- for await (const chunk of client.subscribeWorkerStream(options.agent)) {
954
- process.stdout.write(chunk);
955
- }
956
- return;
957
- }
958
- client.connectEvents();
959
- await new Promise((resolve) => {
960
- client.onEvent((event) => {
961
- deps.log(JSON.stringify(event));
962
- });
963
- // Ctrl+C ends a streaming tail cleanly (exit 0, no error output).
964
- process.once('SIGINT', () => resolve());
965
- });
966
- }, brokerOptionsFromOpts(options));
967
- });
968
- }
969
- //# sourceMappingURL=local-agent.js.map