@phnx-labs/agents-cli 1.22.121 → 1.22.122

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 (70) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +6 -45
  3. package/dist/cli/command-registry.js +0 -2
  4. package/dist/commands/daemon.js +7 -8
  5. package/dist/commands/mailboxes.js +1 -1
  6. package/dist/commands/projects.js +3 -3
  7. package/dist/commands/setup-mine.js +0 -1
  8. package/dist/commands/sync.js +101 -1
  9. package/dist/lib/daemon/daemon.js +1 -16
  10. package/dist/lib/daemon-services.d.ts +1 -1
  11. package/dist/lib/daemon-services.js +0 -5
  12. package/dist/lib/daemon-webhooks.d.ts +1 -1
  13. package/dist/lib/daemon-webhooks.js +1 -1
  14. package/dist/lib/device-config.js +1 -1
  15. package/dist/lib/github/project-prs.js +2 -2
  16. package/dist/lib/hosts/passthrough.js +0 -1
  17. package/dist/lib/plugins/plugins.d.ts +7 -1
  18. package/dist/lib/plugins/plugins.js +26 -5
  19. package/dist/lib/pr-land-detach.js +2 -2
  20. package/dist/lib/refresh.js +4 -1
  21. package/dist/lib/scheduling/routines.d.ts +1 -1
  22. package/dist/lib/scheduling/routines.js +1 -1
  23. package/dist/lib/session/db.d.ts +1 -1
  24. package/dist/lib/session/db.js +51 -28
  25. package/dist/lib/staleness/index.js +12 -0
  26. package/dist/lib/staleness/types.d.ts +5 -0
  27. package/dist/lib/startup/command-registry.js +1 -1
  28. package/dist/lib/state.d.ts +0 -3
  29. package/dist/lib/state.js +0 -6
  30. package/dist/lib/sync-delete.d.ts +21 -0
  31. package/dist/lib/sync-delete.js +113 -0
  32. package/package.json +1 -3
  33. package/dist/commands/monitors.d.ts +0 -2
  34. package/dist/commands/monitors.js +0 -1070
  35. package/dist/lib/daemon/monitor-engine-service.d.ts +0 -13
  36. package/dist/lib/daemon/monitor-engine-service.js +0 -25
  37. package/dist/lib/monitors/config.d.ts +0 -77
  38. package/dist/lib/monitors/config.js +0 -405
  39. package/dist/lib/monitors/dispatch.d.ts +0 -10
  40. package/dist/lib/monitors/dispatch.js +0 -72
  41. package/dist/lib/monitors/engine.d.ts +0 -45
  42. package/dist/lib/monitors/engine.js +0 -243
  43. package/dist/lib/monitors/fingerprint.d.ts +0 -3
  44. package/dist/lib/monitors/fingerprint.js +0 -43
  45. package/dist/lib/monitors/pid-watch.d.ts +0 -4
  46. package/dist/lib/monitors/pid-watch.js +0 -14
  47. package/dist/lib/monitors/remote.d.ts +0 -31
  48. package/dist/lib/monitors/remote.js +0 -63
  49. package/dist/lib/monitors/sources/command.d.ts +0 -4
  50. package/dist/lib/monitors/sources/command.js +0 -20
  51. package/dist/lib/monitors/sources/device.d.ts +0 -3
  52. package/dist/lib/monitors/sources/device.js +0 -31
  53. package/dist/lib/monitors/sources/failure.d.ts +0 -5
  54. package/dist/lib/monitors/sources/failure.js +0 -25
  55. package/dist/lib/monitors/sources/file.d.ts +0 -4
  56. package/dist/lib/monitors/sources/file.js +0 -46
  57. package/dist/lib/monitors/sources/http.d.ts +0 -3
  58. package/dist/lib/monitors/sources/http.js +0 -25
  59. package/dist/lib/monitors/sources/index.d.ts +0 -5
  60. package/dist/lib/monitors/sources/index.js +0 -22
  61. package/dist/lib/monitors/sources/poll.d.ts +0 -1
  62. package/dist/lib/monitors/sources/poll.js +0 -1
  63. package/dist/lib/monitors/sources/types.d.ts +0 -9
  64. package/dist/lib/monitors/sources/types.js +0 -1
  65. package/dist/lib/monitors/sources/webhook.d.ts +0 -3
  66. package/dist/lib/monitors/sources/webhook.js +0 -3
  67. package/dist/lib/monitors/sources/ws.d.ts +0 -4
  68. package/dist/lib/monitors/sources/ws.js +0 -35
  69. package/dist/lib/monitors/state.d.ts +0 -51
  70. package/dist/lib/monitors/state.js +0 -221
