@phnx-labs/agents-cli 1.23.13 → 1.23.15

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 (164) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +30 -59
  3. package/dist/cli/command-registry.js +0 -24
  4. package/dist/commands/accounts.js +3 -3
  5. package/dist/commands/daemon.js +5 -147
  6. package/dist/commands/doctor.js +7 -0
  7. package/dist/commands/events-logs.d.ts +2 -0
  8. package/dist/commands/{logs.js → events-logs.js} +28 -127
  9. package/dist/commands/events.js +3 -1
  10. package/dist/commands/exec.d.ts +0 -1
  11. package/dist/commands/exec.js +3 -11
  12. package/dist/commands/feed.d.ts +1 -1
  13. package/dist/commands/feed.js +4 -7
  14. package/dist/commands/mcp.js +1 -1
  15. package/dist/commands/menubar.js +12 -226
  16. package/dist/commands/projects.js +1 -2
  17. package/dist/commands/{trash.d.ts → prune-trash.d.ts} +1 -1
  18. package/dist/commands/{trash.js → prune-trash.js} +8 -8
  19. package/dist/commands/prune.js +3 -1
  20. package/dist/commands/send.js +2 -5
  21. package/dist/commands/sessions.js +1 -1
  22. package/dist/commands/ssh.js +2 -2
  23. package/dist/commands/utils.d.ts +1 -5
  24. package/dist/commands/utils.js +1 -7
  25. package/dist/lib/agent-spec/agents.d.ts +0 -2
  26. package/dist/lib/agent-spec/agents.js +0 -12
  27. package/dist/lib/agent-spec/index.d.ts +0 -4
  28. package/dist/lib/agent-spec/index.js +0 -4
  29. package/dist/lib/commands.d.ts +1 -5
  30. package/dist/lib/commands.js +2 -69
  31. package/dist/lib/comms-render.d.ts +0 -7
  32. package/dist/lib/comms-render.js +0 -41
  33. package/dist/lib/config-keys.d.ts +1 -1
  34. package/dist/lib/config-keys.js +8 -0
  35. package/dist/lib/daemon/daemon.js +1 -6
  36. package/dist/lib/daemon-services.d.ts +1 -1
  37. package/dist/lib/daemon-services.js +0 -5
  38. package/dist/lib/device-config.d.ts +2 -0
  39. package/dist/lib/device-config.js +81 -8
  40. package/dist/lib/devices/doctor-findings.d.ts +6 -1
  41. package/dist/lib/devices/doctor-findings.js +34 -1
  42. package/dist/lib/git.d.ts +1 -0
  43. package/dist/lib/git.js +5 -0
  44. package/dist/lib/hooks/install.d.ts +0 -7
  45. package/dist/lib/hooks/install.js +0 -55
  46. package/dist/lib/hosts/passthrough.js +2 -4
  47. package/dist/lib/hosts/progress.js +2 -2
  48. package/dist/lib/hosts/remote-cmd.js +0 -1
  49. package/dist/lib/installations/migrate.d.ts +1 -0
  50. package/dist/lib/installations/migrate.js +18 -1
  51. package/dist/lib/installations/versions.js +2 -2
  52. package/dist/lib/loop.js +1 -1
  53. package/dist/lib/mailbox-target.d.ts +0 -31
  54. package/dist/lib/mailbox-target.js +0 -37
  55. package/dist/lib/mcp-lookup.d.ts +7 -0
  56. package/dist/lib/mcp-lookup.js +71 -0
  57. package/dist/lib/mcp.d.ts +0 -8
  58. package/dist/lib/mcp.js +0 -47
  59. package/dist/lib/menubar/install-menubar.d.ts +0 -15
  60. package/dist/lib/menubar/install-menubar.js +24 -118
  61. package/dist/lib/menubar/resolve-version.d.ts +9 -10
  62. package/dist/lib/menubar/resolve-version.js +70 -30
  63. package/dist/lib/paths.d.ts +0 -1
  64. package/dist/lib/paths.js +0 -18
  65. package/dist/lib/plugins/skills.d.ts +0 -10
  66. package/dist/lib/plugins/skills.js +2 -165
  67. package/dist/lib/project-pull.js +1 -2
  68. package/dist/lib/resources.d.ts +1 -1
  69. package/dist/lib/routines-project.js +1 -1
  70. package/dist/lib/session/local-tmux-attach.js +2 -2
  71. package/dist/lib/startup/command-registry.js +20 -7
  72. package/dist/lib/teams/agents.js +1 -1
  73. package/dist/lib/teams/placement-probe.d.ts +9 -0
  74. package/dist/lib/teams/placement-probe.js +20 -15
  75. package/dist/lib/triggers/webhook.d.ts +2 -59
  76. package/dist/lib/triggers/webhook.js +2 -422
  77. package/package.json +2 -1
  78. package/dist/commands/funnel.d.ts +0 -2
  79. package/dist/commands/funnel.js +0 -77
  80. package/dist/commands/logs.d.ts +0 -2
  81. package/dist/commands/mailboxes.d.ts +0 -2
  82. package/dist/commands/mailboxes.js +0 -400
  83. package/dist/commands/message.d.ts +0 -2
  84. package/dist/commands/message.js +0 -259
  85. package/dist/commands/packages-materialize.d.ts +0 -6
  86. package/dist/commands/packages-materialize.js +0 -90
  87. package/dist/commands/packages.d.ts +0 -5
  88. package/dist/commands/packages.js +0 -763
  89. package/dist/commands/route.d.ts +0 -2
  90. package/dist/commands/route.js +0 -259
  91. package/dist/commands/testdata/feed-hub.d.ts +0 -1
  92. package/dist/commands/testdata/feed-hub.js +0 -11
  93. package/dist/commands/tmux.d.ts +0 -7
  94. package/dist/commands/tmux.js +0 -529
  95. package/dist/commands/traces.d.ts +0 -2
  96. package/dist/commands/traces.js +0 -204
  97. package/dist/commands/webhook.d.ts +0 -5
  98. package/dist/commands/webhook.js +0 -105
  99. package/dist/lib/agent-spec/materialize.d.ts +0 -3
  100. package/dist/lib/agent-spec/materialize.js +0 -277
  101. package/dist/lib/agent-spec/package-resolve.d.ts +0 -4
  102. package/dist/lib/agent-spec/package-resolve.js +0 -231
  103. package/dist/lib/agent-spec/package-schema.d.ts +0 -3
  104. package/dist/lib/agent-spec/package-schema.js +0 -136
  105. package/dist/lib/agent-spec/package-types.d.ts +0 -94
  106. package/dist/lib/agent-spec/package-types.js +0 -10
  107. package/dist/lib/daemon/testdata/process-view-daemon.d.ts +0 -1
  108. package/dist/lib/daemon/testdata/process-view-daemon.js +0 -12
  109. package/dist/lib/daemon/testdata/process-view-start.d.ts +0 -1
  110. package/dist/lib/daemon/testdata/process-view-start.js +0 -41
  111. package/dist/lib/daemon/webhook-receiver-service.d.ts +0 -8
  112. package/dist/lib/daemon/webhook-receiver-service.js +0 -16
  113. package/dist/lib/daemon-webhooks.d.ts +0 -48
  114. package/dist/lib/daemon-webhooks.js +0 -177
  115. package/dist/lib/funnel.d.ts +0 -6
  116. package/dist/lib/funnel.js +0 -31
  117. package/dist/lib/net-close.d.ts +0 -2
  118. package/dist/lib/net-close.js +0 -20
  119. package/dist/lib/packages/output-home.d.ts +0 -9
  120. package/dist/lib/packages/output-home.js +0 -89
  121. package/dist/lib/registry.d.ts +0 -65
  122. package/dist/lib/registry.js +0 -432
  123. package/dist/lib/routers.d.ts +0 -25
  124. package/dist/lib/routers.js +0 -122
  125. package/dist/lib/run-trace-sync.d.ts +0 -7
  126. package/dist/lib/run-trace-sync.js +0 -35
  127. package/dist/lib/session/testdata/pid-registry-namespace.d.ts +0 -1
  128. package/dist/lib/session/testdata/pid-registry-namespace.js +0 -25
  129. package/dist/lib/session/testdata/process-view-namespace.d.ts +0 -1
  130. package/dist/lib/session/testdata/process-view-namespace.js +0 -56
  131. package/dist/lib/session/testdata/process-view-private.d.ts +0 -1
  132. package/dist/lib/session/testdata/process-view-private.js +0 -11
  133. package/dist/lib/testdata/daemon-health-writer.d.ts +0 -1
  134. package/dist/lib/testdata/daemon-health-writer.js +0 -8
  135. package/dist/lib/testdata/owner-notify-api.d.ts +0 -23
  136. package/dist/lib/testdata/owner-notify-api.js +0 -82
  137. package/dist/lib/testdata/refresh-coordinator-worker.d.ts +0 -1
  138. package/dist/lib/testdata/refresh-coordinator-worker.js +0 -23
  139. package/dist/lib/traces/backend.d.ts +0 -8
  140. package/dist/lib/traces/backend.js +0 -33
  141. package/dist/lib/traces/classify.d.ts +0 -40
  142. package/dist/lib/traces/classify.js +0 -70
  143. package/dist/lib/traces/config.d.ts +0 -2
  144. package/dist/lib/traces/config.js +0 -2
  145. package/dist/lib/traces/insights.d.ts +0 -30
  146. package/dist/lib/traces/insights.js +0 -198
  147. package/dist/lib/traces/phenotype.d.ts +0 -18
  148. package/dist/lib/traces/phenotype.js +0 -335
  149. package/dist/lib/traces/provision.d.ts +0 -16
  150. package/dist/lib/traces/provision.js +0 -25
  151. package/dist/lib/traces/schema2-build.d.ts +0 -28
  152. package/dist/lib/traces/schema2-build.js +0 -496
  153. package/dist/lib/traces/schema2-danger.d.ts +0 -7
  154. package/dist/lib/traces/schema2-danger.js +0 -123
  155. package/dist/lib/traces/schema2.d.ts +0 -139
  156. package/dist/lib/traces/schema2.js +0 -20
  157. package/dist/lib/traces/segments.d.ts +0 -73
  158. package/dist/lib/traces/segments.js +0 -236
  159. package/dist/lib/traces/sync.d.ts +0 -197
  160. package/dist/lib/traces/sync.js +0 -654
  161. package/dist/lib/traces/worker-template.d.ts +0 -1
  162. package/dist/lib/traces/worker-template.js +0 -292
  163. package/dist/lib/triggers/handlers.d.ts +0 -66
  164. package/dist/lib/triggers/handlers.js +0 -383