@@ -1,1070 +0,0 @@
1
- import chalk from 'chalk';
2
- import { withAliases } from '../lib/verbs.js';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
5
- import * as yaml from 'yaml';
6
- import { isDaemonRunning, signalDaemonReload, startDaemon, RedirectedHomeDaemonError, } from '../lib/daemon/daemon.js';
7
- import { findDuplicateMonitor, monitorFingerprint } from '../lib/monitors/fingerprint.js';
8
- import { gatherFleetMonitors, NO_MONITOR_FANOUT_ENV } from '../lib/monitors/remote.js';
9
- import { listMonitors, readMonitor, writeMonitor, deleteMonitor, setMonitorEnabled, getMonitorPath, validateMonitor, monitorRunsOnThisDevice, requiresSingleOwner, monitorSharedInputOwner, parseInterval, } from '../lib/monitors/config.js';
10
- import { formatRelativeTime } from '../lib/session/relative-time.js';
11
- import { evaluateMonitorOnce, POLL_SOURCE_TYPES } from '../lib/monitors/engine.js';
12
- import { listFires, readState, readLiveness, resolveFireOutcome, getMonitorHistoryDir } from '../lib/monitors/state.js';
13
- import { listRuns, getLatestRun, getRunDir } from '../lib/scheduling/routines.js';
14
- import { getMonitorsDir } from '../lib/state.js';
15
- import { IS_WINDOWS } from '../lib/platform/index.js';
16
- import { safeJoin } from '../lib/paths.js';
17
- import { machineId, normalizeHost } from '../lib/machine-id.js';
18
- import { loadDevices } from '../lib/devices/registry.js';
19
- import { assertDaemonEnabled } from '../lib/device-config.js';
20
- import { setHelpSections } from '../lib/help.js';
21
- import { isPidAlive } from '../lib/session/active.js';
22
- import { PID_WATCH_EXITED_TOKEN, pidLivenessCommand } from '../lib/monitors/pid-watch.js';
23
- import { isInteractiveTerminal, requireInteractiveSelection } from './utils.js';
24
- function stdoutJson(payload) {
25
- process.stdout.write(JSON.stringify(payload) + '\n');
26
- }
27
- function stderrLine(message) {
28
- process.stderr.write(message + '\n');
29
- }
30
- function sourceLabel(source) {
31
- switch (source.type) {
32
- case 'command':
33
- case 'poll':
34
- return `${source.type}: ${source.command ?? ''}${source.interval ? ` @${source.interval}` : ''}`;
35
- case 'poll-http':
36
- return `poll-http: ${source.url ?? ''} @${source.interval ?? ''}`;
37
- case 'ws':
38
- return `ws: ${source.wsUrl ?? ''}`;
39
- case 'file':
40
- return `file: ${source.path ?? ''}`;
41
- case 'device':
42
- return `device: ${source.device ?? ''}`;
43
- case 'webhook':
44
- return `on ${source.webhook?.source}:${source.webhook?.event}`;
45
- default:
46
- return source.type;
47
- }
48
- }
49
- function warnMissingPostcondition(action) {
50
- if ((action.type === 'run' || action.type === 'routine') && !action.postcondition) {
51
- stderrLine(chalk.yellow(` Note: ${action.type} has no --postcondition — a completed agent that did nothing will still record as ok. Add --postcondition '<cmd>' that exits 0 when the intended effect happened.`));
52
- }
53
- }
54
- function fireOutcomeDisplay(name, f) {
55
- const rec = resolveFireOutcome(name, f);
56
- if (rec.ok)
57
- return { label: chalk.green('ok'), note: '' };
58
- if (rec.effect === 'none') {
59
- const note = rec.error ? chalk.gray(` ${rec.error}`) : '';
60
- return { label: chalk.yellow('no effect'), note };
61
- }
62
- const corrected = f.ok !== false && rec.runStatus
63
- ? chalk.yellow(` (run ${rec.runStatus})`)
64
- : '';
65
- return { label: chalk.red('failed') + corrected, note: '' };
66
- }
67
- function actionLabel(action) {
68
- switch (action.type) {
69
- case 'run':
70
- return `run ${action.agent ?? ''}`;
71
- case 'routine':
72
- return `routine ${action.routine ?? ''}`;
73
- case 'notify':
74
- return `notify ${action.notifyChannel ?? 'owner'}`;
75
- case 'webhook-out':
76
- return `webhook-out ${action.url ?? ''}`;
77
- default:
78
- return action.type;
79
- }
80
- }
81
- function ownerLabel(monitor) {
82
- if (monitor.device)
83
- return monitor.device;
84
- if (monitor.devices && monitor.devices.length > 0)
85
- return monitor.devices.join(',');
86
- if (requiresSingleOwner(monitor)) {
87
- const owner = monitorSharedInputOwner();
88
- return owner ? `${owner} (owner)` : 'unowned — set interactive.host';
89
- }
90
- return 'all';
91
- }
92
- function builtinTag(monitor) {
93
- return monitor.scope === 'system' ? chalk.gray(' (built-in)') : '';
94
- }
95
- function remoteLivenessNote(d) {
96
- if (!d)
97
- return chalk.gray('—');
98
- if (d.enabled === false)
99
- return chalk.gray('paused');
100
- if (d.stalled)
101
- return chalk.red('STALLED');
102
- if (d.lastActionFailed)
103
- return chalk.red('ACTION FAILED');
104
- if (d.lastFiredAt)
105
- return chalk.green(`fired ${formatRelativeTime(d.lastFiredAt)}`);
106
- if (typeof d.checkCount === 'number' && d.checkCount > 0)
107
- return chalk.gray(`checked ${d.checkCount}x`);
108
- if (d.lastCheckedAt)
109
- return chalk.gray(`checked ${formatRelativeTime(d.lastCheckedAt)}`);
110
- return chalk.yellow('never polled');
111
- }
112
- function fleetReachNote(fleet) {
113
- if (fleet.discoveryFailed) {
114
- stderrLine(chalk.yellow(' Note: could not reach the device registry — the fleet was not checked, only this device is shown.'));
115
- }
116
- else if (fleet.skipped.length > 0) {
117
- stderrLine(chalk.yellow(` Note: could not reach ${fleet.skipped.length} device(s): ${fleet.skipped.join(', ')} — their monitors are not shown.`));
118
- }
119
- }
120
- function remoteMonitorJsonRow(r) {
121
- const d = r.display;
122
- return {
123
- machine: r.machine,
124
- name: r.monitor.name,
125
- enabled: d?.enabled ?? null,
126
- source: r.monitor.source,
127
- condition: r.monitor.condition,
128
- action: r.monitor.action,
129
- owner: d?.owner ?? null,
130
- scope: d?.scope ?? null,
131
- builtin: d?.scope === 'system',
132
- runsHere: false,
133
- lastSeenAt: null,
134
- lastFiredAt: d?.lastFiredAt ?? null,
135
- lastCheckedAt: d?.lastCheckedAt ?? null,
136
- checkCount: d?.checkCount ?? 0,
137
- lastError: null,
138
- consecutiveErrors: 0,
139
- stalled: d?.stalled ?? false,
140
- lastActionStatus: null,
141
- lastActionFailed: d?.lastActionFailed ?? false,
142
- };
143
- }
144
- function monitorIntervalMs(monitor) {
145
- if (monitor.source.interval)
146
- return parseInterval(monitor.source.interval) ?? 60_000;
147
- return 60_000;
148
- }
149
- function isStalled(monitor, liveness) {
150
- if (!monitor.enabled || !monitorRunsOnThisDevice(monitor))
151
- return false;
152
- if (!liveness)
153
- return false;
154
- const staleAfter = Math.max(monitorIntervalMs(monitor) * 3, 90_000);
155
- return Date.now() - new Date(liveness.lastCheckedAt).getTime() > staleAfter;
156
- }
157
- function livenessLabel(monitor, state, liveness) {
158
- const here = monitorRunsOnThisDevice(monitor);
159
- if (!monitor.enabled)
160
- return chalk.gray('paused');
161
- if (!here) {
162
- return state?.lastFiredAt ? chalk.gray(`fired ${formatRelativeTime(state.lastFiredAt)}`) : chalk.gray('owned elsewhere');
163
- }
164
- if (!liveness)
165
- return chalk.yellow('never polled');
166
- if (isStalled(monitor, liveness)) {
167
- return chalk.red(`STALLED — last poll ${formatRelativeTime(liveness.lastCheckedAt)}`);
168
- }
169
- const checkedAgo = formatRelativeTime(liveness.lastCheckedAt);
170
- if (liveness.lastError) {
171
- return chalk.red(`checked ${liveness.checkCount}x · error: ${liveness.lastError.replace(/\s+/g, ' ').slice(0, 60)}`);
172
- }
173
- const latestFire = listFires(monitor.name).at(-1);
174
- if (latestFire) {
175
- const outcome = resolveFireOutcome(monitor.name, latestFire);
176
- if (!outcome.ok) {
177
- return chalk.red(`ACTION FAILED ${formatRelativeTime(latestFire.firedAt)}`) + chalk.gray(` · checked ${liveness.checkCount}x`);
178
- }
179
- }
180
- if (state?.lastFiredAt) {
181
- return chalk.green(`fired ${formatRelativeTime(state.lastFiredAt)}`) + chalk.gray(` · checked ${liveness.checkCount}x`);
182
- }
183
- return chalk.gray(`checked ${liveness.checkCount}x · last ${checkedAgo} · no match yet`);
184
- }
185
- function ensureDaemonRunning() {
186
- try {
187
- assertDaemonEnabled();
188
- }
189
- catch (err) {
190
- stderrLine(chalk.yellow(err.message));
191
- return false;
192
- }
193
- if (isDaemonRunning()) {
194
- signalDaemonReload();
195
- stderrLine(chalk.gray('Daemon reloaded'));
196
- return true;
197
- }
198
- let result;
199
- try {
200
- result = startDaemon();
201
- }
202
- catch (err) {
203
- if (err instanceof RedirectedHomeDaemonError) {
204
- stderrLine(chalk.yellow(err.message));
205
- return true;
206
- }
207
- throw err;
208
- }
209
- if (result.pid) {
210
- console.log(chalk.green(`Daemon started (PID: ${result.pid}). It will watch monitors in the background.`));
211
- console.log(chalk.gray('Disable only monitor polling with: agents daemon services disable monitors'));
212
- }
213
- else {
214
- stderrLine(chalk.yellow('Could not start the daemon. Start it manually with: agents daemon start'));
215
- }
216
- return true;
217
- }
218
- async function assertEnginePickup(monitor) {
219
- const pollSource = POLL_SOURCE_TYPES.has(monitor.source.type);
220
- if (!monitor.enabled || !monitorRunsOnThisDevice(monitor) || !pollSource)
221
- return;
222
- const before = readLiveness(monitor.name);
223
- const baseline = before?.checkCount ?? 0;
224
- const deadline = Date.now() + 12_000;
225
- stderrLine(chalk.gray(' waiting for the engine to poll it…'));
226
- while (Date.now() < deadline) {
227
- await new Promise((r) => setTimeout(r, 500));
228
- const now = readLiveness(monitor.name);
229
- if (now && now.checkCount > baseline) {
230
- console.log(chalk.green(` engine picked it up — first poll ${formatRelativeTime(now.lastCheckedAt)}`));
231
- if (now.lastError) {
232
- stderrLine(chalk.yellow(` note: that poll errored — ${now.lastError.replace(/\s+/g, ' ').slice(0, 80)}`));
233
- }
234
- return;
235
- }
236
- }
237
- stderrLine(chalk.yellow(` the engine has not polled '${monitor.name}' yet.`));
238
- stderrLine(chalk.yellow(` confirm the daemon is running (agents routines status) and re-check with: agents monitors view ${monitor.name}`));
239
- }
240
- async function validateDevice(name) {
241
- const normalized = normalizeHost(name.trim());
242
- if (!normalized) {
243
- stderrLine(chalk.red('device name must be non-empty'));
244
- process.exit(1);
245
- }
246
- const registry = await loadDevices();
247
- const registered = new Set(Object.keys(registry).map((k) => normalizeHost(k)));
248
- if (!registered.has(normalized)) {
249
- stderrLine(chalk.red(`Unknown device: ${normalized}`));
250
- stderrLine(chalk.gray(`Registered: ${[...registered].sort().join(', ') || '(none)'}`));
251
- stderrLine(chalk.gray('Enroll devices with: agents devices sync'));
252
- process.exit(1);
253
- }
254
- return normalized;
255
- }
256
- function buildSource(options, name) {
257
- const chosen = [];
258
- if (options.watch)
259
- chosen.push({ type: 'command', source: { type: 'command', command: options.watch } });
260
- if (options.watchPid) {
261
- const pid = Number(options.watchPid);
262
- if (!Number.isInteger(pid) || pid < 1) {
263
- stderrLine(chalk.red(`--watch-pid must be a positive integer pid, got '${options.watchPid}'`));
264
- process.exit(1);
265
- }
266
- if (!isPidAlive(pid) && !options.force) {
267
- stderrLine(chalk.red(`Process ${pid} is not running — there is nothing to watch.`));
268
- stderrLine(chalk.gray('Pass --force to arm it anyway (e.g. the pid is about to be spawned by a concurrent step).'));
269
- process.exit(1);
270
- }
271
- const seenRunningMarkerPath = path.join(getMonitorHistoryDir(name), 'pid-watch-seen-running');
272
- chosen.push({ type: 'command', source: { type: 'command', command: pidLivenessCommand(pid, seenRunningMarkerPath) } });
273
- }
274
- if (options.poll) {
275
- chosen.push({ type: 'poll', source: { type: 'poll', command: options.poll[0], interval: options.poll[1] } });
276
- }
277
- if (options.pollHttp) {
278
- chosen.push({
279
- type: 'poll-http',
280
- source: { type: 'poll-http', url: options.pollHttp[0], interval: options.pollHttp[1] },
281
- });
282
- }
283
- if (options.ws)
284
- chosen.push({ type: 'ws', source: { type: 'ws', wsUrl: options.ws } });
285
- if (options.watchFile)
286
- chosen.push({ type: 'file', source: { type: 'file', path: options.watchFile } });
287
- if (options.watchDevice) {
288
- chosen.push({ type: 'device', source: { type: 'device', device: options.watchDevice } });
289
- }
290
- if (options.on) {
291
- const raw = String(options.on);
292
- const [src, event] = raw.includes(':') ? raw.split(':', 2) : ['github', raw];
293
- if (src !== 'github' && src !== 'linear') {
294
- stderrLine(chalk.red('--on source must be github or linear'));
295
- process.exit(1);
296
- }
297
- const webhook = { source: src, event };
298
- if (options.repo)
299
- webhook.repo = options.repo;
300
- if (options.branch)
301
- webhook.branch = options.branch;
302
- if (options.action)
303
- webhook.action = options.action;
304
- if (options.teamKey)
305
- webhook.teamKey = options.teamKey;
306
- if (options.label)
307
- webhook.label = options.label;
308
- chosen.push({ type: 'webhook', source: { type: 'webhook', webhook } });
309
- }
310
- if (chosen.length === 0) {
311
- stderrLine(chalk.red('A source is required: --watch, --watch-pid, --poll, --poll-http, --ws, --watch-file, --watch-device, or --on'));
312
- process.exit(1);
313
- }
314
- if (chosen.length > 1) {
315
- stderrLine(chalk.red(`Exactly one source is allowed; got ${chosen.map((c) => c.type).join(', ')}`));
316
- process.exit(1);
317
- }
318
- return chosen[0].source;
319
- }
320
- function buildCondition(options) {
321
- const modes = [];
322
- if (options.onChange)
323
- modes.push('on-change');
324
- if (options.match)
325
- modes.push('match');
326
- if (options.every)
327
- modes.push('every');
328
- if (modes.length > 1) {
329
- stderrLine(chalk.red('--on-change, --match, and --every are mutually exclusive'));
330
- process.exit(1);
331
- }
332
- if (options.watchPid && modes.length === 0) {
333
- return { mode: 'match', match: PID_WATCH_EXITED_TOKEN };
334
- }
335
- const mode = modes[0] ?? (options.match ? 'match' : 'on-change');
336
- const condition = { mode };
337
- if (options.match)
338
- condition.match = options.match;
339
- if (options.dedupeKey)
340
- condition.dedupeKey = options.dedupeKey;
341
- return condition;
342
- }
343
- function buildAction(options) {
344
- const chosen = [];
345
- if (options.run) {
346
- const action = { type: 'run', agent: options.run, prompt: options.prompt };
347
- if (options.mode)
348
- action.mode = options.mode;
349
- if (options.effort)
350
- action.effort = options.effort;
351
- if (options.actionTimeout)
352
- action.timeout = options.actionTimeout;
353
- if (options.postcondition)
354
- action.postcondition = options.postcondition;
355
- chosen.push(action);
356
- }
357
- if (options.routine) {
358
- const action = { type: 'routine', routine: options.routine };
359
- if (options.postcondition)
360
- action.postcondition = options.postcondition;
361
- chosen.push(action);
362
- }
363
- if (options.notify !== undefined) {
364
- const channel = typeof options.notify === 'string' ? options.notify : undefined;
365
- chosen.push({ type: 'notify', ...(channel ? { notifyChannel: channel } : {}) });
366
- }
367
- if (options.webhookOut)
368
- chosen.push({ type: 'webhook-out', url: options.webhookOut });
369
- if (chosen.length === 0) {
370
- stderrLine(chalk.red('An action is required: --run <agent> --prompt, --routine, --notify, or --webhook-out'));
371
- process.exit(1);
372
- }
373
- if (chosen.length > 1) {
374
- stderrLine(chalk.red(`Exactly one action is allowed; got ${chosen.map((c) => c.type).join(', ')}`));
375
- process.exit(1);
376
- }
377
- if (options.postcondition && chosen[0].type !== 'run' && chosen[0].type !== 'routine') {
378
- stderrLine(chalk.red('--postcondition only applies to --run or --routine'));
379
- process.exit(1);
380
- }
381
- return chosen[0];
382
- }
383
- async function pickMonitor(message, alternatives = []) {
384
- const monitors = listMonitors();
385
- if (monitors.length === 0) {
386
- stderrLine(chalk.yellow('No monitors configured'));
387
- return null;
388
- }
389
- if (!isInteractiveTerminal()) {
390
- requireInteractiveSelection(message.replace(/:$/, ''), alternatives);
391
- }
392
- try {
393
- const { select } = await import('@inquirer/prompts');
394
- return await select({
395
- message,
396
- choices: monitors.map((m) => ({
397
- value: m.name,
398
- name: `${m.name} ${chalk.gray(`(${sourceLabel(m.source)} → ${actionLabel(m.action)})`)}`,
399
- })),
400
- });
401
- }
402
- catch (err) {
403
- if (err instanceof Error && (err.name === 'ExitPromptError' || err.message.includes('User force closed'))) {
404
- stderrLine(chalk.gray('Cancelled'));
405
- return null;
406
- }
407
- throw err;
408
- }
409
- }
410
- async function guardAgainstDuplicateMonitor(config, force) {
411
- if (force)
412
- return;
413
- const existing = listMonitors();
414
- const sameName = existing.find((m) => m.name === config.name);
415
- if (sameName) {
416
- stderrLine(chalk.red(`Monitor '${config.name}' already exists — adding would overwrite it.`));
417
- stderrLine(chalk.gray(` Inspect it: agents monitors view ${config.name}`));
418
- stderrLine(chalk.gray(` Replace it: agents monitors add ${config.name} ... --force`));
419
- process.exit(1);
420
- }
421
- const duplicate = findDuplicateMonitor(config, existing);
422
- if (duplicate) {
423
- stderrLine(chalk.red(`Monitor '${duplicate}' already watches this exact source and fires the same action.`));
424
- stderrLine(chalk.gray(' Adding it again would fire the same trigger twice.'));
425
- stderrLine(chalk.gray(` Inspect it: agents monitors view ${duplicate}`));
426
- stderrLine(chalk.gray(` Add anyway: agents monitors add ${config.name} ... --force`));
427
- process.exit(1);
428
- }
429
- if (process.env[NO_MONITOR_FANOUT_ENV])
430
- return;
431
- const mine = monitorFingerprint(config);
432
- const fleet = await gatherFleetMonitors({ againstFingerprint: mine });
433
- const clash = fleet.monitors.find((r) => monitorFingerprint(r.monitor) === mine);
434
- if (clash) {
435
- stderrLine(chalk.red(`Monitor '${clash.monitor.name}' on ${chalk.bold(clash.machine)} already watches this exact source and fires the same action.`));
436
- stderrLine(chalk.gray(' Two boxes watching one work item is a double trigger.'));
437
- stderrLine(chalk.gray(` Inspect it: agents ssh ${clash.machine} 'agents monitors view ${clash.monitor.name}'`));
438
- stderrLine(chalk.gray(` Add anyway: agents monitors add ${config.name} ... --force`));
439
- process.exit(1);
440
- }
441
- if (fleet.discoveryFailed) {
442
- stderrLine(chalk.yellow(' Note: could not reach the device registry — the fleet was not checked for duplicates.'));
443
- }
444
- else if (fleet.skipped.length > 0) {
445
- stderrLine(chalk.yellow(` Note: could not check ${fleet.skipped.join(', ')} — a duplicate there would not have been caught.`));
446
- }
447
- }
448
- export function registerMonitorsCommands(program) {
449
- const monitorsCmd = program
450
- .command('monitors')
451
- .description('Durable event-triggered watchers: watch a source, detect a change, fire an action. The daemon auto-starts on first add unless daemon.enabled is false.');
452
- setHelpSections(monitorsCmd, {
453
- examples: `
454
- # CI went red → triage it (poll a command, diff, fire an agent)
455
- agents monitors add ci-red \\
456
- --poll 'gh pr checks 1119 --json name,bucket' 30s --match 'fail' \\
457
- --run claude --prompt 'CI failed on #1119: {event}. Diagnose and fix.' \\
458
- --device yosemite-s0
459
-
460
- # Merge-on-green: the fire is ok only if the PR actually merged
461
- agents monitors add merge-1682 \\
462
- --poll 'gh pr view 1682 --json state --jq .state' 2m --match OPEN \\
463
- --run claude --prompt 'Rebase-merge #1682: {event}' \\
464
- --postcondition 'gh pr view 1682 --json state --jq .state | grep -qx MERGED'
465
-
466
- # SSL cert issued → notify (poll an HTTPS endpoint every 8h)
467
- agents monitors add cert-issued \\
468
- --poll-http 'https://secure.ssl.com/team/.../co-ec1l5dgjofa' 8h \\
469
- --match 'issued' --notify --device zion
470
-
471
- # Dry-run: evaluate the source once and show what it would emit (no action)
472
- agents monitors test ci-red
473
-
474
- # A fleet box going loaded → spin up an agent
475
- agents monitors add box-loaded --watch-device yosemite-s0 --match loaded \\
476
- --run claude --prompt 'yosemite-s0 is loaded: {event}. Investigate.'
477
-
478
- # A backgrounded shell that will never exit on its own (a watch loop, gh pr
479
- # checks --watch, a long sleep) — arm a REAL watcher instead of trusting the
480
- # harness's own exit hook (which only fires when the process dies):
481
- agents monitors add pr-checks-1234 --watch-pid 48213 \\
482
- --run claude --prompt 'PID 48213 exited: {event}. Resume and check the result.'
483
- `,
484
- notes: `
485
- A monitor is a routine whose trigger is a watched SOURCE instead of a clock.
486
- It has three parts:
487
- - SOURCE (--watch, --watch-pid, --poll, --poll-http, --ws, --watch-file, --watch-device, --on)
488
- - CONDITION (--on-change [default], --match <re>, --every; --dedupe-key)
489
- - ACTION (--run <agent> --prompt, --routine, --notify, --webhook-out)
490
- --postcondition <cmd> on --run/--routine asserts the effect
491
- happened (exit 0) after the agent settles; otherwise the
492
- fire records as "no effect", not ok.
493
-
494
- The fired event is injected into a run/routine prompt as {event}.
495
- Pin the single OWNER device with --device (exactly-once). The daemon (shared
496
- with routines) auto-starts on first add unless daemon.enabled is false on this
497
- device; manage it with 'agents daemon start|stop' (or 'agents routines start|stop').
498
-
499
- v1 evaluates poll sources (command, poll, poll-http, file, device). Push
500
- sources (ws, webhook) are accepted but delivered through a receiver wired in
501
- a follow-up.
502
-
503
- --watch-pid <pid> refuses to arm (fails loud) when the pid is already dead —
504
- a "will re-invoke me" watcher pointed at a corpse never fires. It defaults
505
- the condition to fire on exit, unlike a raw --watch which defaults to
506
- on-change.
507
- `,
508
- });
509
- monitorsCmd
510
- .command('add [nameOrPath]')
511
- .description('Create a monitor from inline flags or a YAML file. Auto-starts the daemon unless daemon.enabled is false.')
512
- .option('--watch <cmd>', 'Run a shell command; its stdout is the observation')
513
- .option('--watch-pid <pid>', 'Watch a backgrounded process for exit — a reliable, daemon-polled alternative to a harness exit hook. Fails loud if the pid is already gone. Defaults to firing on exit')
514
- .option('--poll <cmd...>', 'Re-run a command every interval: --poll "<cmd>" <interval> (e.g. 30s)')
515
- .option('--poll-http <url...>', 'GET a URL every interval: --poll-http <url> <interval> (e.g. 15m)')
516
- .option('--on <source:event>', 'Webhook trigger source: github:pull_request or linear:Issue')
517
- .option('--ws <url>', 'WebSocket; each frame is an observation')
518
- .option('--watch-file <path>', 'Watch a file or directory for changes')
519
- .option('--watch-device <name>', 'A fleet device becomes the source (health/reachability)')
520
- .option('--repo <owner/name>', 'GitHub repo filter for --on github:<event>')
521
- .option('--branch <name>', 'GitHub branch filter for --on github:<event>')
522
- .option('--action <name>', 'Linear action filter for --on linear:<event>')
523
- .option('--team-key <key>', 'Linear team key filter for --on linear:<event>')
524
- .option('--label <name>', 'Linear issue label filter for --on linear:Issue')
525
- .option('--on-change', 'Fire when the observation differs from last-seen (the default)')
526
- .option('--match <regex>', 'Fire when the observation matches this regex')
527
- .option('--dedupe-key <expr>', 'Regex whose first match is the "same event" signature (default: full output)')
528
- .option('--every', 'Fire on every observation (no dedupe) — rate-limit this')
529
- .option('--run <agent>', 'Spawn an agent (claude, codex, ..., or a custom harness from agents harness list) with the prompt on fire')
530
- .option('--prompt <prompt>', 'Prompt for --run; {event} is replaced with the fired event')
531
- .option('--mode <mode>', 'Execution mode for --run: plan, edit, auto, or skip')
532
- .option('--effort <effort>', 'Reasoning effort for --run: low | medium | high | xhigh | max | auto')
533
- .option('--action-timeout <t>', 'Kill the --run action if it runs longer than this (e.g. 10m)')
534
- .option('--postcondition <cmd>', 'Shell command that must exit 0 after a --run/--routine action settles; otherwise the fire records as no-effect, not ok. {event} is replaced with the fired event summary')
535
- .option('--routine <name>', 'Fire an existing routine on change')
536
- .option('--notify [channel]', 'Notify every normal-policy owner channel; [channel] selects one channel')
537
- .option('--webhook-out <url>', 'POST the event to this URL')
538
- .option('--device <name>', 'OWNER (not body placement) — the single machine that evaluates + fires (exactly-once). See docs/concepts.md#placement.')
539
- .option('--devices <list>', 'Allowlist (comma-separated): each device fires independently')
540
- .option('--run-on <host>', 'BODY placement — execute the ACTION on this machine over SSH (same idea as run --where device:<host>)')
541
- .option('--cwd <path>', "Working directory for --run, home-relative or ~/… (default: the execution target's home)")
542
- .option('--rate-limit <spec>', 'Auto-pause if it fires more than N/<interval> (e.g. 5/1m)')
543
- .option('--disabled', 'Create the monitor paused (enable later with resume)')
544
- .option('--force', 'Overwrite a same-named monitor, or add one that duplicates an existing watcher')
545
- .action(async (nameOrPath, options) => {
546
- const hasSourceFlag = Boolean(options.watch || options.watchPid || options.poll || options.pollHttp || options.on || options.ws || options.watchFile || options.watchDevice);
547
- if (!hasSourceFlag && nameOrPath && /\.ya?ml$/.test(nameOrPath) && fs.existsSync(path.resolve(nameOrPath))) {
548
- const resolved = path.resolve(nameOrPath);
549
- let parsed;
550
- try {
551
- parsed = yaml.parse(fs.readFileSync(resolved, 'utf-8'));
552
- }
553
- catch (err) {
554
- stderrLine(chalk.red(`Invalid YAML: ${err.message}`));
555
- process.exit(1);
556
- }
557
- const name = parsed?.name || path.basename(resolved).replace(/\.ya?ml$/, '');
558
- const config = { enabled: true, ...parsed, name };
559
- const errors = validateMonitor(config);
560
- if (errors.length > 0) {
561
- stderrLine(chalk.red('Validation errors:'));
562
- for (const err of errors)
563
- stderrLine(chalk.red(` - ${err}`));
564
- process.exit(1);
565
- }
566
- await guardAgainstDuplicateMonitor(config, options.force === true);
567
- writeMonitor(config);
568
- console.log(chalk.green(`Monitor '${name}' added`));
569
- warnMissingPostcondition(config.action);
570
- if (ensureDaemonRunning())
571
- await assertEnginePickup(config);
572
- return;
573
- }
574
- if (!nameOrPath) {
575
- stderrLine(chalk.red('Monitor name is required'));
576
- stderrLine(chalk.gray('Usage: agents monitors add <name> --poll "<cmd>" 30s --match fail --run claude --prompt "..."'));
577
- process.exit(1);
578
- }
579
- const source = buildSource(options, nameOrPath);
580
- if (source.type === 'device' && source.device) {
581
- source.device = await validateDevice(source.device);
582
- }
583
- const condition = buildCondition(options);
584
- const action = buildAction(options);
585
- let device;
586
- let devices;
587
- if (options.device && options.devices) {
588
- stderrLine(chalk.red('--device (single owner) and --devices (allowlist) are mutually exclusive'));
589
- process.exit(1);
590
- }
591
- if (options.device)
592
- device = await validateDevice(options.device);
593
- if (options.devices) {
594
- devices = [];
595
- for (const d of String(options.devices).split(',').map((s) => s.trim()).filter(Boolean)) {
596
- devices.push(await validateDevice(d));
597
- }
598
- }
599
- if (options.runOn && !device && !devices) {
600
- device = machineId();
601
- stderrLine(chalk.gray(`--run-on set with no --device/--devices: pinned owner to this machine (${device}).`));
602
- }
603
- let rateLimit;
604
- if (options.rateLimit) {
605
- const m = String(options.rateLimit).match(/^(\d+)\/(.+)$/);
606
- if (!m) {
607
- stderrLine(chalk.red('--rate-limit must be N/<interval>, e.g. 5/1m'));
608
- process.exit(1);
609
- }
610
- rateLimit = { max: parseInt(m[1], 10), per: m[2] };
611
- }
612
- const config = {
613
- name: nameOrPath,
614
- enabled: !options.disabled,
615
- source,
616
- condition,
617
- action,
618
- ...(device ? { device } : {}),
619
- ...(devices ? { devices } : {}),
620
- ...(options.runOn ? { runOn: options.runOn } : {}),
621
- ...(options.cwd ? { cwd: options.cwd } : {}),
622
- ...(rateLimit ? { rateLimit } : {}),
623
- };
624
- const errors = validateMonitor(config);
625
- if (errors.length > 0) {
626
- stderrLine(chalk.red('Validation errors:'));
627
- for (const err of errors)
628
- stderrLine(chalk.red(` - ${err}`));
629
- process.exit(1);
630
- }
631
- if (condition.mode === 'match' && condition.match && /^(issued|success|ok|pass(ed)?|done|ready)$/i.test(condition.match)) {
632
- stderrLine(chalk.yellow(` Note: --match '${condition.match}' only fires on success — it stays silent if the source breaks or never matches.`));
633
- }
634
- await guardAgainstDuplicateMonitor(config, options.force === true);
635
- writeMonitor(config);
636
- console.log(chalk.green(`Monitor '${nameOrPath}' added`));
637
- console.log(chalk.gray(` ${sourceLabel(source)} → [${condition.mode}] → ${actionLabel(action)} · owner: ${ownerLabel(config)}`));
638
- warnMissingPostcondition(action);
639
- if (ensureDaemonRunning())
640
- await assertEnginePickup(config);
641
- });
642
- monitorsCmd
643
- .command('list')
644
- .description('See all monitors across the fleet: source, condition, action, owner, last fire, and the box each lives on.')
645
- .option('--json', 'Emit machine-readable JSON')
646
- .option('--local', 'This device only — skip the fleet fan-out')
647
- .action(async (options) => {
648
- const self = machineId();
649
- const monitors = listMonitors();
650
- const peerMode = !!process.env[NO_MONITOR_FANOUT_ENV];
651
- const localOnly = peerMode || options.local === true;
652
- let fleet = null;
653
- if (!localOnly) {
654
- fleet = await gatherFleetMonitors();
655
- }
656
- const remote = (fleet?.monitors ?? []).filter((r) => normalizeHost(r.machine) !== self);
657
- if (options.json) {
658
- const localRows = monitors.map((m) => {
659
- const state = readState(m.name);
660
- const liveness = readLiveness(m.name);
661
- const latestFire = listFires(m.name).at(-1);
662
- const latestOutcome = latestFire ? resolveFireOutcome(m.name, latestFire) : null;
663
- return {
664
- machine: self,
665
- name: m.name,
666
- enabled: m.enabled,
667
- source: m.source,
668
- condition: m.condition,
669
- action: m.action,
670
- owner: ownerLabel(m),
671
- scope: m.scope ?? 'user',
672
- builtin: m.scope === 'system',
673
- runsHere: monitorRunsOnThisDevice(m),
674
- lastSeenAt: state?.lastSeenAt ?? null,
675
- lastFiredAt: state?.lastFiredAt ?? null,
676
- lastCheckedAt: liveness?.lastCheckedAt ?? null,
677
- checkCount: liveness?.checkCount ?? 0,
678
- lastError: liveness?.lastError ?? null,
679
- consecutiveErrors: liveness?.consecutiveErrors ?? 0,
680
- stalled: isStalled(m, liveness),
681
- lastActionStatus: latestOutcome?.runStatus ?? null,
682
- lastActionFailed: latestOutcome ? !latestOutcome.ok : false,
683
- };
684
- });
685
- stdoutJson([...localRows, ...remote.map(remoteMonitorJsonRow)]);
686
- return;
687
- }
688
- if (monitors.length === 0 && remote.length === 0) {
689
- console.log(chalk.gray('No monitors configured'));
690
- console.log(chalk.gray(' Add one: agents monitors add <name> --poll "<cmd>" 30s --match fail --run claude --prompt "..."'));
691
- if (fleet && (fleet.discoveryFailed || fleet.skipped.length > 0))
692
- fleetReachNote(fleet);
693
- return;
694
- }
695
- console.log(chalk.bold('Monitors\n'));
696
- if (monitors.length > 0) {
697
- if (remote.length > 0)
698
- console.log(chalk.gray(` ${self} (this device)`));
699
- for (const m of monitors) {
700
- const state = readState(m.name);
701
- const liveness = readLiveness(m.name);
702
- const enabled = m.enabled ? chalk.green('on') : chalk.gray('off');
703
- const here = monitorRunsOnThisDevice(m);
704
- const owner = here ? ownerLabel(m) : chalk.gray(ownerLabel(m));
705
- console.log(` ${chalk.cyan(m.name.padEnd(22))} ${enabled.padEnd(3)} ${sourceLabel(m.source)}${builtinTag(m)}`);
706
- console.log(` ${' '.repeat(22)} ${chalk.gray(`[${m.condition.mode}]`)} → ${actionLabel(m.action)} ${chalk.gray(`owner: ${owner}`)} ${livenessLabel(m, state, liveness)}`);
707
- }
708
- }
709
- const byMachine = new Map();
710
- for (const r of remote) {
711
- const key = r.machine;
712
- (byMachine.get(key) ?? byMachine.set(key, []).get(key)).push(r);
713
- }
714
- for (const machine of [...byMachine.keys()].sort()) {
715
- console.log(chalk.gray(`\n ${machine}`));
716
- for (const r of byMachine.get(machine)) {
717
- const m = r.monitor;
718
- const enabled = r.display?.enabled === false ? chalk.gray('off') : chalk.green('on');
719
- console.log(` ${chalk.cyan(m.name.padEnd(22))} ${enabled.padEnd(3)} ${sourceLabel(m.source)}${builtinTag({ scope: r.display?.scope })}`);
720
- console.log(` ${' '.repeat(22)} ${chalk.gray(`[${m.condition.mode}]`)} → ${actionLabel(m.action)} ${chalk.gray(`owner: ${r.display?.owner ?? machine}`)} ${remoteLivenessNote(r.display)}`);
721
- }
722
- }
723
- if (fleet && (fleet.discoveryFailed || fleet.skipped.length > 0))
724
- fleetReachNote(fleet);
725
- console.log();
726
- });
727
- monitorsCmd
728
- .command('view [name]')
729
- .description('Show a monitor’s full YAML config plus its current watched-state and recent fires.')
730
- .option('--json', 'Emit machine-readable JSON')
731
- .action(async (name, options) => {
732
- if (!name) {
733
- name = (await pickMonitor('Select monitor to view', ['agents monitors view <name>'])) ?? undefined;
734
- if (!name)
735
- return;
736
- }
737
- const monitor = readMonitor(name);
738
- if (!monitor) {
739
- stderrLine(chalk.red(`Monitor '${name}' not found`));
740
- process.exit(1);
741
- }
742
- const state = readState(name);
743
- const liveness = readLiveness(name);
744
- const recentFires = listFires(name).slice(-5);
745
- if (options.json) {
746
- stdoutJson({
747
- name,
748
- monitor,
749
- owner: ownerLabel(monitor),
750
- runsHere: monitorRunsOnThisDevice(monitor),
751
- state,
752
- liveness,
753
- stalled: isStalled(monitor, liveness),
754
- recentFires: recentFires.map((f) => ({ ...f, reconciled: resolveFireOutcome(name, f) })),
755
- });
756
- return;
757
- }
758
- console.log(chalk.bold(`Monitor: ${name}\n`));
759
- console.log(yaml.stringify(monitor));
760
- console.log(chalk.bold('Liveness'));
761
- console.log(` ${livenessLabel(monitor, state, liveness)}`);
762
- if (liveness) {
763
- console.log(chalk.gray(` last checked: ${liveness.lastCheckedAt} (${formatRelativeTime(liveness.lastCheckedAt)})`));
764
- console.log(chalk.gray(` checks: ${liveness.checkCount}`));
765
- if (liveness.lastError) {
766
- console.log(chalk.red(` last error: ${liveness.lastError.replace(/\s+/g, ' ').slice(0, 200)} (${liveness.consecutiveErrors} in a row)`));
767
- }
768
- }
769
- else if (monitor.enabled && monitorRunsOnThisDevice(monitor)) {
770
- console.log(chalk.yellow(' The engine has not polled this monitor yet. If this persists, the daemon may not have picked it up — check: agents routines status'));
771
- }
772
- if (state) {
773
- console.log(chalk.bold('\nWatched state'));
774
- console.log(chalk.gray(` last seen: ${state.lastSeenAt}`));
775
- if (state.lastFiredAt)
776
- console.log(chalk.gray(` last fired: ${state.lastFiredAt}`));
777
- console.log(chalk.gray(` last value: ${state.lastValue.replace(/\s+/g, ' ').slice(0, 120)}`));
778
- }
779
- if (recentFires.length > 0) {
780
- console.log(chalk.bold('\nRecent fires'));
781
- for (const f of recentFires) {
782
- const { label, note } = fireOutcomeDisplay(name, f);
783
- console.log(` ${chalk.gray(f.firedAt)} ${f.action ?? '?'} ${label}`);
784
- if (note)
785
- console.log(note);
786
- }
787
- }
788
- });
789
- monitorsCmd
790
- .command('test [name]')
791
- .description('DRY-RUN: evaluate the source once and print the emitted event + whether it would fire. No action is taken.')
792
- .option('--json', 'Emit machine-readable JSON')
793
- .action(async (name, options) => {
794
- if (!name) {
795
- name = (await pickMonitor('Select monitor to test', ['agents monitors test <name>'])) ?? undefined;
796
- if (!name)
797
- return;
798
- }
799
- const monitor = readMonitor(name);
800
- if (!monitor) {
801
- stderrLine(chalk.red(`Monitor '${name}' not found`));
802
- process.exit(1);
803
- }
804
- const { observation, decision } = await evaluateMonitorOnce(monitor);
805
- const wouldFire = Boolean(decision?.fire);
806
- if (options.json) {
807
- stdoutJson({
808
- name,
809
- dryRun: true,
810
- monitor,
811
- observation,
812
- decision,
813
- wouldFire,
814
- });
815
- return;
816
- }
817
- console.log(chalk.bold(`Dry-run: ${name}\n`));
818
- console.log(chalk.gray(` ${sourceLabel(monitor.source)} · [${monitor.condition.mode}] · ${actionLabel(monitor.action)}\n`));
819
- if (!observation) {
820
- console.log(chalk.yellow('No observation — this source is push-only (ws/webhook) or produced nothing this tick.'));
821
- return;
822
- }
823
- console.log(chalk.bold('Observation'));
824
- console.log(observation.raw.split('\n').slice(0, 20).map((l) => ` ${l}`).join('\n'));
825
- if (observation.meta)
826
- console.log(chalk.gray(` meta: ${JSON.stringify(observation.meta)}`));
827
- if (observation.failed) {
828
- console.log(chalk.yellow(` poll failed (${observation.failureReason ?? 'observation failure'}) — not a value change; skipped`));
829
- }
830
- console.log('');
831
- console.log(`Would fire: ${wouldFire ? chalk.green('yes') : chalk.gray('no')}`);
832
- if (decision?.event) {
833
- console.log(chalk.bold('\nEmitted event'));
834
- console.log(` summary: ${decision.event.summary}`);
835
- console.log(chalk.gray(` → would ${actionLabel(monitor.action)}`));
836
- }
837
- else if (!wouldFire && monitor.condition.mode === 'on-change' && !readState(name)) {
838
- console.log(chalk.gray(' (first observation establishes a baseline; a later change fires)'));
839
- }
840
- console.log(chalk.gray('\n(dry run — no action taken, no state written)'));
841
- });
842
- monitorsCmd
843
- .command('edit [name]')
844
- .description('Open a monitor’s YAML in $EDITOR.')
845
- .action(async (name) => {
846
- if (!name) {
847
- name = (await pickMonitor('Select monitor to edit', ['agents monitors edit <name>'])) ?? undefined;
848
- if (!name)
849
- return;
850
- }
851
- let monitorPath = getMonitorPath(name);
852
- if (!monitorPath) {
853
- const dir = getMonitorsDir();
854
- fs.mkdirSync(dir, { recursive: true });
855
- monitorPath = safeJoin(dir, `${name}.yml`);
856
- const builtIn = readMonitor(name);
857
- if (builtIn) {
858
- writeMonitor(builtIn);
859
- console.log(chalk.gray(`Editing a copy of built-in monitor '${name}' in your user dir: ${monitorPath}`));
860
- }
861
- else {
862
- const template = yaml.stringify({
863
- name,
864
- source: { type: 'poll', command: 'echo hello', interval: '1m' },
865
- condition: { mode: 'on-change' },
866
- action: { type: 'notify' },
867
- });
868
- fs.writeFileSync(monitorPath, template, 'utf-8');
869
- console.log(chalk.gray(`Created new monitor file: ${monitorPath}`));
870
- }
871
- }
872
- const editor = process.env.EDITOR || process.env.VISUAL || (IS_WINDOWS ? 'notepad' : 'vi');
873
- const parts = editor.split(/\s+/).filter(Boolean);
874
- const { spawn } = await import('child_process');
875
- const child = spawn(parts[0], [...parts.slice(1), monitorPath], { stdio: 'inherit' });
876
- child.on('close', (code) => {
877
- if (code !== 0)
878
- return;
879
- const monitor = readMonitor(name);
880
- if (!monitor)
881
- return;
882
- const errors = validateMonitor(monitor);
883
- if (errors.length > 0) {
884
- stderrLine(chalk.yellow('\nWarning: monitor has validation errors:'));
885
- for (const err of errors)
886
- stderrLine(chalk.yellow(` - ${err}`));
887
- }
888
- else {
889
- console.log(chalk.green(`\nMonitor '${name}' saved`));
890
- if (isDaemonRunning()) {
891
- signalDaemonReload();
892
- stderrLine(chalk.gray('Daemon reloaded'));
893
- }
894
- }
895
- });
896
- });
897
- monitorsCmd
898
- .command('logs [name]')
899
- .description('Show the latest action run’s status + report. --run for a specific run, --full for raw stdout.')
900
- .option('-r, --run <runId>', 'Show a specific action run instead of the latest')
901
- .option('-m, --full', 'Show the full raw stdout stream')
902
- .action(async (name, options) => {
903
- if (!name) {
904
- name = (await pickMonitor('Select monitor to view logs', ['agents monitors logs <name>'])) ?? undefined;
905
- if (!name)
906
- return;
907
- }
908
- const run = options.run ? listRuns(name).find((r) => r.runId === options.run) : getLatestRun(name);
909
- if (!run) {
910
- stderrLine(chalk.yellow(`No action runs found for monitor '${name}'`));
911
- stderrLine(chalk.gray(' (notify / webhook-out actions have no run log — see: agents monitors runs)'));
912
- return;
913
- }
914
- const logPath = path.join(getRunDir(name, run.runId), 'stdout.log');
915
- if (options.full) {
916
- if (!fs.existsSync(logPath)) {
917
- stderrLine(chalk.yellow(`Log not found: ${logPath}`));
918
- return;
919
- }
920
- console.log(chalk.gray(`Run: ${run.runId}\n`));
921
- console.log(fs.readFileSync(logPath, 'utf-8'));
922
- return;
923
- }
924
- const statusColor = run.status === 'completed' ? chalk.green : run.status === 'running' ? chalk.yellow : chalk.red;
925
- console.log(chalk.bold(name) + chalk.gray(` run ${run.runId}`));
926
- console.log(statusColor(run.status) + chalk.gray(` ${run.startedAt}`));
927
- console.log(chalk.gray('─'.repeat(60)));
928
- const reportPath = path.join(getRunDir(name, run.runId), 'report.md');
929
- if (fs.existsSync(reportPath)) {
930
- console.log(fs.readFileSync(reportPath, 'utf-8').trimEnd());
931
- }
932
- else if (fs.existsSync(logPath)) {
933
- console.log(fs.readFileSync(logPath, 'utf-8').split('\n').slice(-40).join('\n').trimEnd());
934
- }
935
- else {
936
- console.log(chalk.gray('(no output captured)'));
937
- }
938
- });
939
- monitorsCmd
940
- .command('runs [name]')
941
- .description('See a monitor’s fire history: when it fired, the action, and the outcome.')
942
- .action(async (name) => {
943
- if (!name) {
944
- name = (await pickMonitor('Select monitor to view fires', ['agents monitors runs <name>'])) ?? undefined;
945
- if (!name)
946
- return;
947
- }
948
- const fires = listFires(name);
949
- if (fires.length === 0) {
950
- stderrLine(chalk.yellow(`No fires recorded for monitor '${name}'`));
951
- return;
952
- }
953
- console.log(chalk.bold(`Fire history: ${name}\n`));
954
- for (const f of fires.slice(-20)) {
955
- const { label, note } = fireOutcomeDisplay(name, f);
956
- const runRef = f.runId ? chalk.gray(` run ${f.runId}`) : '';
957
- console.log(` ${f.firedAt} ${(f.action ?? '?').padEnd(12)} ${label}${runRef}`);
958
- console.log(chalk.gray(` ${f.summary.slice(0, 100)}`));
959
- if (note)
960
- console.log(note);
961
- }
962
- });
963
- monitorsCmd
964
- .command('pause [name]')
965
- .description('Temporarily disable a monitor. Stops watching until resumed.')
966
- .action(async (name) => {
967
- if (!name) {
968
- name = (await pickMonitor('Select monitor to pause', ['agents monitors pause <name>'])) ?? undefined;
969
- if (!name)
970
- return;
971
- }
972
- try {
973
- setMonitorEnabled(name, false);
974
- console.log(chalk.green(`Monitor '${name}' paused`));
975
- if (isDaemonRunning())
976
- signalDaemonReload();
977
- }
978
- catch (err) {
979
- stderrLine(chalk.red(err.message));
980
- process.exit(1);
981
- }
982
- });
983
- monitorsCmd
984
- .command('resume [name]')
985
- .description('Re-enable a paused monitor so the daemon watches it again.')
986
- .action(async (name) => {
987
- if (!name) {
988
- name = (await pickMonitor('Select monitor to resume', ['agents monitors resume <name>'])) ?? undefined;
989
- if (!name)
990
- return;
991
- }
992
- try {
993
- setMonitorEnabled(name, true);
994
- console.log(chalk.green(`Monitor '${name}' resumed`));
995
- if (isDaemonRunning())
996
- signalDaemonReload();
997
- }
998
- catch (err) {
999
- stderrLine(chalk.red(err.message));
1000
- process.exit(1);
1001
- }
1002
- });
1003
- monitorsCmd
1004
- .command('device [name]')
1005
- .description('View or (re)pin the OWNER device — the single machine that evaluates + fires (exactly-once).')
1006
- .option('--set <name>', 'Pin the owner to this device (strict fleet validation)')
1007
- .option('--clear', 'Remove the owner pin so the monitor runs on every device')
1008
- .action(async (name, options) => {
1009
- if (options.set !== undefined && options.clear) {
1010
- stderrLine(chalk.red('--set and --clear are mutually exclusive'));
1011
- process.exit(1);
1012
- }
1013
- if (!name) {
1014
- name = (await pickMonitor('Select monitor', ['agents monitors device <name> --set X'])) ?? undefined;
1015
- if (!name)
1016
- return;
1017
- }
1018
- const monitor = readMonitor(name);
1019
- if (!monitor) {
1020
- stderrLine(chalk.red(`Monitor '${name}' not found`));
1021
- process.exit(1);
1022
- }
1023
- if (options.clear) {
1024
- monitor.device = undefined;
1025
- monitor.devices = undefined;
1026
- writeMonitor(monitor);
1027
- console.log(chalk.green(`Owner cleared for '${name}' — evaluates on every device`));
1028
- if (isDaemonRunning())
1029
- signalDaemonReload();
1030
- return;
1031
- }
1032
- if (options.set !== undefined) {
1033
- const device = await validateDevice(options.set);
1034
- monitor.device = device;
1035
- monitor.devices = undefined;
1036
- writeMonitor(monitor);
1037
- console.log(chalk.green(`Owner for '${name}' set to: ${device}`));
1038
- if (isDaemonRunning())
1039
- signalDaemonReload();
1040
- return;
1041
- }
1042
- console.log(`Owner for '${name}': ${chalk.cyan(ownerLabel(monitor))}`);
1043
- console.log(chalk.gray(' Re-pin with: agents monitors device ' + name + ' --set <device>'));
1044
- });
1045
- withAliases(monitorsCmd
1046
- .command('remove [name]'), 'remove')
1047
- .description('Delete a monitor. Stops watching; past fire history remains on disk.')
1048
- .action(async (name) => {
1049
- if (!name) {
1050
- name = (await pickMonitor('Select monitor to remove', ['agents monitors remove <name>'])) ?? undefined;
1051
- if (!name)
1052
- return;
1053
- }
1054
- if (deleteMonitor(name)) {
1055
- console.log(chalk.green(`Monitor '${name}' removed`));
1056
- if (isDaemonRunning()) {
1057
- signalDaemonReload();
1058
- stderrLine(chalk.gray('Daemon reloaded'));
1059
- }
1060
- }
1061
- else if (readMonitor(name)) {
1062
- stderrLine(chalk.red(`Monitor '${name}' is a built-in and can't be removed; pause it with: agents monitors pause ${name}`));
1063
- process.exit(1);
1064
- }
1065
- else {
1066
- stderrLine(chalk.red(`Monitor '${name}' not found`));
1067
- process.exit(1);
1068
- }
1069
- });
1070
- }