@@ -1,400 +0,0 @@
1
- import * as os from 'os';
2
- import * as path from 'path';
3
- import chalk from 'chalk';
4
- import { die, humanDuration, relTime, truncate, visibleWidth } from '../lib/format.js';
5
- import { setHelpSections } from '../lib/help.js';
6
- import { listBoxes, readBox, mailboxDir, isValidMailboxId, watchMessages, } from '../lib/mailbox.js';
7
- import { gcMailbox } from '../lib/mailbox-gc.js';
8
- import { GLYPH, masthead, sparkline, aggregate, hourlyCounts, graphEdges, } from '../lib/comms-render.js';
9
- import { getMailboxRootDir } from '../lib/state.js';
10
- import { getActiveSessions } from '../lib/session/active.js';
11
- import { mailboxIdForActiveSession } from '../lib/mailbox-target.js';
12
- function labelForBox(id, byMailbox) {
13
- const s = byMailbox.get(id);
14
- if (s) {
15
- const topic = s.name || s.topic || s.label;
16
- return { label: topic ? truncate(topic, 40) : id.slice(0, 8), live: true };
17
- }
18
- return { label: id.slice(0, 8), live: false };
19
- }
20
- async function collectBoxes(root) {
21
- let sessions = [];
22
- try {
23
- sessions = await getActiveSessions();
24
- }
25
- catch {
26
- }
27
- const byMailbox = new Map();
28
- for (const s of sessions) {
29
- const mid = mailboxIdForActiveSession(s);
30
- if (mid)
31
- byMailbox.set(mid, s);
32
- }
33
- return listBoxes(root).map((id) => {
34
- const { label, live } = labelForBox(id, byMailbox);
35
- return { id, label, live, messages: readBox(mailboxDir(id, root)) };
36
- });
37
- }
38
- function pending(box) {
39
- return box.messages.filter((m) => m.state !== 'consumed').length;
40
- }
41
- function senderOf(m) {
42
- return m.from || 'operator';
43
- }
44
- const STATE_TAG = {
45
- inbox: chalk.yellow('pending'),
46
- processing: chalk.cyan('in-flight'),
47
- consumed: chalk.dim('delivered'),
48
- };
49
- function selfMailboxId() {
50
- const dir = process.env.AGENTS_MAILBOX_DIR;
51
- if (!dir)
52
- return undefined;
53
- const id = path.basename(dir.replace(/[/\\]+$/, ''));
54
- return id || undefined;
55
- }
56
- function parseSinceArg(s) {
57
- const m = s.match(/^(\d+)([smhdw])$/);
58
- if (m) {
59
- const n = parseInt(m[1], 10);
60
- const unitMs = {
61
- s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000,
62
- };
63
- return Date.now() - n * unitMs[m[2]];
64
- }
65
- const ms = Date.parse(s);
66
- if (Number.isNaN(ms))
67
- die(`Invalid --since value: ${JSON.stringify(s)} (use e.g. 2h, 7d, or an ISO date).`);
68
- return ms;
69
- }
70
- function buildFilters(opts) {
71
- return {
72
- from: opts.from,
73
- to: opts.to,
74
- sinceMs: opts.since ? parseSinceArg(opts.since) : undefined,
75
- };
76
- }
77
- function hasFilters(f) {
78
- return Boolean(f.from || f.to || f.sinceMs != null);
79
- }
80
- function matchesFilters(msg, toLabel, boxId, f) {
81
- if (f.sinceMs != null) {
82
- const t = Date.parse(msg.ts);
83
- if (Number.isNaN(t) || t < f.sinceMs)
84
- return false;
85
- }
86
- if (f.from && !msg.from.toLowerCase().includes(f.from.toLowerCase()))
87
- return false;
88
- if (f.to && !toLabel.toLowerCase().includes(f.to.toLowerCase()) && !boxId.toLowerCase().includes(f.to.toLowerCase()))
89
- return false;
90
- return true;
91
- }
92
- function clockTime(iso) {
93
- const d = new Date(iso);
94
- if (Number.isNaN(d.getTime()))
95
- return '--:--:--';
96
- const p = (n) => String(n).padStart(2, '0');
97
- return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
98
- }
99
- function renderOverview(boxes, limit, filters) {
100
- const nonEmpty = boxes.filter((b) => b.messages.length > 0);
101
- if (nonEmpty.length === 0) {
102
- console.log(chalk.dim('No mailboxes with messages. Boxes are created on the first `agents message`.'));
103
- return;
104
- }
105
- const msgs = aggregate(nonEmpty);
106
- const live = boxes.filter((b) => b.live).length;
107
- const awaiting = msgs.filter((m) => m.state !== 'consumed').length;
108
- console.log(masthead({
109
- title: 'fleet comms',
110
- host: os.hostname(),
111
- accent: 'cyan',
112
- right: `${live} live · ${boxes.length} boxes`,
113
- stats: [`${msgs.length} messages`, `${awaiting} awaiting delivery`, `last ${relTime(msgs[0].ts)}`],
114
- }));
115
- console.log(` ${chalk.dim('24h')} ${chalk.cyan(sparkline(hourlyCounts(msgs, 24)))}`);
116
- console.log();
117
- const rows = [...nonEmpty].sort((a, b) => lastTs(b) - lastTs(a));
118
- for (const box of rows) {
119
- const p = pending(box);
120
- const dot = box.live ? chalk.green(GLYPH.live) : chalk.dim(GLYPH.idle);
121
- const counts = [
122
- p > 0 ? chalk.yellow(`${p} pending`) : null,
123
- chalk.dim(`${box.messages.length} total`),
124
- ].filter(Boolean).join(chalk.dim(' · '));
125
- const last = box.messages.length ? chalk.dim(relTime(newestMessage(box).ts)) : '';
126
- console.log(` ${dot} ${chalk.bold(box.label.padEnd(40))} ${counts} ${last}`);
127
- console.log(` ${chalk.dim(box.id)}`);
128
- }
129
- const all = msgs
130
- .filter((m) => matchesFilters(m, m.toLabel, m.box, filters))
131
- .slice(0, limit);
132
- console.log();
133
- console.log(chalk.bold(`Recent messages`) + chalk.dim(` (${all.length})`));
134
- if (all.length === 0) {
135
- console.log(chalk.dim(' Nothing matches the current filters.'));
136
- }
137
- for (const m of all) {
138
- const when = chalk.dim(relTime(m.ts).padStart(10));
139
- const route = `${chalk.magenta(truncate(m.from, 24))} ${chalk.dim(GLYPH.route)} ${chalk.cyan(truncate(m.toLabel, 40))}`;
140
- console.log(` ${when} ${STATE_TAG[m.state]} ${route}`);
141
- console.log(` ${truncate(m.text.replace(/\s+/g, ' ').trim(), 100)}`);
142
- }
143
- console.log();
144
- console.log(chalk.dim('Tip: `agents mailboxes <id>` one box · `--watch` live tail · `--between <a> <b>` thread · `--graph` routes · `--json` machine output'));
145
- }
146
- async function runWatch(root, opts) {
147
- const boxes = await collectBoxes(root);
148
- const labels = new Map(boxes.map((b) => [b.id, b.label]));
149
- const self = selfMailboxId();
150
- const controller = new AbortController();
151
- const onSigint = () => controller.abort();
152
- process.on('SIGINT', onSigint);
153
- try {
154
- if (!opts.json) {
155
- console.log(masthead({
156
- title: 'fleet comms',
157
- host: os.hostname(),
158
- accent: 'cyan',
159
- right: chalk.green(GLYPH.live) + chalk.dim(' live'),
160
- stats: ['watching — ⌃C to stop'],
161
- }));
162
- }
163
- for await (const m of watchMessages(root, {
164
- signal: controller.signal,
165
- backfill: opts.filters.sinceMs != null,
166
- })) {
167
- const toLabel = labels.get(m.box) ?? m.toLabel;
168
- if (!matchesFilters(m, toLabel, m.box, opts.filters))
169
- continue;
170
- const msg = { ...m, toLabel };
171
- if (opts.json) {
172
- console.log(JSON.stringify(msg));
173
- continue;
174
- }
175
- const addressedToYou = self != null && m.to === self;
176
- const to = addressedToYou
177
- ? chalk.yellow(`${GLYPH.ask} you`)
178
- : chalk.cyan(truncate(toLabel, 24));
179
- const text = truncate(m.text.replace(/\s+/g, ' ').trim(), 100);
180
- console.log(`${chalk.dim(clockTime(m.ts))} ${chalk.magenta(truncate(m.from, 24))} ${chalk.dim(GLYPH.stream)} ${to} ${text}`);
181
- }
182
- }
183
- finally {
184
- process.removeListener('SIGINT', onSigint);
185
- }
186
- }
187
- function senderIsBox(from, box) {
188
- if (from === box.id)
189
- return true;
190
- if (from.length >= 4 && box.id.startsWith(from))
191
- return true;
192
- return from.toLowerCase() === box.label.toLowerCase();
193
- }
194
- function renderBetween(boxes, a, b, json) {
195
- const resolveBox = (q) => {
196
- const found = boxes.find((x) => x.id === q)
197
- ?? boxes.find((x) => x.id.startsWith(q))
198
- ?? boxes.find((x) => x.label.toLowerCase().includes(q.toLowerCase()));
199
- if (!found)
200
- die(`No mailbox matching ${JSON.stringify(q)}. Run \`agents mailboxes\` to list boxes.`);
201
- return found;
202
- };
203
- const boxA = resolveBox(a);
204
- const boxB = resolveBox(b);
205
- if (boxA.id === boxB.id)
206
- die('--between needs two different boxes.');
207
- const thread = [
208
- ...boxB.messages.filter((m) => senderIsBox(senderOf(m), boxA)).map((m) => ({
209
- from: senderOf(m), to: boxB.id, toLabel: boxB.label, ts: m.ts, text: m.text, state: m.state, box: boxB.id,
210
- })),
211
- ...boxA.messages.filter((m) => senderIsBox(senderOf(m), boxB)).map((m) => ({
212
- from: senderOf(m), to: boxA.id, toLabel: boxA.label, ts: m.ts, text: m.text, state: m.state, box: boxA.id,
213
- })),
214
- ].sort((x, y) => (x.ts < y.ts ? -1 : x.ts > y.ts ? 1 : 0));
215
- if (json) {
216
- console.log(JSON.stringify({
217
- a: { id: boxA.id, label: boxA.label },
218
- b: { id: boxB.id, label: boxB.label },
219
- count: thread.length,
220
- messages: thread,
221
- }, null, 2));
222
- return;
223
- }
224
- const span = thread.length >= 2
225
- ? humanDuration(Math.max(0, Date.parse(thread[thread.length - 1].ts) - Date.parse(thread[0].ts)))
226
- : '0s';
227
- console.log(` ${chalk.magenta(boxA.label)} ${chalk.dim(GLYPH.thread)} ${chalk.cyan(boxB.label)}` +
228
- chalk.dim(` ${thread.length} message${thread.length === 1 ? '' : 's'} · ${span}`));
229
- if (thread.length === 0) {
230
- console.log(chalk.dim(' No messages between these boxes yet. Sender stamps match on box id or label.'));
231
- return;
232
- }
233
- console.log();
234
- for (const m of thread) {
235
- const when = chalk.dim(relTime(m.ts).padStart(10));
236
- const route = `${chalk.magenta(truncate(m.from, 24))} ${chalk.dim(GLYPH.route)} ${chalk.cyan(truncate(m.toLabel, 24))}`;
237
- console.log(` ${when} ${STATE_TAG[m.state]} ${route}`);
238
- console.log(` ${truncate(m.text.replace(/\s+/g, ' ').trim(), 100)}`);
239
- }
240
- }
241
- async function runGcCommand(opts) {
242
- const sessions = await getActiveSessions();
243
- const activeBoxIds = new Set(sessions.map(mailboxIdForActiveSession).filter((id) => !!id));
244
- const result = gcMailbox(activeBoxIds);
245
- if (opts.json) {
246
- console.log(JSON.stringify(result, null, 2));
247
- return;
248
- }
249
- if (result.messagesDroppedDead === 0 && result.messagesDroppedExpired === 0) {
250
- console.log(chalk.dim(`gc: ${result.boxesScanned} boxes scanned, no pending messages dropped.`));
251
- return;
252
- }
253
- console.log(chalk.yellow(`gc: ${result.messagesDroppedDead} dead-box messages, ${result.messagesDroppedExpired} expired messages dropped ` +
254
- `(${result.boxesScanned} boxes scanned, ${result.deadBoxes} dead boxes).`));
255
- }
256
- function renderGraph(boxes, filters, json) {
257
- const nonEmpty = boxes.filter((b) => b.messages.length > 0);
258
- const msgs = aggregate(nonEmpty).filter((m) => matchesFilters(m, m.toLabel, m.box, filters));
259
- const edges = graphEdges(msgs);
260
- if (json) {
261
- console.log(JSON.stringify(edges, null, 2));
262
- return;
263
- }
264
- console.log(masthead({
265
- title: 'fleet comms',
266
- host: os.hostname(),
267
- accent: 'cyan',
268
- right: `${edges.length} route${edges.length === 1 ? '' : 's'}`,
269
- stats: [`${msgs.length} messages`],
270
- }));
271
- console.log();
272
- if (edges.length === 0) {
273
- console.log(chalk.dim(' No cross-box routes yet.'));
274
- return;
275
- }
276
- for (const e of edges) {
277
- const route = ` ${chalk.magenta(truncate(e.from, 28))} ${chalk.dim('└─▶')} ${chalk.cyan(truncate(e.to, 40))}`;
278
- const dots = '.'.repeat(Math.max(2, 76 - visibleWidth(route)));
279
- console.log(`${route} ${chalk.dim(dots)} ${e.count}`);
280
- }
281
- }
282
- function renderBox(box) {
283
- const dot = box.live ? chalk.green(`${GLYPH.live} live`) : chalk.dim(`${GLYPH.idle} not running`);
284
- console.log(chalk.bold(box.label) + ' ' + dot);
285
- console.log(chalk.dim(box.id));
286
- if (box.messages.length === 0) {
287
- console.log(chalk.dim(' (empty)'));
288
- return;
289
- }
290
- console.log();
291
- for (const m of box.messages) {
292
- const when = chalk.dim(relTime(m.ts));
293
- console.log(` ${STATE_TAG[m.state]} ${chalk.magenta(senderOf(m))} ${when}${m.blockId ? chalk.dim(` block ${m.blockId.slice(0, 12)}`) : ''}`);
294
- console.log(` ${truncate(m.text.replace(/\s+/g, ' ').trim(), 200)}`);
295
- }
296
- }
297
- function lastTs(box) {
298
- if (box.messages.length === 0)
299
- return 0;
300
- const t = Date.parse(newestMessage(box).ts);
301
- return Number.isNaN(t) ? 0 : t;
302
- }
303
- function newestMessage(box) {
304
- return box.messages.reduce((a, b) => (a.ts >= b.ts ? a : b));
305
- }
306
- export function registerMailboxesCommand(program) {
307
- const cmd = program
308
- .command('mailboxes')
309
- .alias('mailbox')
310
- .argument('[id]', 'A mailbox id (session UUID / teams agentId) to inspect in full')
311
- .description('Fleet comms — boxes, live cross-box traffic, threads, and routes across the agent mailbox spool')
312
- .option('--json', 'Output as JSON (NDJSON stream with --watch)')
313
- .option('-n, --limit <n>', 'Max recent messages in the overview log', '20')
314
- .option('-f, --watch', 'Live tail: stream new cross-box messages until Ctrl-C')
315
- .option('--between <boxes...>', 'Thread view: every message between two boxes (id or label), either direction')
316
- .option('--from <agent>', 'Only messages whose sender contains <agent>')
317
- .option('--to <agent>', 'Only messages to boxes whose id or label contains <agent>')
318
- .option('--since <dur>', 'Only messages newer than <dur> (30s/5m/2h/7d or ISO date); with --watch, backfills the window')
319
- .option('--graph', 'Who-talks-to-whom adjacency, busiest first')
320
- .action(async (id, opts) => {
321
- const root = getMailboxRootDir();
322
- const limit = Math.max(1, Number.parseInt(opts.limit ?? '20', 10) || 20);
323
- const filters = buildFilters(opts);
324
- if (opts.between && opts.between.length !== 2) {
325
- die(`--between takes exactly two boxes: \`agents mailboxes --between <a> <b>\`.`);
326
- }
327
- const viewCount = (id ? 1 : 0) + (opts.between ? 1 : 0) + (opts.graph ? 1 : 0);
328
- if (opts.watch && viewCount > 0) {
329
- die('--watch streams the whole fleet and combines with no other view. Drop <id>/--between/--graph, or use --from/--to/--since to filter the stream.');
330
- }
331
- if (!opts.watch && viewCount > 1) {
332
- die('Pick one view: <id>, --between, or --graph.');
333
- }
334
- if (opts.watch) {
335
- await runWatch(root, { json: opts.json, filters });
336
- return;
337
- }
338
- const boxes = await collectBoxes(root);
339
- if (opts.between) {
340
- renderBetween(boxes, opts.between[0], opts.between[1], opts.json);
341
- return;
342
- }
343
- if (opts.graph) {
344
- renderGraph(boxes, filters, opts.json);
345
- return;
346
- }
347
- if (id) {
348
- if (!isValidMailboxId(id))
349
- die(`Invalid mailbox id ${JSON.stringify(id)}.`);
350
- const box = boxes.find((b) => b.id === id) ?? boxes.find((b) => b.id.startsWith(id));
351
- if (!box)
352
- die(`No mailbox ${JSON.stringify(id)} under ${root}.`);
353
- if (opts.json) {
354
- console.log(JSON.stringify(box, null, 2));
355
- return;
356
- }
357
- renderBox(box);
358
- return;
359
- }
360
- if (opts.json) {
361
- console.log(JSON.stringify(boxes.map((b) => {
362
- const messages = hasFilters(filters)
363
- ? b.messages.filter((m) => matchesFilters({ from: senderOf(m), ts: m.ts }, b.label, b.id, filters))
364
- : b.messages;
365
- return {
366
- id: b.id,
367
- label: b.label,
368
- live: b.live,
369
- pending: messages.filter((m) => m.state !== 'consumed').length,
370
- total: messages.length,
371
- messages,
372
- };
373
- }), null, 2));
374
- return;
375
- }
376
- renderOverview(boxes, limit, filters);
377
- });
378
- const gcCmd = cmd
379
- .command('prune')
380
- .alias('gc')
381
- .description('Run a liveness sweep: archive pending messages in dead boxes and prune stale consumed mail.')
382
- .option('--json', 'Emit the GC result as JSON')
383
- .action(async (_opts, command) => runGcCommand({ json: command.optsWithGlobals().json === true }));
384
- setHelpSections(gcCmd, {
385
- examples: `
386
- # One-shot sweep using the live session set as the liveness source
387
- agents mailboxes prune
388
-
389
- # Machine-readable summary (for scripts)
390
- agents mailboxes prune --json
391
- `,
392
- notes: `
393
- A box is considered dead when no live session (the same source
394
- \`agents sessions --active\` uses) owns it. Pending messages in dead boxes
395
- are archived as \`dropped: dead\`; expired messages in live boxes are
396
- archived as \`dropped: expired\'. Both surfaces a failure receipt back to
397
- the feed store when the message carried a blockId.
398
- `,
399
- });
400
- }
@@ -1,2 +0,0 @@
1
- import type { Command } from 'commander';
2
- export declare function registerMessageCommand(program: Command): void;
@@ -1,259 +0,0 @@
1
- import chalk from 'chalk';
2
- import { spawn } from 'child_process';
3
- import { die } from '../lib/format.js';
4
- import { parseDuration } from '../lib/hooks/cache.js';
5
- import { getActiveSessions, isSessionIdLiveOnProcessTable } from '../lib/session/active.js';
6
- import { getTaskById, updateTaskStatus } from '../lib/cloud/store.js';
7
- import { resolveProvider } from '../lib/cloud/registry.js';
8
- import { mailboxDir, enqueue } from '../lib/mailbox.js';
9
- import { getAgentsInvocation } from '../lib/daemon/daemon.js';
10
- import { resolveTaskRef } from '../lib/hosts/tasks.js';
11
- import { reconcileRunningTasks } from '../lib/hosts/reconcile.js';
12
- import { resolveMessageTarget, mailboxIdForActiveSession, decideHostTaskRoute, } from '../lib/mailbox-target.js';
13
- import { blockIdForSession, listBlocks, readBlock, recordAnswer, recordMessageReceipt, } from '../lib/feed/feed.js';
14
- import { verifyOperatorIdentity } from '../lib/operator.js';
15
- import { resolveAnswerRoute, resumeArgv, } from '../lib/answer-router.js';
16
- import { injectIntoTerminal } from '../lib/terminal/index.js';
17
- import { setHelpSections } from '../lib/help.js';
18
- function findOpenBlockForMailbox(mailboxId) {
19
- const direct = readBlock(blockIdForSession(mailboxId));
20
- if (direct && direct.mailboxId === mailboxId)
21
- return direct;
22
- return listBlocks().find((b) => b.mailboxId === mailboxId);
23
- }
24
- function findSessionForMailbox(mailboxId, sessions) {
25
- return sessions.find((s) => mailboxIdForActiveSession(s) === mailboxId);
26
- }
27
- function claimBlockAnswer(block, opts) {
28
- if (!block)
29
- return;
30
- const operatorId = opts.as;
31
- const verified = verifyOperatorIdentity(operatorId);
32
- const claim = recordAnswer(block.blockId, {
33
- answeredBy: opts.from,
34
- answeredFrom: opts.surface || 'cli',
35
- operatorId,
36
- verified,
37
- });
38
- if (!claim.ok) {
39
- if ('unauthorized' in claim) {
40
- die(`Not authorized: ${claim.reason}`);
41
- }
42
- const who = claim.existing.answeredFrom + (claim.existing.answeredBy ? ` (${claim.existing.answeredBy})` : '');
43
- die(`This question was already answered by ${who}.`);
44
- }
45
- }
46
- async function deliverViaMailbox(mailboxId, text, block, opts) {
47
- const msgId = enqueue(mailboxDir(mailboxId), {
48
- to: mailboxId,
49
- text,
50
- from: opts.from,
51
- blockId: block?.blockId,
52
- ttlSeconds: opts.ttlSeconds,
53
- });
54
- if (block) {
55
- recordMessageReceipt(block.blockId, {
56
- msgId,
57
- status: 'queued',
58
- at: new Date().toISOString(),
59
- from: opts.from,
60
- });
61
- console.log(chalk.green(`Queued message ${msgId} for ${mailboxId}. `) +
62
- chalk.dim(`Answer tied to ${block.blockId}; the agent will see it at its next tool call.`));
63
- }
64
- else {
65
- console.log(chalk.green(`Queued message ${msgId} for ${mailboxId}. `) +
66
- chalk.dim('The agent will see it at its next tool call.'));
67
- }
68
- }
69
- async function deliverViaInject(route, mailboxId) {
70
- if (!route.inject || route.payload == null) {
71
- die(`Internal error: inject route missing target/payload for ${mailboxId}.`);
72
- }
73
- const result = await injectIntoTerminal(route.inject, route.payload, {
74
- enter: true,
75
- combined: false,
76
- });
77
- if (!result.ok) {
78
- die(`Failed to inject answer into ${route.inject.backend}: ${result.error ?? 'unknown error'}`);
79
- }
80
- console.log(chalk.green(`Answered ${mailboxId} via ${route.inject.backend}. `) +
81
- chalk.dim(route.reason));
82
- }
83
- async function deliverViaResume(route, mailboxId) {
84
- if (route.kind !== 'resume') {
85
- die(`Internal error: resume route incomplete for ${mailboxId}.`);
86
- }
87
- const argv = resumeArgv(route);
88
- const inv = getAgentsInvocation(argv);
89
- const child = spawn(inv.command, inv.args, {
90
- stdio: 'inherit',
91
- env: process.env,
92
- });
93
- const code = await new Promise((resolve) => {
94
- child.on('exit', (c) => resolve(c ?? 1));
95
- child.on('error', () => resolve(1));
96
- });
97
- if (code !== 0) {
98
- die(`Resume of ${mailboxId} exited with code ${code}. Tried: agents ${argv.join(' ')}`);
99
- }
100
- console.log(chalk.green(`Resumed ${mailboxId} with answer. `) +
101
- chalk.dim(route.reason));
102
- }
103
- async function deliverViaHostReroute(route, text, opts) {
104
- const argv = ['message', route.remoteRef, text, '--device', route.host];
105
- if (opts.from)
106
- argv.push('--from', opts.from);
107
- if (opts.as)
108
- argv.push('--as', opts.as);
109
- if (opts.surface)
110
- argv.push('--surface', opts.surface);
111
- if (opts.ttl)
112
- argv.push('--ttl', opts.ttl);
113
- const inv = getAgentsInvocation(argv);
114
- const child = spawn(inv.command, inv.args, { stdio: 'inherit', env: process.env });
115
- const code = await new Promise((resolve) => {
116
- child.on('exit', (c) => resolve(c ?? 1));
117
- child.on('error', () => resolve(1));
118
- });
119
- if (code !== 0) {
120
- die(`Delivery to '${route.remoteRef}' on host '${route.host}' exited with code ${code}. ` +
121
- `Tried: agents ${argv.join(' ')}`);
122
- }
123
- }
124
- const CONTROL_PLANE_NOTES = `
125
- Planes (do not mix them up):
126
- message / sessions inject - CONTROL a running agent (mailbox answer, terminal keystroke, or resume by runtime)
127
- send - DELIVER a message to a human recipient over a channel provider
128
- feed post - RECORD progress / milestones (optional broadcast may call send)
129
-
130
- <text> here is consumed BY THE TARGET AGENT (an answer, a keystroke, or the
131
- argument to a resume) -- it is not a notification a person reads on their
132
- phone. To reach the operator instead, use \`agents send --to owner\`
133
- (or a feed.broadcast \`channel:\` sink).
134
- `;
135
- export function registerMessageCommand(program) {
136
- const messageCmd = program
137
- .command('message <target> <text>')
138
- .description('Send a message to a running or parked agent (mailbox / terminal-select / resume by runtime).')
139
- .option('--from <who>', 'Label recorded as the sender of this message')
140
- .option('--as <operator>', 'Verified operator id answering a high-consequence block')
141
- .option('--surface <surface>', 'Surface that is sending this answer (feed, terminal, etc.)', 'cli')
142
- .option('--ttl <dur>', 'Delivery TTL if the message is not consumed (e.g. 30m, 1h, 24h); 0 disables expiry');
143
- setHelpSections(messageCmd, { notes: CONTROL_PLANE_NOTES });
144
- messageCmd.action(async (target, text, opts) => {
145
- if (!target.trim()) {
146
- die('Target must be a session/agent id or cloud task id. Run `agents sessions --active` to list running agents.');
147
- }
148
- let ttlSeconds;
149
- if (opts.ttl !== undefined) {
150
- const parsed = parseDuration(opts.ttl);
151
- if (parsed == null) {
152
- die(`Invalid --ttl ${JSON.stringify(opts.ttl)}: expected a duration like 30m, 1h, 24h, or 0.`);
153
- }
154
- ttlSeconds = parsed;
155
- }
156
- const sessions = await getActiveSessions();
157
- const res = resolveMessageTarget(target, sessions, (id) => getTaskById(id) != null);
158
- switch (res.kind) {
159
- case 'cloud': {
160
- const task = getTaskById(res.id);
161
- const provider = resolveProvider(task.provider);
162
- try {
163
- await provider.message(res.id, text);
164
- updateTaskStatus(res.id, 'running');
165
- console.log(chalk.green(`Message sent to cloud task ${res.id}. Agent is continuing.`));
166
- }
167
- catch (err) {
168
- die(err.message);
169
- }
170
- return;
171
- }
172
- case 'local': {
173
- try {
174
- const block = findOpenBlockForMailbox(res.id);
175
- const session = findSessionForMailbox(res.id, sessions);
176
- const route = resolveAnswerRoute({
177
- mailboxId: res.id,
178
- answer: text,
179
- block,
180
- session,
181
- });
182
- if (route.kind === 'refuse') {
183
- die(route.reason);
184
- }
185
- claimBlockAnswer(block, opts);
186
- if (route.kind === 'mailbox') {
187
- await deliverViaMailbox(res.id, text, block, { from: opts.from, ttlSeconds });
188
- return;
189
- }
190
- if (route.kind === 'tmux' || route.kind === 'iterm') {
191
- await deliverViaInject(route, res.id);
192
- if (block) {
193
- recordMessageReceipt(block.blockId, {
194
- msgId: `inject-${Date.now()}`,
195
- status: 'queued',
196
- at: new Date().toISOString(),
197
- from: opts.from,
198
- });
199
- }
200
- return;
201
- }
202
- if (route.kind === 'resume') {
203
- await deliverViaResume(route, res.id);
204
- return;
205
- }
206
- die(`Unknown delivery route: ${route.kind}`);
207
- }
208
- catch (err) {
209
- die(err.message);
210
- }
211
- return;
212
- }
213
- case 'ambiguous': {
214
- const lines = res.candidates.map((c) => ` ${c.id} ${chalk.dim(c.label)}`).join('\n');
215
- die(`"${target}" matches ${res.candidates.length} running agents:\n${lines}\nRe-run with a full id.`);
216
- return;
217
- }
218
- case 'none': {
219
- if (await isSessionIdLiveOnProcessTable(target)) {
220
- try {
221
- const block = findOpenBlockForMailbox(target);
222
- const route = resolveAnswerRoute({
223
- mailboxId: target,
224
- answer: text,
225
- block,
226
- session: null,
227
- });
228
- if (route.kind === 'refuse')
229
- die(route.reason);
230
- claimBlockAnswer(block, opts);
231
- if (route.kind === 'mailbox') {
232
- await deliverViaMailbox(target, text, block, { from: opts.from, ttlSeconds });
233
- return;
234
- }
235
- die(`Live process carries --session-id ${target} but needs a ${route.kind} rail ` +
236
- `that is unavailable without an active-session row. Retry after the session ` +
237
- `reappears in \`agents sessions --active\`, or inject into its terminal directly.`);
238
- }
239
- catch (err) {
240
- die(err.message);
241
- }
242
- return;
243
- }
244
- const onDisk = resolveTaskRef(target);
245
- const hostRoute = decideHostTaskRoute(onDisk ? reconcileRunningTasks([onDisk])[0] : null, target);
246
- if (hostRoute.kind === 'reroute') {
247
- await deliverViaHostReroute(hostRoute, text, opts);
248
- return;
249
- }
250
- if (hostRoute.kind === 'finished') {
251
- die(`Task '${target}' on host '${hostRoute.host}' already ${hostRoute.status}` +
252
- (hostRoute.exitCode !== undefined ? ` (exit ${hostRoute.exitCode})` : '') +
253
- `. Nothing to message. View its output: \`agents logs ${target}\`.`);
254
- }
255
- die(`No running agent or cloud task matches "${target}". List targets with \`agents sessions --active\` or \`agents devices ps\`.`);
256
- }
257
- }
258
- });
259
- }
@@ -1,6 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type MaterializationReceipt } from '../lib/agent-spec/index.js';
3
- import { PORTABLE_HARNESSES } from '../lib/packages/output-home.js';
4
- export { PORTABLE_HARNESSES };
5
- export type { MaterializationReceipt };
6
- export declare function registerPortablePackageCommands(program: Command): void;