@phnx-labs/agents-cli 1.23.28 → 1.23.29

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 +4 -0
  2. package/README.md +33 -82
  3. package/dist/bootstrap.js +0 -17
  4. package/dist/cli/command-registry.js +0 -2
  5. package/dist/commands/cloud.js +0 -58
  6. package/dist/commands/config.js +0 -4
  7. package/dist/commands/daemon-index.js +1 -1
  8. package/dist/commands/daemon.js +14 -63
  9. package/dist/commands/doctor.js +0 -12
  10. package/dist/commands/events.js +1 -1
  11. package/dist/commands/feed.d.ts +1 -3
  12. package/dist/commands/feed.js +1 -6
  13. package/dist/commands/fleet-capture.js +2 -4
  14. package/dist/commands/focus.d.ts +0 -1
  15. package/dist/commands/focus.js +2 -4
  16. package/dist/commands/inspect.d.ts +1 -19
  17. package/dist/commands/inspect.js +8 -474
  18. package/dist/commands/mine.js +1 -1
  19. package/dist/commands/prune.js +2 -64
  20. package/dist/commands/ps-roster.d.ts +0 -4
  21. package/dist/commands/ps-roster.js +2 -30
  22. package/dist/commands/ps.js +1 -4
  23. package/dist/commands/repo.d.ts +1 -1
  24. package/dist/commands/repo.js +4 -4
  25. package/dist/commands/sessions-browser.d.ts +0 -2
  26. package/dist/commands/sessions-browser.js +2 -32
  27. package/dist/commands/sessions-optimize.js +3 -4
  28. package/dist/commands/setup-mine.js +0 -1
  29. package/dist/commands/ssh.js +8 -9
  30. package/dist/commands/sync.js +1 -1
  31. package/dist/commands/update.js +2 -2
  32. package/dist/commands/watchdog.js +3 -4
  33. package/dist/lib/accounting/rotate.d.ts +0 -2
  34. package/dist/lib/accounting/rotate.js +1 -4
  35. package/dist/lib/agent-spec/agents.d.ts +0 -1
  36. package/dist/lib/agent-spec/agents.js +0 -8
  37. package/dist/lib/auth-health.d.ts +0 -1
  38. package/dist/lib/auth-health.js +0 -3
  39. package/dist/lib/cli-entry.d.ts +0 -1
  40. package/dist/lib/cli-entry.js +0 -36
  41. package/dist/lib/cloud/types.d.ts +0 -2
  42. package/dist/lib/config-keys.d.ts +1 -1
  43. package/dist/lib/config-keys.js +1 -4
  44. package/dist/lib/daemon/daemon.d.ts +0 -4
  45. package/dist/lib/daemon/daemon.js +6 -202
  46. package/dist/lib/daemon/heartbeat-service.d.ts +1 -1
  47. package/dist/lib/daemon/heartbeat-service.js +1 -8
  48. package/dist/lib/daemon-services.d.ts +1 -1
  49. package/dist/lib/daemon-services.js +1 -11
  50. package/dist/lib/device-config.d.ts +0 -2
  51. package/dist/lib/device-config.js +4 -22
  52. package/dist/lib/devices/config-migration.js +1 -3
  53. package/dist/lib/exec.d.ts +2 -5
  54. package/dist/lib/exec.js +18 -18
  55. package/dist/lib/factory/snapshot.d.ts +0 -5
  56. package/dist/lib/factory/snapshot.js +1 -28
  57. package/dist/lib/feed/events.d.ts +1 -11
  58. package/dist/lib/feed/events.js +0 -20
  59. package/dist/lib/feed/feed.d.ts +0 -2
  60. package/dist/lib/feed-outcome.d.ts +0 -2
  61. package/dist/lib/feed-outcome.js +0 -5
  62. package/dist/lib/fleet/capture.d.ts +0 -1
  63. package/dist/lib/fleet/capture.js +0 -3
  64. package/dist/lib/fleet/manifest.js +0 -6
  65. package/dist/lib/fleet/types.d.ts +0 -1
  66. package/dist/lib/harness/adapter.d.ts +0 -7
  67. package/dist/lib/harness/adapters/claude.js +0 -18
  68. package/dist/lib/harness/adapters/codex.js +0 -10
  69. package/dist/lib/harness/adapters/cursor.js +0 -11
  70. package/dist/lib/harness/adapters/kimi.js +0 -3
  71. package/dist/lib/harness/adapters/muse.js +0 -11
  72. package/dist/lib/harness/index.d.ts +1 -1
  73. package/dist/lib/harness/index.js +0 -2
  74. package/dist/lib/hosts/passthrough.js +2 -10
  75. package/dist/lib/hosts/ready.d.ts +0 -4
  76. package/dist/lib/hosts/ready.js +0 -9
  77. package/dist/lib/hosts/reconcile.d.ts +0 -1
  78. package/dist/lib/hosts/reconcile.js +0 -8
  79. package/dist/lib/installations/migrate.d.ts +0 -2
  80. package/dist/lib/installations/migrate.js +0 -145
  81. package/dist/lib/loop.js +1 -2
  82. package/dist/lib/menubar/snapshot.d.ts +0 -1
  83. package/dist/lib/menubar/snapshot.js +1 -4
  84. package/dist/lib/placement.d.ts +1 -2
  85. package/dist/lib/placement.js +4 -24
  86. package/dist/lib/profiles.d.ts +0 -1
  87. package/dist/lib/profiles.js +0 -6
  88. package/dist/lib/session/active.d.ts +1 -3
  89. package/dist/lib/session/active.js +0 -4
  90. package/dist/lib/session/db.d.ts +0 -1
  91. package/dist/lib/session/db.js +4 -8
  92. package/dist/lib/session/discover.d.ts +0 -1
  93. package/dist/lib/session/discover.js +3 -128
  94. package/dist/lib/session/live-metadata.js +0 -2
  95. package/dist/lib/session/presentation.d.ts +0 -1
  96. package/dist/lib/session/presentation.js +3 -8
  97. package/dist/lib/session/selection.d.ts +0 -2
  98. package/dist/lib/session/selection.js +2 -12
  99. package/dist/lib/staleness/detectors/commands.d.ts +1 -1
  100. package/dist/lib/staleness/detectors/hooks.d.ts +1 -1
  101. package/dist/lib/staleness/detectors/mcp.d.ts +1 -1
  102. package/dist/lib/staleness/detectors/permissions.d.ts +1 -1
  103. package/dist/lib/staleness/detectors/plugins.d.ts +1 -1
  104. package/dist/lib/staleness/detectors/rules.d.ts +1 -1
  105. package/dist/lib/staleness/detectors/skills.d.ts +1 -1
  106. package/dist/lib/staleness/detectors/subagents.d.ts +1 -1
  107. package/dist/lib/staleness/detectors/workflows.d.ts +1 -1
  108. package/dist/lib/staleness/writers/commands.d.ts +1 -1
  109. package/dist/lib/staleness/writers/hooks.d.ts +1 -1
  110. package/dist/lib/staleness/writers/mcp.d.ts +1 -1
  111. package/dist/lib/staleness/writers/permissions.d.ts +1 -1
  112. package/dist/lib/staleness/writers/plugins.d.ts +1 -1
  113. package/dist/lib/staleness/writers/rules.d.ts +1 -1
  114. package/dist/lib/staleness/writers/skills.d.ts +1 -1
  115. package/dist/lib/staleness/writers/subagents.d.ts +1 -1
  116. package/dist/lib/staleness/writers/workflows.d.ts +1 -1
  117. package/dist/lib/startup/command-registry.js +5 -2
  118. package/dist/lib/state.d.ts +0 -3
  119. package/dist/lib/state.js +2 -25
  120. package/dist/lib/types.d.ts +0 -1
  121. package/dist/lib/watchdog/runner.d.ts +0 -2
  122. package/dist/lib/watchdog/runner.js +0 -2
  123. package/package.json +1 -1
  124. package/scripts/postinstall.js +2 -2
  125. package/dist/commands/routines.d.ts +0 -14
  126. package/dist/commands/routines.js +0 -2149
  127. package/dist/commands/routines.test-fixture.d.ts +0 -52
  128. package/dist/commands/routines.test-fixture.js +0 -254
  129. package/dist/lib/catchup.d.ts +0 -19
  130. package/dist/lib/catchup.js +0 -83
  131. package/dist/lib/daemon/catchup-service.d.ts +0 -18
  132. package/dist/lib/daemon/catchup-service.js +0 -21
  133. package/dist/lib/daemon/runner.d.ts +0 -91
  134. package/dist/lib/daemon/runner.js +0 -1927
  135. package/dist/lib/harness/adapters/droid.d.ts +0 -2
  136. package/dist/lib/harness/adapters/droid.js +0 -14
  137. package/dist/lib/overdue.d.ts +0 -9
  138. package/dist/lib/overdue.js +0 -74
  139. package/dist/lib/routine-activation.d.ts +0 -13
  140. package/dist/lib/routine-activation.js +0 -117
  141. package/dist/lib/routine-context.d.ts +0 -59
  142. package/dist/lib/routine-context.js +0 -181
  143. package/dist/lib/routine-notify-owner.d.ts +0 -4
  144. package/dist/lib/routine-notify-owner.js +0 -49
  145. package/dist/lib/routine-notify.d.ts +0 -17
  146. package/dist/lib/routine-notify.js +0 -138
  147. package/dist/lib/routine-process-cleanup.d.ts +0 -9
  148. package/dist/lib/routine-process-cleanup.js +0 -81
  149. package/dist/lib/routine-readiness.d.ts +0 -31
  150. package/dist/lib/routine-readiness.js +0 -256
  151. package/dist/lib/routines-format.d.ts +0 -7
  152. package/dist/lib/routines-format.js +0 -127
  153. package/dist/lib/routines-placement.d.ts +0 -16
  154. package/dist/lib/routines-placement.js +0 -60
  155. package/dist/lib/routines-project.d.ts +0 -49
  156. package/dist/lib/routines-project.js +0 -306
  157. package/dist/lib/sandbox.d.ts +0 -15
  158. package/dist/lib/sandbox.js +0 -309
  159. package/dist/lib/scheduler.d.ts +0 -23
  160. package/dist/lib/scheduler.js +0 -106
  161. package/dist/lib/scheduling/routines.d.ts +0 -264
  162. package/dist/lib/scheduling/routines.js +0 -1292
  163. package/dist/lib/triggers/webhook.d.ts +0 -26
  164. package/dist/lib/triggers/webhook.js +0 -181
@@ -1,2149 +0,0 @@
1
- import chalk from 'chalk';
2
- import ora from 'ora';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
5
- import * as yaml from 'yaml';
6
- import { isDaemonRunning, signalDaemonReload, startDaemon, readDaemonLog, getDaemonStatus, getDaemonLogPath, RedirectedHomeDaemonError, } from '../lib/daemon/daemon.js';
7
- import { isDaemonServiceEnabled, setDaemonServiceEnabled } from '../lib/daemon-services.js';
8
- import { assertSchedulerEnabled, assertDaemonEnabled, isDaemonEnabled, isSchedulerEnabled, } from '../lib/device-config.js';
9
- import { parseAgentVersionSpec, isAgentHardDeprecated, hardDeprecationError, ROUTINE_AGENT_IDS } from '../lib/agents.js';
10
- import { isCustomHarnessName } from '../lib/profiles.js';
11
- import { RUN_STRATEGIES, normalizeRunStrategy } from '../lib/accounting/rotate.js';
12
- import { formatRepoLink, REPO_DISPLAY_MAX } from '../lib/routines-format.js';
13
- import { listJobs as listAllJobs, deleteJob, readJob, validateJob, writeJob, setJobEnabled, listRuns, routineStats, getLatestRun, getRunDir, getJobPath, isCanonicalRoutineSource, parseAtTime, hasCompletedOneShotRun, isOneShotLikeSchedule, isOneShotRoutine, jobRunsOnThisDevice, checkJobDeviceEligibility, normalizeTriggerEvent, parseHostStrategy, resolveHostStrategy, HOST_STRATEGIES, computeProjectGroupKind, projectGroupKey, projectGroupTitle, projectGroupOrder, normalizeProjects, buildRoutineListJson, buildRoutineStatusRows, fireConditionLabel, nextRunForDisplay, nextRunLabel, localLatestRun, listJobsForDisplay, } from '../lib/scheduling/routines.js';
14
- export { buildRoutineListJson } from '../lib/scheduling/routines.js';
15
- import { listProjectDefs, isSafeProjectName } from '../lib/projects.js';
16
- import { evaluateActivationReadinessLive } from '../lib/routine-readiness.js';
17
- import { discoverProjectRoutines, findProjectRoutine, materialiseProjectRoutine, syncProjectRoutines, syncAllProjectRoutines, displayProjectPath, } from '../lib/routines-project.js';
18
- import { fireWebhookJobs, matchJobsToWebhook } from '../lib/triggers/webhook.js';
19
- import { getRoutinesDir } from '../lib/state.js';
20
- import { IS_WINDOWS } from '../lib/platform/index.js';
21
- import { safeJoin } from '../lib/paths.js';
22
- import { executeJob, monitorRunningJobs } from '../lib/daemon/runner.js';
23
- import { JobScheduler } from '../lib/scheduler.js';
24
- import { detectOverdueJobs } from '../lib/overdue.js';
25
- import { runCatchup } from '../lib/catchup.js';
26
- import { isInteractiveTerminal, requireInteractiveSelection } from './utils.js';
27
- import { itemPicker } from '../lib/picker.js';
28
- import { Separator } from '@inquirer/core';
29
- import { setHelpSections } from '../lib/help.js';
30
- import { loadDevices, loadDevicesSync } from '../lib/devices/registry.js';
31
- import { machineId, normalizeHost } from '../lib/machine-id.js';
32
- import { addHostOption } from '../lib/hosts/option.js';
33
- import { devicesWithRoutineEnabled } from '../lib/routine-activation.js';
34
- import { spawnSync } from 'node:child_process';
35
- import { getCliLaunch } from '../lib/cli-entry.js';
36
- export function formatRunDuration(startedAt, completedAt) {
37
- if (!completedAt)
38
- return '';
39
- const ms = Date.parse(completedAt) - Date.parse(startedAt);
40
- if (!Number.isFinite(ms) || ms < 0)
41
- return '';
42
- const sec = Math.round(ms / 1000);
43
- if (sec < 60)
44
- return ` · ${sec} sec`;
45
- const min = Math.round(sec / 60);
46
- if (min < 60)
47
- return ` · ${min} min`;
48
- const hr = Math.floor(min / 60);
49
- const rem = min % 60;
50
- return rem ? ` · ${hr} hr ${rem} min` : ` · ${hr} hr`;
51
- }
52
- function scheduleLabel(job) {
53
- let label = fireConditionLabel(job);
54
- if (isOneShotRoutine(job))
55
- label = `${label} (one-shot)`;
56
- if (job.endAt) {
57
- const end = new Date(job.endAt);
58
- const endLabel = Number.isFinite(end.getTime())
59
- ? end.toLocaleDateString()
60
- : job.endAt;
61
- label = `${label} (until ${endLabel})`;
62
- }
63
- return label;
64
- }
65
- function deviceStateLabel(name, registry) {
66
- const profile = registry[normalizeHost(name)] ?? registry[name];
67
- if (!profile)
68
- return 'unknown';
69
- if (profile.reachability?.reachable === false)
70
- return 'offline';
71
- if (profile.reachability?.reachable === true)
72
- return 'online';
73
- if (profile.tailscale?.online === false)
74
- return 'offline';
75
- if (profile.tailscale?.online === true)
76
- return 'online';
77
- return 'unknown';
78
- }
79
- function titleWithDeviceState(title, name, registry) {
80
- const state = deviceStateLabel(name, registry);
81
- return state && state !== 'online' ? `${title} (${state})` : title;
82
- }
83
- function placementTag(job) {
84
- const strategy = resolveHostStrategy(job);
85
- if (strategy === 'local')
86
- return job.host ? `->${job.host}` : '';
87
- if (strategy === 'host')
88
- return `->${job.host ?? '?'}`;
89
- if (strategy === 'fleet')
90
- return '->fleet';
91
- return '->cloud';
92
- }
93
- function deviceLabel(job, width) {
94
- const full = [devicesWithRoutineEnabled(job.name).join(','), placementTag(job)]
95
- .filter(Boolean)
96
- .join(' ');
97
- const raw = full.length === 0 ? 'all' : full;
98
- const display = width && raw.length > width
99
- ? raw.slice(0, width - 1) + '…'
100
- : raw;
101
- return { raw, display, dim: full.length === 0 || !jobRunsOnThisDevice(job) };
102
- }
103
- function groupRoutineJobsByDevice(jobs, registry, self = machineId()) {
104
- const groups = new Map();
105
- const add = (key, title, job) => {
106
- const existing = groups.get(key);
107
- if (existing) {
108
- existing.jobs.push(job);
109
- return;
110
- }
111
- groups.set(key, { key, title, jobs: [job], local: !key.startsWith('device:') });
112
- };
113
- for (const job of jobs) {
114
- const strategy = resolveHostStrategy(job);
115
- if (strategy === 'cloud') {
116
- add('cloud', 'Cloud', job);
117
- continue;
118
- }
119
- if (strategy === 'fleet') {
120
- add('fleet', 'Fleet-wide', job);
121
- continue;
122
- }
123
- if (strategy === 'host') {
124
- const host = job.host ?? 'unknown-host';
125
- add(`host:${normalizeHost(host)}`, titleWithDeviceState(`Host: ${host}`, host, registry), job);
126
- continue;
127
- }
128
- const devices = devicesWithRoutineEnabled(job.name);
129
- if (devices.length === 0) {
130
- add('disabled', 'Disabled', job);
131
- continue;
132
- }
133
- for (const device of devices) {
134
- const normalized = normalizeHost(device);
135
- if (normalized === self) {
136
- add('this-machine', `This machine (${self})`, job);
137
- }
138
- else {
139
- add(`device:${normalized}`, titleWithDeviceState(`Device: ${normalized}`, normalized, registry), job);
140
- }
141
- }
142
- }
143
- const order = (group) => {
144
- if (group.key === 'this-machine')
145
- return 0;
146
- if (group.key === 'fleet')
147
- return 1;
148
- if (group.key === 'disabled')
149
- return 2;
150
- if (group.key === 'cloud')
151
- return 3;
152
- if (group.key.startsWith('device:'))
153
- return 4;
154
- if (group.key.startsWith('host:'))
155
- return 5;
156
- return 5;
157
- };
158
- return [...groups.values()].sort((a, b) => order(a) - order(b) || a.title.localeCompare(b.title));
159
- }
160
- export function groupRoutineJobsByProject(jobs, knownProjectNames) {
161
- const groups = new Map();
162
- const add = (key, title, job) => {
163
- const existing = groups.get(key);
164
- if (existing) {
165
- existing.jobs.push(job);
166
- return;
167
- }
168
- groups.set(key, { key, title, jobs: [job], local: true });
169
- };
170
- const orderByKey = new Map();
171
- for (const job of jobs) {
172
- const group = computeProjectGroupKind(job.projects, knownProjectNames);
173
- const key = projectGroupKey(group);
174
- orderByKey.set(key, projectGroupOrder(group));
175
- add(key, projectGroupTitle(group), job);
176
- }
177
- const order = (group) => orderByKey.get(group.key) ?? 0;
178
- return [...groups.values()].sort((a, b) => order(a) - order(b) || a.title.localeCompare(b.title));
179
- }
180
- function collectProject(value, previous) {
181
- return previous.concat([value]);
182
- }
183
- function renderRoutineRows({ jobs, scheduler, overdueSet, link, now, local = true }) {
184
- const NAME_W = 24;
185
- const AGENT_W = 10;
186
- const REPO_W = REPO_DISPLAY_MAX;
187
- const DEVICE_W = 22;
188
- const SCHED_W = 34;
189
- const ENABLED_W = 10;
190
- const NEXT_W = 22;
191
- const header = ` ${'Name'.padEnd(NAME_W)} ${'Agent'.padEnd(AGENT_W)} ${'Repo'.padEnd(REPO_W)} ${'Devices'.padEnd(DEVICE_W)} ${'Schedule'.padEnd(SCHED_W)} ${'Enabled'.padEnd(ENABLED_W)} ${'Next Run'.padEnd(NEXT_W)} Last Status`;
192
- console.log(chalk.gray(header));
193
- console.log(chalk.gray(' ' + '-'.repeat(NAME_W + AGENT_W + REPO_W + DEVICE_W + SCHED_W + ENABLED_W + NEXT_W + 20)));
194
- for (const job of jobs) {
195
- const nextStr = nextRunLabel(job, scheduler, now);
196
- const schedStr = scheduleLabel(job);
197
- const latestRun = local ? localLatestRun(job) : null;
198
- const lastStatus = latestRun?.status || '-';
199
- const sourceRepo = job.source?.repo ?? job.repo;
200
- const sourceLabel = sourceRepo
201
- ? (job.source?.branch ? `${sourceRepo}@${job.source.branch}` : sourceRepo)
202
- : null;
203
- const repoInfo = formatRepoLink(sourceLabel ?? job.repo);
204
- const repoCell = link(repoInfo.display, repoInfo.href);
205
- const repoPadding = Math.max(0, REPO_W - repoInfo.display.length);
206
- const enabledStr = job.enabled ? chalk.green('yes') : chalk.gray('no');
207
- const enabledWord = job.enabled ? 'yes' : 'no';
208
- const enabledPad = Math.max(0, ENABLED_W - enabledWord.length);
209
- const device = deviceLabel(job, DEVICE_W);
210
- const deviceCell = device.dim ? chalk.gray(device.display) : device.display;
211
- const devicePad = Math.max(0, DEVICE_W - device.display.length);
212
- const statusColor = lastStatus === 'completed' ? chalk.green
213
- : lastStatus === 'failed' ? chalk.red
214
- : lastStatus === 'timeout' ? chalk.yellow
215
- : lastStatus === 'missed' ? chalk.magenta
216
- : chalk.gray;
217
- const overdueTag = overdueSet.has(job.name) ? chalk.yellow(' (overdue)') : '';
218
- const reason = latestRun ? runFailureReason(latestRun) : null;
219
- const reasonTag = reason ? chalk.gray(` — ${reason}`) : '';
220
- const agentLabelPadded = job.command
221
- ? chalk.magenta('command'.padEnd(10))
222
- : job.workflow
223
- ? chalk.magenta(`wf:${job.workflow}`.padEnd(10))
224
- : (job.agent || '').padEnd(10);
225
- console.log(` ${chalk.cyan(job.name.padEnd(NAME_W))} ${agentLabelPadded} ${repoCell}${' '.repeat(repoPadding)} ${deviceCell}${' '.repeat(devicePad)} ${schedStr.padEnd(SCHED_W)} ${enabledStr}${' '.repeat(enabledPad)} ${chalk.gray(nextStr.padEnd(NEXT_W))} ${statusColor(lastStatus)}${overdueTag}${reasonTag}`);
226
- }
227
- }
228
- function parseRoutineTrigger(options) {
229
- const raw = typeof options.on === 'string' ? options.on : undefined;
230
- if (!raw)
231
- return undefined;
232
- const [sourceMaybe, eventMaybe] = raw.includes(':') ? raw.split(':', 2) : ['github', raw];
233
- if (sourceMaybe === 'github') {
234
- const event = normalizeTriggerEvent(eventMaybe);
235
- if (!event)
236
- throw new Error(`Unknown GitHub trigger event '${eventMaybe}'`);
237
- const trigger = { type: 'github_event', event };
238
- if (typeof options.repo === 'string')
239
- trigger.repo = options.repo;
240
- if (typeof options.branch === 'string')
241
- trigger.branch = options.branch;
242
- if (typeof options.action === 'string')
243
- trigger.action = options.action;
244
- if (typeof options.label === 'string')
245
- trigger.label = options.label;
246
- return trigger;
247
- }
248
- if (sourceMaybe === 'linear') {
249
- const trigger = { type: 'linear_event', event: eventMaybe };
250
- if (typeof options.action === 'string')
251
- trigger.action = options.action;
252
- if (typeof options.teamKey === 'string')
253
- trigger.teamKey = options.teamKey;
254
- if (typeof options.label === 'string')
255
- trigger.label = options.label;
256
- if (typeof options.stateTo === 'string')
257
- trigger.stateTo = options.stateTo;
258
- if (typeof options.stateFrom === 'string')
259
- trigger.stateFrom = options.stateFrom;
260
- return trigger;
261
- }
262
- throw new Error('--on source must be github or linear');
263
- }
264
- function ensureSchedulerRunning(opts = {}) {
265
- const log = opts.stderr ? console.error : console.log;
266
- try {
267
- assertDaemonEnabled();
268
- assertSchedulerEnabled();
269
- }
270
- catch (err) {
271
- console.error(chalk.yellow(err.message));
272
- return;
273
- }
274
- const wasServiceEnabled = isDaemonServiceEnabled('scheduler');
275
- if (!wasServiceEnabled)
276
- setDaemonServiceEnabled('scheduler', true);
277
- if (isDaemonRunning()) {
278
- const reloaded = signalDaemonReload();
279
- if (!reloaded) {
280
- console.error(chalk.yellow('Scheduler service enabled, but live reload is unavailable. Restart deliberately with: agents daemon restart'));
281
- }
282
- else if (!opts.quiet) {
283
- log(chalk.gray(wasServiceEnabled ? 'Scheduler reloaded' : 'Scheduler service enabled and reloaded'));
284
- }
285
- return;
286
- }
287
- let result;
288
- try {
289
- result = startDaemon();
290
- }
291
- catch (err) {
292
- if (err instanceof RedirectedHomeDaemonError) {
293
- if (!opts.quiet)
294
- log(chalk.yellow(err.message));
295
- return;
296
- }
297
- throw err;
298
- }
299
- if (opts.quiet)
300
- return;
301
- if (result.pid) {
302
- log(chalk.green(`Scheduler started (PID: ${result.pid}). It will run in the background and fire routines on schedule.`));
303
- log(chalk.gray(`Stop anytime with: agents routines stop`));
304
- }
305
- else {
306
- log(chalk.yellow('Could not start the scheduler. Start it manually with: agents routines start'));
307
- }
308
- }
309
- function writeJson(payload) {
310
- process.stdout.write(JSON.stringify(payload) + '\n');
311
- }
312
- function printSyncResult(sync) {
313
- console.log(chalk.bold(displayProjectPath(sync.projectRoot)));
314
- if (sync.synced.length === 0 && sync.skipped.length === 0 && sync.removed.length === 0 && sync.errors.length === 0) {
315
- console.log(chalk.gray(' (no project routines)'));
316
- }
317
- if (sync.synced.length > 0) {
318
- console.log(chalk.green(` synced: ${sync.synced.join(', ')}`));
319
- }
320
- if (sync.removed.length > 0) {
321
- console.log(chalk.gray(` removed: ${sync.removed.join(', ')}`));
322
- }
323
- for (const s of sync.skipped) {
324
- console.log(chalk.yellow(` skipped ${s.name}: ${s.reason}`));
325
- }
326
- for (const e of sync.errors) {
327
- console.log(chalk.red(` error ${e.name}: ${e.error}`));
328
- }
329
- }
330
- function runMetaJson(run) {
331
- return {
332
- jobId: run.jobName,
333
- jobName: run.jobName,
334
- runId: run.runId,
335
- status: run.status,
336
- startedAt: run.startedAt,
337
- completedAt: run.completedAt,
338
- exitCode: run.exitCode,
339
- errorMessage: run.errorMessage ?? null,
340
- duration: run.duration ?? null,
341
- };
342
- }
343
- export function buildRunsJson(runs) {
344
- return runs.map(runMetaJson);
345
- }
346
- function isPromptCancelled(err) {
347
- return (err instanceof Error &&
348
- (err.message.includes('User force closed') ||
349
- err.name === 'ExitPromptError' ||
350
- err.code === 'ERR_USE_AFTER_CLOSE'));
351
- }
352
- async function pickJob(message, filter, alternatives = [], cwd) {
353
- let jobs = listAllJobs(cwd);
354
- if (filter) {
355
- jobs = jobs.filter(filter);
356
- }
357
- if (jobs.length === 0) {
358
- console.log(chalk.yellow('No jobs available'));
359
- return null;
360
- }
361
- if (!isInteractiveTerminal()) {
362
- requireInteractiveSelection(message.replace(/:$/, ''), alternatives);
363
- }
364
- try {
365
- const { select } = await import('@inquirer/prompts');
366
- return await select({
367
- message,
368
- choices: jobs.map((job) => ({
369
- value: job.name,
370
- name: `${job.name} ${chalk.gray(`(${job.command ? 'command' : job.workflow ? `wf:${job.workflow}` : job.agent}, ${job.schedule ?? fireConditionLabel(job)})`)}`,
371
- })),
372
- });
373
- }
374
- catch (err) {
375
- if (isPromptCancelled(err)) {
376
- console.log(chalk.gray('Cancelled'));
377
- return null;
378
- }
379
- throw err;
380
- }
381
- }
382
- async function enableRoutineAction(name) {
383
- if (!name) {
384
- name = await pickJob('Select routine to enable', (job) => !job.enabled, ['agents routines enable <name>']) ?? undefined;
385
- if (!name) {
386
- const available = discoverProjectRoutines();
387
- if (available.length > 0) {
388
- console.log(chalk.gray(`Project routines available to enable: ${available.map((r) => r.name).join(', ')}`));
389
- console.log(chalk.gray(' Enable one by name: agents routines enable <name>'));
390
- }
391
- return;
392
- }
393
- }
394
- try {
395
- if (!readJob(name)) {
396
- const found = findProjectRoutine(name);
397
- if (!found) {
398
- console.log(chalk.red(`No routine named '${name}'.`));
399
- const available = discoverProjectRoutines();
400
- if (available.length > 0) {
401
- console.log(chalk.gray(` Available project routines: ${available.map((r) => r.name).join(', ')}`));
402
- }
403
- process.exit(1);
404
- }
405
- if ('ambiguous' in found) {
406
- console.log(chalk.red(`'${name}' is defined in more than one project: ${found.ambiguous.join(', ')}.`));
407
- console.log(chalk.gray(' Enable it from inside the project you want, or rename one.'));
408
- process.exit(1);
409
- }
410
- const mat = materialiseProjectRoutine(found.projectRoot, name);
411
- if ('error' in mat) {
412
- console.log(chalk.red(`Cannot enable '${name}': ${mat.error}`));
413
- process.exit(1);
414
- }
415
- console.log(chalk.gray(`Materialised '${name}' from ${displayProjectPath(found.projectRoot)}`));
416
- }
417
- const job = readJob(name);
418
- if (job) {
419
- const readiness = await evaluateActivationReadinessLive(job);
420
- if (!readiness.ready) {
421
- const r = readiness.readiness;
422
- console.log(chalk.red(`Cannot enable '${name}' — not ready: ${r.code}`));
423
- console.log(chalk.gray(` ${r.message}`));
424
- if (r.repair)
425
- console.log(chalk.gray(` repair: ${r.repair}`));
426
- console.log(chalk.gray(` fix it, then: agents routines doctor ${name} --fix`));
427
- process.exit(1);
428
- }
429
- }
430
- setJobEnabled(name, true);
431
- console.log(chalk.green(`Routine '${name}' enabled`));
432
- if (isDaemonRunning()) {
433
- signalDaemonReload();
434
- console.log(chalk.gray('Daemon reloaded'));
435
- }
436
- }
437
- catch (err) {
438
- console.log(chalk.red(err.message));
439
- process.exit(1);
440
- }
441
- }
442
- async function disableRoutineAction(name) {
443
- if (!name) {
444
- name = await pickJob('Select routine to disable', (job) => job.enabled, ['agents routines disable <name>']) ?? undefined;
445
- if (!name)
446
- return;
447
- }
448
- try {
449
- if (!readJob(name)) {
450
- console.log(chalk.red(`No routine named '${name}'.`));
451
- process.exit(1);
452
- }
453
- setJobEnabled(name, false);
454
- console.log(chalk.green(`Routine '${name}' disabled`));
455
- if (isDaemonRunning()) {
456
- signalDaemonReload();
457
- console.log(chalk.gray('Scheduler reloaded'));
458
- }
459
- }
460
- catch (err) {
461
- console.log(chalk.red(err.message));
462
- process.exit(1);
463
- }
464
- }
465
- async function parseAndValidateDevices(raw) {
466
- const names = [...new Set(raw.split(',').map((s) => s.trim()).filter(Boolean).map((s) => normalizeHost(s)))];
467
- if (names.length === 0) {
468
- console.log(chalk.red('--devices requires at least one non-empty device name'));
469
- process.exit(1);
470
- }
471
- const registry = await loadDevices();
472
- const registered = new Set(Object.keys(registry).map((k) => normalizeHost(k)));
473
- const unknown = names.filter((n) => !registered.has(n));
474
- if (unknown.length > 0) {
475
- console.log(chalk.red(`Unknown device(s): ${unknown.join(', ')}`));
476
- console.log(chalk.gray(`Registered: ${[...registered].sort().join(', ') || '(none)'}`));
477
- console.log(chalk.gray('Enroll devices with: agents devices sync'));
478
- process.exit(1);
479
- }
480
- return names;
481
- }
482
- function runRoutinesList(options) {
483
- if (options.groupBy && options.groupBy !== 'device' && options.groupBy !== 'project') {
484
- console.error(chalk.red(`Unsupported --group-by '${options.groupBy}'. Use: project (default) or device`));
485
- process.exit(1);
486
- }
487
- if (options.json) {
488
- process.stdout.write(JSON.stringify(buildRoutineListJson()) + '\n');
489
- return;
490
- }
491
- try {
492
- monitorRunningJobs();
493
- }
494
- catch { }
495
- const jobs = listJobsForDisplay(process.cwd());
496
- if (jobs.length === 0) {
497
- console.log(chalk.gray('No jobs configured'));
498
- console.log(chalk.gray(' Add a job: agents routines add <path-to-job.yml>'));
499
- return;
500
- }
501
- const scheduler = new JobScheduler(async () => { });
502
- scheduler.loadAll();
503
- const overdueSet = new Set();
504
- try {
505
- for (const j of detectOverdueJobs())
506
- overdueSet.add(j.name);
507
- }
508
- catch {
509
- }
510
- console.log(chalk.bold('Scheduled Jobs\n'));
511
- const link = (label, url) => url && process.stdout.isTTY ? `\x1b]8;;${url}\x07${label}\x1b]8;;\x07` : label;
512
- const now = new Date();
513
- if (options.flat) {
514
- renderRoutineRows({ jobs, scheduler, overdueSet, link, now });
515
- }
516
- else if (options.groupBy === 'device') {
517
- let registry = {};
518
- try {
519
- registry = loadDevicesSync();
520
- }
521
- catch (err) {
522
- console.error(chalk.yellow(`Could not read device registry: ${err.message}`));
523
- }
524
- const groups = groupRoutineJobsByDevice(jobs, registry);
525
- for (const group of groups) {
526
- console.log(chalk.bold(`\n${group.title}`));
527
- renderRoutineRows({ jobs: group.jobs, scheduler, overdueSet, link, now, local: group.local });
528
- }
529
- if (groups.some((group) => !group.local)) {
530
- console.log();
531
- console.log(chalk.gray(' Last Status is per-device: rows under another device show "-" — read it there with: agents routines list --device <name>'));
532
- }
533
- }
534
- else {
535
- const knownProjectNames = new Set(listProjectDefs().map((p) => p.name));
536
- const groups = groupRoutineJobsByProject(jobs, knownProjectNames);
537
- for (const group of groups) {
538
- console.log(chalk.bold(`\n${group.title}`));
539
- renderRoutineRows({ jobs: group.jobs, scheduler, overdueSet, link, now });
540
- }
541
- }
542
- if (overdueSet.size > 0) {
543
- console.log();
544
- console.log(chalk.yellow(` ${overdueSet.size} routine(s) overdue — catch up with: agents routines catchup`));
545
- }
546
- scheduler.stopAll();
547
- console.log();
548
- }
549
- function routineMatchesQuery(job, q) {
550
- const kind = job.command ? 'command' : job.workflow ? `wf:${job.workflow}` : job.agent ?? '';
551
- return [job.name, kind, fireConditionLabel(job), (job.projects ?? []).join(' ')]
552
- .join(' ')
553
- .toLowerCase()
554
- .includes(q);
555
- }
556
- const SKIP_REASON_LABEL = {
557
- duplicate_slot: 'duplicate slot (already fired)',
558
- wrong_owner: 'pinned to another device',
559
- };
560
- function runIdToStartIso(runId) {
561
- const m = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(runId);
562
- if (!m)
563
- return null;
564
- const iso = `${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z`;
565
- return Number.isFinite(Date.parse(iso)) ? iso : null;
566
- }
567
- export function runFailureReason(run) {
568
- if (run.status === 'completed' || run.status === 'running')
569
- return null;
570
- const compact = (s) => {
571
- const one = s.replace(/\s+/g, ' ').trim();
572
- return one.length > 80 ? one.slice(0, 79) + '…' : one;
573
- };
574
- if (run.skipReason === 'active_run') {
575
- if (run.activeRunId) {
576
- const since = runIdToStartIso(run.activeRunId);
577
- return since
578
- ? `blocked: run ${run.activeRunId} active since ${since}`
579
- : `blocked: run ${run.activeRunId} still active`;
580
- }
581
- if (run.errorMessage)
582
- return compact(run.errorMessage);
583
- return 'blocked: a prior run is still active';
584
- }
585
- if (run.errorMessage)
586
- return compact(run.errorMessage);
587
- if (run.status === 'blocked' && run.readiness) {
588
- return compact(run.readiness.message || run.readiness.code);
589
- }
590
- if (run.skipReason)
591
- return SKIP_REASON_LABEL[run.skipReason];
592
- if (run.status === 'missed')
593
- return 'scheduler was not running when it came due';
594
- if ((run.status === 'failed' || run.status === 'timeout') && run.exitCode !== null && run.exitCode !== undefined) {
595
- return `exit ${run.exitCode}`;
596
- }
597
- return null;
598
- }
599
- function routineBrowserRow(job, scheduler, overdueSet, now) {
600
- const kind = job.command ? 'command' : job.workflow ? `wf:${job.workflow}` : job.agent ?? '?';
601
- const name = job.name.length > 24 ? job.name.slice(0, 23) + '…' : job.name.padEnd(24);
602
- const enabled = job.enabled === false ? chalk.gray('paused') : chalk.green('on');
603
- const latest = localLatestRun(job);
604
- const last = latest
605
- ? latest.status === 'completed'
606
- ? chalk.green('ok')
607
- : latest.status === 'failed' || latest.status === 'timeout'
608
- ? chalk.red(latest.status)
609
- : chalk.yellow(latest.status)
610
- : chalk.gray('—');
611
- const next = overdueSet.has(job.name)
612
- ? chalk.yellow('overdue')
613
- : chalk.gray(nextRunLabel(job, scheduler, now));
614
- return `${chalk.bold(name)} ${chalk.cyan(kind.padEnd(12))} ${enabled.padEnd(6)} ${chalk.gray(scheduleLabel(job)).padEnd(24)} next ${next} · last ${last}`;
615
- }
616
- function buildRoutineDetail(job, scheduler, now) {
617
- const lines = [];
618
- lines.push(chalk.bold.underline('Definition'));
619
- const kind = job.command
620
- ? `command: ${job.command}`
621
- : job.workflow
622
- ? `workflow: ${job.workflow}`
623
- : `agent: ${job.agent ?? '?'}`;
624
- lines.push(` ${kind}`);
625
- lines.push(` schedule: ${fireConditionLabel(job)}${isOneShotRoutine(job) ? ' (one-shot)' : ''}`);
626
- const devices = devicesWithRoutineEnabled(job.name);
627
- lines.push(` devices: ${devices.length > 0 ? devices.join(', ') : chalk.gray('none (paused)')}`);
628
- if (job.timezone)
629
- lines.push(` timezone: ${job.timezone}`);
630
- if (job.repo)
631
- lines.push(` repo: ${job.repo}`);
632
- if (job.prompt) {
633
- const oneLine = job.prompt.replace(/\s+/g, ' ').trim();
634
- lines.push(` prompt: ${oneLine.length > 120 ? oneLine.slice(0, 119) + '…' : oneLine}`);
635
- }
636
- lines.push('');
637
- lines.push(chalk.bold.underline('Next fire'));
638
- const nextDate = nextRunForDisplay(job, scheduler);
639
- lines.push(` ${nextRunLabel(job, scheduler, now)}${nextDate ? chalk.gray(` (${nextDate.toISOString()})`) : ''}`);
640
- lines.push('');
641
- lines.push(chalk.bold.underline('Recent runs'));
642
- const runs = listRuns(job.name).slice(-5);
643
- if (runs.length === 0) {
644
- lines.push(chalk.gray(' no runs yet'));
645
- }
646
- else {
647
- for (const run of runs) {
648
- const status = run.status === 'completed'
649
- ? chalk.green(run.status)
650
- : run.status === 'failed' || run.status === 'timeout'
651
- ? chalk.red(run.status)
652
- : chalk.yellow(run.status);
653
- const dur = run.completedAt ? ` ${formatRunDuration(run.startedAt, run.completedAt)}` : '';
654
- const reason = runFailureReason(run);
655
- const why = reason ? chalk.gray(` — ${reason}`) : '';
656
- lines.push(` ${run.startedAt} ${status}${dur}${why}`);
657
- }
658
- }
659
- lines.push('');
660
- lines.push(chalk.bold.underline('Stats'));
661
- const stats = routineStats(job.name);
662
- if (stats.count === 0) {
663
- lines.push(chalk.gray(' no completed runs'));
664
- }
665
- else {
666
- lines.push(` runs ${stats.count} · failed ${stats.failed} · missed ${stats.missed}`);
667
- lines.push(` avg ${stats.avgMs}ms · p50 ${stats.p50}ms · p95 ${stats.p95}ms`);
668
- }
669
- return lines.join('\n');
670
- }
671
- async function runRoutinesBrowser(options) {
672
- if (options.groupBy && options.groupBy !== 'device' && options.groupBy !== 'project') {
673
- console.error(chalk.red(`Unsupported --group-by '${options.groupBy}'. Use: project (default) or device`));
674
- process.exit(1);
675
- }
676
- try {
677
- monitorRunningJobs();
678
- }
679
- catch { }
680
- const jobs = listJobsForDisplay(process.cwd());
681
- if (jobs.length === 0) {
682
- console.log(chalk.gray('No jobs configured'));
683
- console.log(chalk.gray(' Add a job: agents routines add <path-to-job.yml>'));
684
- return;
685
- }
686
- const scheduler = new JobScheduler(async () => { });
687
- scheduler.loadAll();
688
- try {
689
- const now = new Date();
690
- const overdueSet = new Set();
691
- try {
692
- for (const j of detectOverdueJobs())
693
- overdueSet.add(j.name);
694
- }
695
- catch { }
696
- let groups;
697
- if (options.groupBy === 'device') {
698
- let registry = {};
699
- try {
700
- registry = loadDevicesSync();
701
- }
702
- catch { }
703
- groups = groupRoutineJobsByDevice(jobs, registry);
704
- }
705
- else {
706
- const knownProjectNames = new Set(listProjectDefs().map((p) => p.name));
707
- groups = groupRoutineJobsByProject(jobs, knownProjectNames);
708
- }
709
- const filter = (query) => {
710
- const q = query.trim().toLowerCase();
711
- const rows = [];
712
- for (const group of groups) {
713
- const matched = q ? group.jobs.filter((j) => routineMatchesQuery(j, q)) : group.jobs;
714
- if (matched.length === 0)
715
- continue;
716
- rows.push(new Separator(chalk.bold(`── ${group.title} ──`)));
717
- rows.push(...matched);
718
- }
719
- return rows;
720
- };
721
- const picked = await itemPicker({
722
- message: 'Routines',
723
- subtitle: chalk.gray('type to filter · ↑↓ navigate · space toggles detail · ⏎ open'),
724
- items: filter(''),
725
- filter,
726
- labelFor: (job) => routineBrowserRow(job, scheduler, overdueSet, now),
727
- buildPreview: (job) => buildRoutineDetail(job, scheduler, now),
728
- shortIdFor: (job) => job.name,
729
- pageSize: 15,
730
- enterHint: 'open',
731
- emptyMessage: 'No routines match.',
732
- });
733
- if (picked) {
734
- console.log();
735
- console.log(chalk.bold(picked.item.name));
736
- console.log(buildRoutineDetail(picked.item, scheduler, now));
737
- }
738
- }
739
- finally {
740
- scheduler.stopAll();
741
- }
742
- }
743
- export function registerRoutinesCommands(program) {
744
- const routinesCmd = program
745
- .command('routines')
746
- .description('Schedule agents to run on a cron schedule or at a specific time. The daemon starts at install/upgrade and on setup when daemon.enabled is not false; routines add also ensures it is running.');
747
- addHostOption(routinesCmd);
748
- setHelpSections(routinesCmd, {
749
- examples: `
750
- # Cron routine: Claude every weekday at 9 AM (scheduler auto-starts)
751
- agents routines add daily-standup --schedule "0 9 * * 1-5" --agent claude --prompt "Draft standup from git log"
752
-
753
- # One-shot: Codex tomorrow at 2:30 PM, then never again
754
- agents routines add hotfix-review --at "14:30" --agent codex --prompt "Review hotfix PR #42"
755
-
756
- # Create from YAML (for complex routines with multiple settings)
757
- agents routines add weekly-report.yml
758
-
759
- # Place the job body on a fleet device / cloud / named host (not --host)
760
- agents routines add drain --schedule "0 3 * * *" --agent claude --placement fleet --prompt "Drain queue"
761
- agents routines add review --schedule "0 9 * * 1" --agent claude --placement cloud --prompt "Review open PRs"
762
-
763
- # Pin an exact installed version (same agent@version syntax as agents run)
764
- agents routines add version-pin --schedule "*/5 * * * *" --agent claude@2.1.207 --cwd /path/to/repo --prompt "Reply OK"
765
-
766
- # Per-routine selection strategy + health-aware fleet placement at each fire
767
- agents routines add release-shepherd --schedule "*/5 * * * *" --agent claude --strategy balanced --run-on auto --cwd /path/to/repo --prompt "Own the release through verification"
768
-
769
- # Enable a routine (materialises a project routine on first enable)
770
- agents routines enable security-sweep
771
- agents routines disable security-sweep
772
-
773
- # List all routines and their next run times
774
- agents routines list
775
-
776
- # List routines on a specific device
777
- agents routines list --device yosemite-s0
778
-
779
- # Create a routine restricted to specific devices
780
- agents routines add nightly --schedule "0 2 * * *" --agent claude --prompt "Summarize today's commits" --devices yosemite-s0,mac-mini
781
-
782
- # Interactively manage which devices may run a routine
783
- agents routines devices nightly
784
-
785
- # Run a routine right now in the foreground (ignores schedule)
786
- agents routines run daily-standup
787
-
788
- # Check whether the scheduler is running
789
- agents routines status
790
-
791
- # Machine-readable scheduler + per-routine status: owner device, last fire, last error, in-flight run
792
- agents routines status --json
793
- `,
794
- notes: `
795
- A routine is a YAML file that schedules an agent invocation. It specifies:
796
- - which agent to run (claude, codex, antigravity, ...)
797
- - when to run (cron schedule or one-shot time)
798
- - what task to give the agent (the prompt)
799
- - execution constraints (mode, effort, timeout)
800
-
801
- The always-on agents daemon starts at install/upgrade and on setup (when
802
- daemon.enabled is not false). Adding a routine also ensures it is running.
803
- Manage it with 'agents routines start|stop|status'.
804
-
805
- Version / credit failover (same semantics as 'agents run'):
806
- - Omit 'version:' to let the configured run strategy (default: balanced)
807
- pick a healthy install and skip accounts that are out of credits or
808
- rate-limited. Pin with '--agent claude@2.1.x' (or 'version:' in YAML)
809
- when you want one install only; '--strategy pinned|available|balanced'
810
- persists a per-routine selection policy that beats the firing box's
811
- run.<agent>.strategy config.
812
- - Three distinct device flags: '--devices a,b' is the scheduler FIRING
813
- allowlist (which daemons may fire this routine); '--run-on <name|auto>'
814
- is BODY placement (where the fired job executes — 'auto' re-picks a
815
- healthy device at each fire); the parent '--device' manages the
816
- routine DEFINITION on another machine.
817
- - Foreground 'agents routines run' re-dispatches to the next healthy
818
- same-agent account when a mid-run rate/usage limit is detected.
819
- - Detached/daemon fires use the pre-flight pick only (next tick re-selects).
820
- - Diagnostic lines log which account was picked, which were skipped, and
821
- each failover hop: look for "[agents] routine <name>:" in the run log.
822
- - Claude auth: a routine authenticates through the pinned account's own
823
- on-disk login (the same one 'agents run claude' uses on this device).
824
- The daemon injects no token; if that account's login has expired the
825
- run is skipped up front with a re-login hint.
826
- `,
827
- });
828
- routinesCmd
829
- .command('browse', { isDefault: true, hidden: true })
830
- .description('Interactive routines browser (the default for a bare `agents routines`)')
831
- .option('--json', 'Emit machine-readable JSON instead of the browser (matches `routines list --json`)')
832
- .option('--group-by <field>', 'Group by field: project (default) or device', 'project')
833
- .option('--flat', 'Print the legacy flat table instead of the interactive browser')
834
- .action(async (options) => {
835
- if (options.json || options.flat || !isInteractiveTerminal()) {
836
- runRoutinesList(options);
837
- return;
838
- }
839
- await runRoutinesBrowser(options);
840
- });
841
- routinesCmd
842
- .command('list')
843
- .description('See all scheduled jobs, when they run next, and their last execution status')
844
- .option('--json', 'Emit machine-readable JSON instead of the table (used by the menu bar helper)')
845
- .option('--group-by <field>', 'Group output by field: project (default) or device', 'project')
846
- .option('--flat', 'Print the legacy flat table instead of grouped sections')
847
- .action((options) => {
848
- runRoutinesList(options);
849
- });
850
- routinesCmd
851
- .command('add [nameOrPath]')
852
- .description('Create a new routine from a YAML file or inline flags. Starts the scheduler automatically if it is not already running.')
853
- .option('-s, --schedule <cron>', 'Cron schedule in standard format (5 fields: minute hour day month weekday)')
854
- .option('-a, --agent <agent[@version]>', `Which agent runs this routine: ${ROUTINE_AGENT_IDS.join(', ')}, or a custom harness name (agents harness list). An @version pins that exact installed version (same syntax as agents run), persisted as separate agent + version fields; a custom harness pins its own host version.`)
855
- .option('--strategy <strategy>', `Version/account selection strategy for this routine: ${RUN_STRATEGIES.join(' | ')}. Overrides run.<agent>.strategy from the firing device's config. Conflicts with an @version pin.`)
856
- .option('--balanced', 'Shortcut for --strategy balanced.')
857
- .option('--workflow <name>', 'Run an installed workflow (~/.agents/workflows/<name>) via `agents run`. Mutually exclusive with --agent.')
858
- .option('--command <sh>', 'Run a plain shell command directly (no agent, no auth, no sandbox) — for deterministic housekeeping routines. Mutually exclusive with --agent and --workflow; --prompt is not used.')
859
- .option('-p, --prompt <prompt>', 'Task instruction for the agent')
860
- .option('-m, --mode <mode>', "Execution mode: plan (read-only), edit (can write files), auto (the default; more autonomous than edit, mechanism per-harness — see `agents run --help`), or skip (bypass all permission prompts). 'full' accepted as alias for skip.", 'auto')
861
- .option('-e, --effort <effort>', 'Reasoning effort: low | medium | high | xhigh | max | auto', 'auto')
862
- .option('-t, --timeout <timeout>', 'Kill the agent if it runs longer than this (e.g., 10m, 2h, 3d, 1w; max 1w)', '10m')
863
- .option('--timezone <tz>', 'Interpret schedule in this timezone (e.g., America/Los_Angeles)')
864
- .option('--devices <names>', 'Fleet allowlist (comma-separated): only listed devices schedule and fire this routine. Omit for unrestricted.')
865
- .option('--run-on <name|auto>', "BODY placement: execute the job body on this machine over SSH (registered host, device, capability tag, or user@host), or 'auto' to pick a healthy, signed-in, unloaded fleet device AT EACH FIRE — the same picker as agents run --device auto. Sets hostStrategy=host ('auto' sets fleet). Distinct from the parent --device (which manages this DEFINITION on another machine) and from --devices (the scheduler firing allowlist).")
866
- .option('--placement <strategy>', `BODY placement strategy: ${HOST_STRATEGIES.join('|')} (default: local, or host when --run-on is set). Maps to the shared Placement model (local|device|fleet|cloud). Not the same as --device (which manages routines on a remote machine).`)
867
- .option('--run-cwd <dir>', 'Working directory on the --run-on host (--remote-cwd is taken by the remote-management passthrough)')
868
- .option('--at <time>', 'One-shot mode: run once at this time (e.g., "14:30" or "2026-02-24 09:00"), then disable')
869
- .option('--on <source:event>', 'Webhook trigger instead of/in addition to a schedule: github:pull_request or linear:Issue')
870
- .option('--repo <owner/name>', 'GitHub repo filter for --on github:<event>')
871
- .option('--branch <name>', 'GitHub branch filter for --on github:<event>')
872
- .option('--action <name>', 'Webhook action filter for --on triggers (GitHub: labeled/opened; Linear: update)')
873
- .option('--team-key <key>', 'Linear team key filter for --on linear:<event> (e.g. RUSH)')
874
- .option('--label <name>', 'Label filter for --on triggers (GitHub label name or Linear issue label)')
875
- .option('--state-to <name>', 'Linear current-state filter for --on linear:<event> (e.g. Plan)')
876
- .option('--state-from <name>', 'Linear previous-state filter for --on linear:<event> (e.g. Triage)')
877
- .option('--end-at <iso>', 'Stop firing on or after this ISO 8601 timestamp (e.g., "2026-12-31T23:59:00Z"); routine auto-disables.')
878
- .option('--no-catchup', 'Do not run this routine late if its fire is missed (daemon down/asleep). The miss is still recorded. For routines whose value expires with their slot, e.g. a 9am brief.')
879
- .option('--disabled', 'Create the routine but keep it paused (enable later with resume)')
880
- .option('--resume <sessionId>', 'At fire time, resume this existing session id (via `agents run <agent> --resume`) instead of starting fresh — the actual session reopens with full context and the prompt becomes its next turn. Powers self-scheduled wake-ups (e.g. /hibernate). Requires --agent claude or codex; runs un-sandboxed (the session store lives in the real home, not the job overlay).')
881
- .option('--project <name>', 'Associate with a named project (repeatable; use --all-projects for all)', collectProject, [])
882
- .option('--all-projects', 'Associate this routine with all defined projects (sets projects: ["*"])')
883
- .option('--project-anchor <name>', 'Singular EXECUTION anchor: the named project whose base directory the run lands in (distinct from --project, which is grouping metadata). Rootless (Linear-imported) projects anchor a relative --cwd at the target home.')
884
- .option('--cwd <path>', 'Portable execution directory. Relative values resolve under --project-anchor when usable, otherwise under the execution target $HOME. Supersedes --run-cwd/remoteCwd.')
885
- .option('--json', 'Emit machine-readable JSON with the created routine id and status')
886
- .action(async (nameOrPath, options) => {
887
- const hasInlineFlags = options.schedule || options.agent || options.workflow || options.command || options.prompt || options.at || options.on;
888
- if (hasInlineFlags) {
889
- if (!nameOrPath) {
890
- console.error(chalk.red('Job name is required'));
891
- console.error(chalk.gray('Usage: agents routines add <name> --schedule "..." --agent <agent> --prompt "..."'));
892
- process.exit(1);
893
- }
894
- if ([options.agent, options.workflow, options.command].filter(Boolean).length > 1) {
895
- console.error(chalk.red('--agent, --workflow, and --command are mutually exclusive; specify exactly one'));
896
- process.exit(1);
897
- }
898
- let schedule = options.schedule;
899
- let trigger;
900
- let runOnce = false;
901
- try {
902
- trigger = parseRoutineTrigger(options);
903
- }
904
- catch (err) {
905
- console.error(chalk.red(err.message));
906
- process.exit(1);
907
- }
908
- if (options.at) {
909
- const parsed = parseAtTime(options.at);
910
- if (!parsed) {
911
- console.error(chalk.red(`Invalid --at format: ${options.at}`));
912
- console.error(chalk.gray('Supported formats: "14:30" or "2026-02-24 09:00"'));
913
- process.exit(1);
914
- }
915
- schedule = parsed.schedule;
916
- runOnce = parsed.runOnce;
917
- }
918
- if (!options.at && isOneShotLikeSchedule(schedule)) {
919
- runOnce = true;
920
- console.error(chalk.yellow(`Schedule "${schedule}" pins minute, hour, day, and month; treating it as one-shot. Prefer --at for one-time routines.`));
921
- }
922
- if (!schedule && !trigger) {
923
- console.error(chalk.red('Schedule or trigger is required (use --schedule, --at, or --on)'));
924
- process.exit(1);
925
- }
926
- if (!options.agent && !options.workflow && !options.command) {
927
- console.error(chalk.red('An agent, workflow, or command is required (use --agent, --workflow, or --command)'));
928
- process.exit(1);
929
- }
930
- let parsedAgent;
931
- if (options.agent) {
932
- if (isCustomHarnessName(options.agent)) {
933
- parsedAgent = { agent: options.agent };
934
- }
935
- else {
936
- const parsed = parseAgentVersionSpec(options.agent);
937
- if ('error' in parsed) {
938
- console.error(chalk.red(parsed.error));
939
- process.exit(1);
940
- }
941
- parsedAgent = parsed;
942
- if (isAgentHardDeprecated(parsed.agent)) {
943
- console.error(chalk.red(hardDeprecationError(parsed.agent)));
944
- process.exit(1);
945
- }
946
- }
947
- }
948
- let strategy;
949
- if (options.strategy !== undefined || options.balanced) {
950
- if (options.strategy !== undefined && options.balanced) {
951
- console.error(chalk.red('--balanced conflicts with --strategy. Use one strategy override.'));
952
- process.exit(1);
953
- }
954
- if (!options.agent) {
955
- console.error(chalk.red('--strategy only applies to agent routines (set --agent)'));
956
- process.exit(1);
957
- }
958
- if (options.strategy !== undefined) {
959
- const normalized = normalizeRunStrategy(options.strategy);
960
- if (!normalized) {
961
- console.error(chalk.red(`Invalid strategy: ${options.strategy}. Use ${RUN_STRATEGIES.join(', ')}.`));
962
- process.exit(1);
963
- }
964
- strategy = normalized;
965
- }
966
- else {
967
- strategy = 'balanced';
968
- }
969
- if (parsedAgent?.version) {
970
- console.error(chalk.red(`--strategy ${strategy} conflicts with the @${parsedAgent.version} pin — an exact pin leaves nothing to select; drop --strategy or the @version pin`));
971
- process.exit(1);
972
- }
973
- }
974
- if (!options.command && !options.prompt) {
975
- console.error(chalk.red('Prompt is required (use --prompt)'));
976
- process.exit(1);
977
- }
978
- let devices;
979
- if (options.devices !== undefined) {
980
- devices = await parseAndValidateDevices(options.devices);
981
- }
982
- let projects;
983
- if (options.allProjects) {
984
- if (options.project && options.project.length > 0) {
985
- console.error(chalk.red('--all-projects and --project are mutually exclusive'));
986
- process.exit(1);
987
- }
988
- projects = ['*'];
989
- }
990
- else if (options.project && options.project.length > 0) {
991
- for (const name of options.project) {
992
- if (!isSafeProjectName(name)) {
993
- console.error(chalk.red(`Invalid project name "${name}": must start with a letter or digit, contain only letters, digits, dots, hyphens, or underscores`));
994
- process.exit(1);
995
- }
996
- }
997
- const deduped = normalizeProjects(options.project) ?? [];
998
- const knownProjectNames = new Set(listProjectDefs().map((p) => p.name));
999
- const unknown = deduped.filter((n) => !knownProjectNames.has(n));
1000
- if (unknown.length > 0) {
1001
- console.error(chalk.red(`Unknown project(s): ${unknown.join(', ')}. Define them first with: agents projects add`));
1002
- process.exit(1);
1003
- }
1004
- projects = deduped;
1005
- }
1006
- let hostStrategy;
1007
- try {
1008
- hostStrategy = parseHostStrategy(options.placement) ?? undefined;
1009
- }
1010
- catch (err) {
1011
- console.error(chalk.red(err.message));
1012
- process.exit(1);
1013
- }
1014
- if (options.runOn && !hostStrategy)
1015
- hostStrategy = options.runOn === 'auto' ? 'fleet' : 'host';
1016
- if (options.runOn === 'auto' && hostStrategy !== 'fleet') {
1017
- console.error(chalk.red("--run-on auto is fleet placement — drop --placement, or use --placement fleet with it"));
1018
- process.exit(1);
1019
- }
1020
- if (hostStrategy === 'host' && !options.runOn) {
1021
- console.error(chalk.red('--placement host requires --run-on <name>'));
1022
- process.exit(1);
1023
- }
1024
- const config = {
1025
- name: nameOrPath,
1026
- ...(schedule ? { schedule } : {}),
1027
- ...(trigger ? { trigger } : {}),
1028
- ...(parsedAgent ? { agent: parsedAgent.agent } : {}),
1029
- ...(parsedAgent?.version ? { version: parsedAgent.version } : {}),
1030
- ...(strategy ? { strategy } : {}),
1031
- ...(options.workflow ? { workflow: options.workflow } : {}),
1032
- ...(options.command ? { command: options.command } : {}),
1033
- mode: options.mode,
1034
- effort: options.effort,
1035
- timeout: options.timeout,
1036
- enabled: !options.disabled,
1037
- prompt: options.prompt ?? '',
1038
- timezone: options.timezone,
1039
- ...(devices ? { devices } : {}),
1040
- ...(options.runOn ? { host: options.runOn } : {}),
1041
- ...(hostStrategy ? { hostStrategy } : {}),
1042
- ...(options.runCwd ? { remoteCwd: options.runCwd } : {}),
1043
- ...(options.projectAnchor ? { project: options.projectAnchor } : {}),
1044
- ...(options.cwd ? { cwd: options.cwd } : {}),
1045
- ...(runOnce ? { runOnce: true } : {}),
1046
- ...(options.catchup === false ? { catchup: false } : {}),
1047
- ...(options.endAt ? { endAt: options.endAt } : {}),
1048
- ...(options.resume ? { resume: options.resume } : {}),
1049
- ...(projects ? { projects } : {}),
1050
- };
1051
- const errors = validateJob(config);
1052
- if (errors.length > 0) {
1053
- console.error(chalk.red('Validation errors:'));
1054
- for (const err of errors) {
1055
- console.error(chalk.red(` - ${err}`));
1056
- }
1057
- process.exit(1);
1058
- }
1059
- writeJob(config);
1060
- const deviceMatch = !devices || devices.map(normalizeHost).includes(normalizeHost(machineId()));
1061
- const readiness = await evaluateActivationReadinessLive(config);
1062
- const activate = config.enabled && deviceMatch && readiness.ready;
1063
- setJobEnabled(config.name, activate);
1064
- if (config.enabled && deviceMatch && !readiness.ready) {
1065
- const r = readiness.readiness;
1066
- if (!options.json) {
1067
- console.log(chalk.yellow(`Saved paused — not ready to activate: ${r.code}`));
1068
- console.log(chalk.gray(` ${r.message}`));
1069
- if (r.repair)
1070
- console.log(chalk.gray(` repair: ${r.repair}`));
1071
- console.log(chalk.gray(` then: agents routines enable ${config.name}`));
1072
- }
1073
- }
1074
- if (options.json) {
1075
- writeJson({
1076
- ok: true,
1077
- added: nameOrPath,
1078
- job: config,
1079
- jobId: config.name,
1080
- name: config.name,
1081
- status: activate ? 'added' : 'added_paused',
1082
- enabled: config.enabled,
1083
- activated: activate,
1084
- ready: readiness.ready,
1085
- ...(readiness.readiness ? { readiness: readiness.readiness } : {}),
1086
- schedule: config.schedule ?? null,
1087
- trigger: config.trigger ?? null,
1088
- });
1089
- ensureSchedulerRunning({ quiet: true });
1090
- return;
1091
- }
1092
- console.log(chalk.green(`Job '${nameOrPath}' added`));
1093
- if (runOnce) {
1094
- console.log(chalk.gray(`One-shot job scheduled for: ${options.at}`));
1095
- }
1096
- ensureSchedulerRunning();
1097
- }
1098
- else {
1099
- if (!nameOrPath) {
1100
- console.error(chalk.red('File path or job name with flags is required'));
1101
- console.error(chalk.gray('Usage: agents routines add <path-to-job.yml>'));
1102
- console.error(chalk.gray(' or: agents routines add <name> --schedule "..." --agent <agent> --prompt "..."'));
1103
- process.exit(1);
1104
- }
1105
- const resolved = path.resolve(nameOrPath);
1106
- if (!fs.existsSync(resolved)) {
1107
- console.error(chalk.red(`File not found: ${resolved}`));
1108
- process.exit(1);
1109
- }
1110
- const content = fs.readFileSync(resolved, 'utf-8');
1111
- let parsed;
1112
- try {
1113
- parsed = yaml.parse(content);
1114
- }
1115
- catch (err) {
1116
- console.error(chalk.red(`Invalid YAML: ${err.message}`));
1117
- process.exit(1);
1118
- }
1119
- const name = parsed.name || path.basename(resolved).replace(/\.ya?ml$/, '');
1120
- parsed.name = name;
1121
- const errors = validateJob(parsed);
1122
- if (errors.length > 0) {
1123
- console.error(chalk.red('Validation errors:'));
1124
- for (const err of errors) {
1125
- console.error(chalk.red(` - ${err}`));
1126
- }
1127
- process.exit(1);
1128
- }
1129
- const config = {
1130
- mode: 'auto',
1131
- effort: 'auto',
1132
- timeout: '10m',
1133
- enabled: true,
1134
- ...parsed,
1135
- };
1136
- if (isOneShotLikeSchedule(config.schedule)) {
1137
- config.runOnce = true;
1138
- console.error(chalk.yellow(`Schedule "${config.schedule}" pins minute, hour, day, and month; treating it as one-shot. Prefer --at for one-time routines.`));
1139
- }
1140
- if (!isCanonicalRoutineSource(resolved, config.name))
1141
- writeJob(config);
1142
- const deviceMatch = !config.devices || config.devices.map(normalizeHost).includes(normalizeHost(machineId()));
1143
- const readiness = await evaluateActivationReadinessLive(config);
1144
- const activate = config.enabled && deviceMatch && readiness.ready;
1145
- setJobEnabled(config.name, activate);
1146
- if (config.devices && config.devices.length > 0 && !options.json) {
1147
- console.log(chalk.yellow(`'devices:' pins activation on this box only — it is not propagated to peers.`));
1148
- console.log(chalk.gray(` pin the fleet with: agents routines devices ${config.name} --set ${config.devices.join(',')}`));
1149
- }
1150
- if (config.enabled && deviceMatch && !readiness.ready && !options.json) {
1151
- const r = readiness.readiness;
1152
- console.log(chalk.yellow(`Saved paused — not ready to activate: ${r.code}`));
1153
- console.log(chalk.gray(` ${r.message}`));
1154
- if (r.repair)
1155
- console.log(chalk.gray(` repair: ${r.repair}`));
1156
- console.log(chalk.gray(` then: agents routines enable ${config.name}`));
1157
- }
1158
- if (options.json) {
1159
- writeJson({
1160
- ok: true,
1161
- added: name,
1162
- job: config,
1163
- jobId: config.name,
1164
- name: config.name,
1165
- status: activate ? 'added' : 'added_paused',
1166
- enabled: config.enabled,
1167
- activated: activate,
1168
- ready: readiness.ready,
1169
- ...(readiness.readiness ? { readiness: readiness.readiness } : {}),
1170
- schedule: config.schedule ?? null,
1171
- trigger: config.trigger ?? null,
1172
- });
1173
- ensureSchedulerRunning({ quiet: true });
1174
- return;
1175
- }
1176
- console.log(chalk.green(`Job '${name}' added`));
1177
- ensureSchedulerRunning();
1178
- }
1179
- });
1180
- routinesCmd
1181
- .command('prune')
1182
- .alias('cleanup')
1183
- .description('Remove expired one-shot routines that already fired and still have a user-layer YAML file.')
1184
- .option('--dry-run', 'Show routines that would be removed without deleting files')
1185
- .action((options) => {
1186
- const jobs = listAllJobs()
1187
- .filter((job) => getJobPath(job.name) !== null)
1188
- .filter((job) => hasCompletedOneShotRun(job));
1189
- if (jobs.length === 0) {
1190
- console.log(chalk.gray('No completed expired one-shot routines to clean up.'));
1191
- return;
1192
- }
1193
- if (options.dryRun) {
1194
- console.log(chalk.bold('Expired one-shot routines eligible for cleanup\n'));
1195
- for (const job of jobs) {
1196
- console.log(` ${chalk.cyan(job.name)} ${chalk.gray(scheduleLabel(job))}`);
1197
- }
1198
- console.log(chalk.gray(`\nDry run. Remove with: agents routines prune`));
1199
- return;
1200
- }
1201
- let removed = 0;
1202
- for (const job of jobs) {
1203
- if (deleteJob(job.name)) {
1204
- removed++;
1205
- console.log(chalk.green(`Removed ${job.name}`));
1206
- }
1207
- }
1208
- console.log(chalk.gray(`Cleaned up ${removed} expired one-shot routine(s).`));
1209
- try {
1210
- signalDaemonReload();
1211
- }
1212
- catch {
1213
- }
1214
- });
1215
- routinesCmd
1216
- .command('remove [name]')
1217
- .description('Delete a routine. Stops scheduling future runs; past execution logs remain on disk.')
1218
- .action(async (name) => {
1219
- if (!name) {
1220
- name = await pickJob('Select job to remove', undefined, ['agents routines remove <name>']) ?? undefined;
1221
- if (!name)
1222
- return;
1223
- }
1224
- const deleted = deleteJob(name);
1225
- if (deleted) {
1226
- console.log(chalk.green(`Job '${name}' removed`));
1227
- if (isDaemonRunning()) {
1228
- signalDaemonReload();
1229
- console.log(chalk.gray('Daemon reloaded'));
1230
- }
1231
- }
1232
- else {
1233
- console.log(chalk.red(`Job '${name}' not found`));
1234
- process.exit(1);
1235
- }
1236
- });
1237
- routinesCmd
1238
- .command('view [name]')
1239
- .description('Show the full YAML configuration for a routine')
1240
- .action(async (name) => {
1241
- if (!name) {
1242
- name = await pickJob('Select job to view', undefined, ['agents routines view <name>'], process.cwd()) ?? undefined;
1243
- if (!name)
1244
- return;
1245
- }
1246
- const job = readJob(name, process.cwd());
1247
- if (!job) {
1248
- console.log(chalk.red(`Job '${name}' not found`));
1249
- process.exit(1);
1250
- }
1251
- console.log(chalk.bold(`Job: ${name}\n`));
1252
- console.log(yaml.stringify(job));
1253
- });
1254
- routinesCmd
1255
- .command('edit [name]')
1256
- .description('Edit a prefilled routine transactionally; invalid YAML never replaces the live definition.')
1257
- .option('--yaml', 'Open the raw YAML in $EDITOR (the current edit surface)')
1258
- .option('--state-to <name>', 'Update the Linear current-state filter before opening the editor')
1259
- .option('--state-from <name>', 'Update the Linear previous-state filter before opening the editor')
1260
- .option('--cwd <path>', 'Set the execution directory and save, without opening an editor')
1261
- .option('--project-anchor <name>', 'Set the execution project anchor and save, without opening an editor')
1262
- .option('--agent <agent[@version]>', 'Set the agent (and optional exact version pin) and save, without opening an editor — same syntax as agents run')
1263
- .option('--strategy <strategy>', `Set the per-routine version/account selection strategy (${RUN_STRATEGIES.join(' | ')}) and save. Conflicts with an @version pin.`)
1264
- .action(async (name, options) => {
1265
- if (!name) {
1266
- name = await pickJob('Select job to edit', undefined, ['agents routines edit <name>']) ?? undefined;
1267
- if (!name)
1268
- return;
1269
- }
1270
- const existing = readJob(name);
1271
- if (options.cwd !== undefined || options.projectAnchor !== undefined || options.agent !== undefined || options.strategy !== undefined) {
1272
- if (!existing) {
1273
- console.error(chalk.red(`Routine '${name}' not found. Create it first: agents routines add ${name} --schedule "..." --agent claude --prompt "..."`));
1274
- process.exit(1);
1275
- }
1276
- if (options.cwd !== undefined)
1277
- existing.cwd = options.cwd;
1278
- if (options.projectAnchor !== undefined)
1279
- existing.project = options.projectAnchor;
1280
- if (options.agent !== undefined) {
1281
- if (isCustomHarnessName(options.agent)) {
1282
- existing.agent = options.agent;
1283
- delete existing.version;
1284
- }
1285
- else {
1286
- const parsed = parseAgentVersionSpec(options.agent);
1287
- if ('error' in parsed) {
1288
- console.error(chalk.red(parsed.error));
1289
- process.exit(1);
1290
- }
1291
- if (isAgentHardDeprecated(parsed.agent)) {
1292
- console.error(chalk.red(hardDeprecationError(parsed.agent)));
1293
- process.exit(1);
1294
- }
1295
- existing.agent = parsed.agent;
1296
- if (parsed.version)
1297
- existing.version = parsed.version;
1298
- else
1299
- delete existing.version;
1300
- }
1301
- }
1302
- if (options.strategy !== undefined) {
1303
- const normalized = normalizeRunStrategy(options.strategy);
1304
- if (!normalized) {
1305
- console.error(chalk.red(`Invalid strategy: ${options.strategy}. Use ${RUN_STRATEGIES.join(', ')}.`));
1306
- process.exit(1);
1307
- }
1308
- existing.strategy = normalized;
1309
- }
1310
- const errors = validateJob(existing);
1311
- if (errors.length > 0) {
1312
- console.error(chalk.red('Validation errors:'));
1313
- for (const err of errors)
1314
- console.error(chalk.red(` - ${err}`));
1315
- process.exit(1);
1316
- }
1317
- writeJob(existing);
1318
- const readiness = await evaluateActivationReadinessLive(existing);
1319
- console.log(chalk.green(`Routine '${name}' updated`));
1320
- if (!readiness.ready && readiness.readiness) {
1321
- console.log(chalk.yellow(`Still not ready: ${readiness.readiness.code}`));
1322
- console.log(chalk.gray(` ${readiness.readiness.message}`));
1323
- }
1324
- else {
1325
- console.log(chalk.gray(` enable it with: agents routines enable ${name}`));
1326
- }
1327
- return;
1328
- }
1329
- if (existing && (options.stateTo !== undefined || options.stateFrom !== undefined)) {
1330
- if (!existing.trigger || existing.trigger.type !== 'linear_event') {
1331
- console.error(chalk.red(`'${name}' does not have a Linear trigger; --state-to/--state-from only apply to linear triggers`));
1332
- process.exit(1);
1333
- }
1334
- if (options.stateTo !== undefined)
1335
- existing.trigger.stateTo = options.stateTo || undefined;
1336
- if (options.stateFrom !== undefined)
1337
- existing.trigger.stateFrom = options.stateFrom || undefined;
1338
- }
1339
- const jobPath = getJobPath(name);
1340
- const cronDir = getRoutinesDir();
1341
- fs.mkdirSync(cronDir, { recursive: true });
1342
- const targetPath = jobPath || safeJoin(cronDir, `${name}.yml`);
1343
- const editPath = safeJoin(cronDir, `.${name}.edit-${process.pid}.yml`);
1344
- const initial = existing
1345
- ? yaml.stringify(existing)
1346
- : yaml.stringify({
1347
- name,
1348
- schedule: '0 9 * * *',
1349
- agent: 'claude',
1350
- prompt: 'Your prompt here',
1351
- });
1352
- fs.writeFileSync(editPath, initial, { encoding: 'utf-8', mode: 0o600 });
1353
- const editor = process.env.EDITOR || process.env.VISUAL || (IS_WINDOWS ? 'notepad' : 'vi');
1354
- const editorParts = editor.split(/\s+/).filter(Boolean);
1355
- const editorBin = editorParts[0];
1356
- const editorArgs = [...editorParts.slice(1), editPath];
1357
- const { spawn: spawnSync } = await import('child_process');
1358
- const child = spawnSync(editorBin, editorArgs, {
1359
- stdio: 'inherit',
1360
- });
1361
- child.on('close', async (code) => {
1362
- if (code !== 0) {
1363
- fs.rmSync(editPath, { force: true });
1364
- return;
1365
- }
1366
- try {
1367
- const raw = fs.readFileSync(editPath, 'utf-8');
1368
- const job = yaml.parse(raw);
1369
- const errors = validateJob(job);
1370
- if (errors.length > 0)
1371
- throw new Error(errors.join('\n'));
1372
- const readiness = await evaluateActivationReadinessLive(job);
1373
- fs.renameSync(editPath, targetPath);
1374
- if (!readiness.ready)
1375
- setJobEnabled(job.name, false);
1376
- console.log(chalk.green(`\nJob '${name}' saved${readiness.ready ? '' : ' paused (not ready)'}`));
1377
- if (isDaemonRunning()) {
1378
- signalDaemonReload();
1379
- console.log(chalk.gray('Daemon reloaded'));
1380
- }
1381
- }
1382
- catch (err) {
1383
- fs.rmSync(editPath, { force: true });
1384
- console.error(chalk.red(`\nRoutine not saved: ${err.message}`));
1385
- process.exitCode = 1;
1386
- }
1387
- });
1388
- });
1389
- routinesCmd
1390
- .command('runs [name]')
1391
- .description('See execution history: run IDs, completion status, and start times (up to last 10 runs)')
1392
- .option('--json', 'Emit machine-readable JSON with run ids and statuses')
1393
- .action(async (name, options) => {
1394
- if (!name) {
1395
- name = await pickJob('Select job to view runs', undefined, ['agents routines runs <name>']) ?? undefined;
1396
- if (!name)
1397
- return;
1398
- }
1399
- const runs = listRuns(name);
1400
- if (options.json) {
1401
- writeJson({
1402
- jobId: name,
1403
- name,
1404
- runs: buildRunsJson(runs.slice(-10)),
1405
- });
1406
- return;
1407
- }
1408
- if (runs.length === 0) {
1409
- console.log(chalk.yellow(`No runs found for job '${name}'`));
1410
- return;
1411
- }
1412
- console.log(chalk.bold(`Execution History: ${name}\n`));
1413
- for (const run of runs.slice(-10)) {
1414
- const status = run.status === 'completed'
1415
- ? chalk.green(run.status)
1416
- : run.status === 'failed'
1417
- ? chalk.red(run.status)
1418
- : chalk.yellow(run.status);
1419
- const reason = runFailureReason(run);
1420
- const why = reason ? chalk.gray(` — ${reason}`) : '';
1421
- console.log(` ${run.runId} ${status} ${run.startedAt}${why}`);
1422
- }
1423
- });
1424
- routinesCmd
1425
- .command('stats [name]')
1426
- .description('Duration + outcome rollup per job: run count, failed, missed, avg/p50/p95 duration')
1427
- .option('--json', 'Emit machine-readable JSON')
1428
- .action(async (name, options) => {
1429
- if (!name) {
1430
- const jobs = listAllJobs();
1431
- const rows = jobs.map((j) => ({ name: j.name, ...routineStats(j.name) }));
1432
- if (options.json) {
1433
- writeJson({ jobs: rows });
1434
- return;
1435
- }
1436
- if (rows.length === 0) {
1437
- console.log(chalk.gray('No jobs configured'));
1438
- return;
1439
- }
1440
- console.log(chalk.bold('Routine stats\n'));
1441
- const pad = (s, w) => (s.length >= w ? s.slice(0, w) : s + ' '.repeat(w - s.length));
1442
- console.log(chalk.gray(` ${pad('JOB', 28)} ${pad('N', 5)} ${pad('FAILED', 7)} ${pad('MISSED', 7)} ${pad('AVG', 7)} ${pad('P50', 7)} P95`));
1443
- for (const r of rows) {
1444
- console.log(` ${pad(r.name, 28)} ${pad(String(r.count), 5)} ${pad(String(r.failed), 7)} ${pad(String(r.missed), 7)} ${pad(`${r.avgMs}ms`, 7)} ${pad(`${r.p50}ms`, 7)} ${r.p95}ms`);
1445
- }
1446
- return;
1447
- }
1448
- const stats = routineStats(name);
1449
- if (options.json) {
1450
- writeJson({ jobId: name, name, ...stats });
1451
- return;
1452
- }
1453
- if (stats.count === 0) {
1454
- console.log(chalk.yellow(`No runs found for job '${name}'`));
1455
- return;
1456
- }
1457
- console.log(chalk.bold(`Stats: ${name}\n`));
1458
- console.log(` Runs: ${stats.count}`);
1459
- console.log(` Failed: ${stats.failed}`);
1460
- console.log(` Missed: ${stats.missed}`);
1461
- console.log(` Avg: ${stats.avgMs}ms`);
1462
- console.log(` P50: ${stats.p50}ms`);
1463
- console.log(` P95: ${stats.p95}ms`);
1464
- });
1465
- routinesCmd
1466
- .command('run [name]')
1467
- .description('Execute a routine right now in the foreground. Ignores the schedule; useful for testing before enabling.')
1468
- .option('--json', 'Emit machine-readable JSON with the run id and status')
1469
- .action(async (name, options) => {
1470
- if (!name) {
1471
- name = await pickJob('Select job to run', undefined, ['agents routines run <name>']) ?? undefined;
1472
- if (!name)
1473
- return;
1474
- }
1475
- const job = readJob(name);
1476
- if (!job) {
1477
- if (options.json) {
1478
- writeJson({ error: `Job '${name}' not found` });
1479
- process.exit(1);
1480
- }
1481
- console.error(chalk.red(`Job '${name}' not found`));
1482
- process.exit(1);
1483
- }
1484
- const eligibility = checkJobDeviceEligibility(job);
1485
- if (eligibility) {
1486
- if (options.json) {
1487
- writeJson({ error: eligibility.message, hint: eligibility.suggestion });
1488
- process.exit(1);
1489
- }
1490
- console.error(chalk.red(eligibility.message));
1491
- console.error(chalk.gray(` ${eligibility.suggestion}`));
1492
- process.exit(1);
1493
- }
1494
- const runLabel = job.command ? 'command' : job.workflow ? `workflow: ${job.workflow}` : `agent: ${job.agent}`;
1495
- const spinner = options.json ? null : ora('Executing...').start();
1496
- if (!options.json)
1497
- console.log(chalk.bold(`Running job '${name}' (${runLabel}, mode: ${job.mode})\n`));
1498
- try {
1499
- const result = await executeJob(job);
1500
- const logPath = `${getRunDir(name, result.meta.runId)}/stdout.log`;
1501
- const succeeded = result.meta.status === 'completed';
1502
- if (options.json) {
1503
- writeJson({
1504
- ok: succeeded,
1505
- job: name,
1506
- logDir: getRunDir(name, result.meta.runId),
1507
- ...runMetaJson(result.meta),
1508
- logPath,
1509
- reportPath: result.reportPath ?? null,
1510
- });
1511
- if (!succeeded)
1512
- process.exitCode = 1;
1513
- return;
1514
- }
1515
- if (succeeded) {
1516
- spinner.succeed(`Job completed (exit code: ${result.meta.exitCode})`);
1517
- }
1518
- else if (result.meta.status === 'timeout') {
1519
- spinner.warn(`Job timed out after ${job.timeout}`);
1520
- }
1521
- else {
1522
- spinner.fail(`Job failed (exit code: ${result.meta.exitCode})`);
1523
- }
1524
- console.log(chalk.gray(` Run: ${result.meta.runId}`));
1525
- console.log(chalk.gray(` Log: ${logPath}`));
1526
- if (result.meta.errorMessage) {
1527
- console.log(chalk.gray(` Reason: ${result.meta.errorMessage}`));
1528
- }
1529
- if (result.reportPath) {
1530
- console.log(chalk.bold('\nReport:\n'));
1531
- console.log(fs.readFileSync(result.reportPath, 'utf-8'));
1532
- }
1533
- if (!succeeded)
1534
- process.exitCode = 1;
1535
- }
1536
- catch (err) {
1537
- if (options.json) {
1538
- writeJson({ error: err.message });
1539
- process.exit(1);
1540
- }
1541
- spinner.fail('Execution failed');
1542
- console.error(chalk.red(err.message));
1543
- process.exit(1);
1544
- }
1545
- });
1546
- routinesCmd
1547
- .command('catchup')
1548
- .description('Run any routines that missed their last scheduled fire on demand. The daemon already does this every 5 minutes — use this to force a pass now. Detached: runs in the background under the scheduler.')
1549
- .option('--dry-run', 'Record the misses and list them without running anything')
1550
- .action(async (options) => {
1551
- const overdue = detectOverdueJobs();
1552
- if (overdue.length === 0) {
1553
- console.log(chalk.gray('No missed fires.'));
1554
- return;
1555
- }
1556
- console.log(chalk.bold(`${overdue.length} missed fire(s):\n`));
1557
- for (const job of overdue) {
1558
- const last = job.lastRanAt ? job.lastRanAt.toLocaleString() : 'never';
1559
- console.log(` ${chalk.cyan(job.name)} — missed ${chalk.gray(job.expectedAt.toLocaleString())}, last ran ${chalk.gray(last)}`);
1560
- }
1561
- if (!options.dryRun && !isDaemonRunning()) {
1562
- try {
1563
- assertDaemonEnabled();
1564
- const started = startDaemon();
1565
- if (started.pid) {
1566
- console.log(chalk.gray(`\nStarted scheduler (PID: ${started.pid}) so catchup runs are monitored.`));
1567
- }
1568
- }
1569
- catch (err) {
1570
- console.log(chalk.yellow(`\n${err.message}`));
1571
- }
1572
- }
1573
- console.log(chalk.bold(options.dryRun ? '\nRecording misses...' : '\nTriggering catchup runs...'));
1574
- const outcomes = await runCatchup({ overdue, dryRun: options.dryRun });
1575
- for (const o of outcomes) {
1576
- if (o.result === 'ran') {
1577
- console.log(` ${o.name} → ${chalk.green('started')} (run: ${o.runId})`);
1578
- }
1579
- else if (o.result === 'recorded') {
1580
- const why = options.dryRun ? 'dry run' : 'catchup: false';
1581
- console.log(` ${o.name} → ${chalk.yellow('recorded as missed')} (${why})`);
1582
- }
1583
- else if (o.result === 'claimed-elsewhere') {
1584
- console.log(` ${o.name} → ${chalk.gray('already claimed by the scheduler')}`);
1585
- }
1586
- else {
1587
- console.log(` ${o.name} → ${chalk.red('failed to start')}: ${o.error}`);
1588
- }
1589
- }
1590
- console.log(chalk.gray('\nTrack progress with: agents routines runs <name>'));
1591
- });
1592
- routinesCmd
1593
- .command('webhook')
1594
- .description('Fire trigger-based routines from a single webhook payload (read from --file or stdin). One-shot: matches and fires, then exits.')
1595
- .option('--source <name>', 'Webhook source: github or linear', 'github')
1596
- .requiredOption('--event <name>', 'Source event name: GitHub X-GitHub-Event value, or Linear payload type')
1597
- .option('--file <path>', 'Read the webhook JSON payload from this file instead of stdin')
1598
- .option('--dry-run', 'Show which routines would fire without firing them')
1599
- .action(async (options) => {
1600
- const source = options.source;
1601
- if (source !== 'github' && source !== 'linear') {
1602
- console.log(chalk.red(`Unknown webhook source "${options.source}". Use github or linear.`));
1603
- process.exit(1);
1604
- }
1605
- let raw;
1606
- if (options.file) {
1607
- const resolved = path.resolve(options.file);
1608
- if (!fs.existsSync(resolved)) {
1609
- console.log(chalk.red(`File not found: ${resolved}`));
1610
- process.exit(1);
1611
- }
1612
- raw = fs.readFileSync(resolved, 'utf-8');
1613
- }
1614
- else {
1615
- if (process.stdin.isTTY) {
1616
- console.log(chalk.red('No payload provided. Pass --file <path> or pipe the webhook JSON on stdin.'));
1617
- process.exit(1);
1618
- }
1619
- const chunks = [];
1620
- for await (const chunk of process.stdin)
1621
- chunks.push(chunk);
1622
- raw = Buffer.concat(chunks).toString('utf-8');
1623
- }
1624
- let payload;
1625
- try {
1626
- const parsed = raw.trim() ? JSON.parse(raw) : {};
1627
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1628
- throw new Error('payload must be a JSON object');
1629
- }
1630
- payload = parsed;
1631
- }
1632
- catch (err) {
1633
- console.log(chalk.red(`Invalid webhook payload JSON: ${err.message}`));
1634
- process.exit(1);
1635
- }
1636
- const webhook = { source, event: options.event, payload };
1637
- if (options.dryRun) {
1638
- const matched = matchJobsToWebhook(listAllJobs(), webhook);
1639
- if (matched.length === 0) {
1640
- console.log(chalk.gray(`No routines match a ${source}:${options.event} event for this payload.`));
1641
- return;
1642
- }
1643
- console.log(chalk.bold(`${matched.length} routine(s) would fire on ${source}:${options.event}:\n`));
1644
- for (const job of matched) {
1645
- console.log(` ${chalk.cyan(job.name)} — ${fireConditionLabel(job)}`);
1646
- }
1647
- console.log(chalk.gray('\n(dry run — no routines triggered)'));
1648
- return;
1649
- }
1650
- if (!isDaemonRunning()) {
1651
- if (!isDaemonEnabled()) {
1652
- console.log(chalk.yellow(`Daemon is disabled (daemon.enabled=false) — run(s) below fire but are not monitored. Re-enable with: agents daemon enable`));
1653
- }
1654
- else {
1655
- try {
1656
- const started = startDaemon();
1657
- if (started.pid) {
1658
- console.log(chalk.gray(`Started scheduler (PID: ${started.pid}) so webhook runs are monitored.`));
1659
- }
1660
- }
1661
- catch (err) {
1662
- if (err instanceof RedirectedHomeDaemonError) {
1663
- console.log(chalk.yellow(err.message));
1664
- }
1665
- else {
1666
- throw err;
1667
- }
1668
- }
1669
- }
1670
- }
1671
- const fired = await fireWebhookJobs(webhook);
1672
- if (fired.length === 0) {
1673
- console.log(chalk.gray(`No routines match a ${source}:${options.event} event for this payload.`));
1674
- return;
1675
- }
1676
- console.log(chalk.bold(`Fired ${fired.length} routine(s) on ${source}:${options.event}:\n`));
1677
- for (const f of fired) {
1678
- console.log(` ${chalk.cyan(f.jobName)} → ${chalk.green('started')} (run: ${f.runId})`);
1679
- }
1680
- console.log(chalk.gray('\nTrack progress with: agents routines runs <name>'));
1681
- });
1682
- routinesCmd
1683
- .command('logs [name]')
1684
- .description('Show a run’s concise summary — status + extracted report. --full for the raw stdout stream; --run for a specific past run.')
1685
- .option('-r, --run <runId>', 'Show logs from this run ID instead of the latest')
1686
- .option('-m, --full', 'Show the full raw stdout stream instead of the concise summary')
1687
- .action(async (name, options) => {
1688
- if (!name) {
1689
- name = await pickJob('Select job to view logs', undefined, ['agents routines logs <name>', 'agents routines logs <name> --run <run-id>']) ?? undefined;
1690
- if (!name)
1691
- return;
1692
- }
1693
- const run = options.run
1694
- ? listRuns(name).find((r) => r.runId === options.run)
1695
- : getLatestRun(name);
1696
- if (!run) {
1697
- console.log(chalk.yellow(options.run ? `No run '${options.run}' for job '${name}'` : `No runs found for job '${name}'`));
1698
- return;
1699
- }
1700
- const runId = run.runId;
1701
- const logPath = path.join(getRunDir(name, runId), 'stdout.log');
1702
- if (options.full) {
1703
- if (!fs.existsSync(logPath)) {
1704
- console.log(chalk.yellow(`Log not found: ${logPath}`));
1705
- return;
1706
- }
1707
- console.log(chalk.gray(`Run: ${runId}\n`));
1708
- console.log(fs.readFileSync(logPath, 'utf-8'));
1709
- return;
1710
- }
1711
- const statusColor = run.status === 'completed' ? chalk.green
1712
- : run.status === 'missed' ? chalk.magenta
1713
- : run.status === 'failed' || run.status === 'timeout' ? chalk.red
1714
- : chalk.yellow;
1715
- console.log(chalk.bold(name) + chalk.gray(` run ${runId}`));
1716
- console.log(statusColor(run.status) +
1717
- chalk.gray(` ${run.startedAt}`) +
1718
- chalk.gray(formatRunDuration(run.startedAt, run.completedAt)) +
1719
- (run.exitCode !== null && run.exitCode !== undefined ? chalk.gray(` exit ${run.exitCode}`) : ''));
1720
- const logsReason = runFailureReason(run);
1721
- if (logsReason)
1722
- console.log(chalk.red('reason: ') + chalk.gray(logsReason));
1723
- console.log(chalk.gray('─'.repeat(60)));
1724
- const reportPath = path.join(getRunDir(name, runId), 'report.md');
1725
- if (fs.existsSync(reportPath)) {
1726
- console.log(fs.readFileSync(reportPath, 'utf-8').trimEnd());
1727
- console.log(chalk.gray('\n(pass --full for the raw stdout stream)'));
1728
- return;
1729
- }
1730
- if (fs.existsSync(logPath)) {
1731
- const lines = fs.readFileSync(logPath, 'utf-8').split('\n');
1732
- const tail = lines.slice(-40).join('\n').trimEnd();
1733
- console.log(chalk.gray('(no report extracted — showing the last lines of stdout)'));
1734
- if (tail)
1735
- console.log(tail);
1736
- console.log(chalk.gray('\n(pass --full for the raw stdout stream)'));
1737
- }
1738
- else {
1739
- console.log(chalk.gray('(no output captured for this run)'));
1740
- }
1741
- });
1742
- routinesCmd
1743
- .command('report [name]')
1744
- .description('Show the extracted report from the most recent execution. Reports are parsed from agent output on completion.')
1745
- .option('-r, --run <runId>', 'Show report from this run ID instead of the latest')
1746
- .action(async (name, options) => {
1747
- if (!name) {
1748
- name = await pickJob('Select job to view report', undefined, ['agents routines report <name>', 'agents routines report <name> --run <run-id>']) ?? undefined;
1749
- if (!name)
1750
- return;
1751
- }
1752
- let runId = options.run;
1753
- if (!runId) {
1754
- const latest = getLatestRun(name);
1755
- if (!latest) {
1756
- console.log(chalk.yellow(`No runs found for job '${name}'`));
1757
- return;
1758
- }
1759
- runId = latest.runId;
1760
- }
1761
- const reportPath = path.join(getRunDir(name, runId), 'report.md');
1762
- if (!fs.existsSync(reportPath)) {
1763
- console.log(chalk.yellow(`No report found for run ${runId}`));
1764
- console.log(chalk.gray(` Reports are extracted from agent output on completion`));
1765
- return;
1766
- }
1767
- console.log(chalk.gray(`Run: ${runId}\n`));
1768
- console.log(fs.readFileSync(reportPath, 'utf-8'));
1769
- });
1770
- routinesCmd
1771
- .command('doctor [name]')
1772
- .description('Check a routine\'s execution-context and harness readiness. Bare or --all checks every routine; --fix applies safe activation repairs (activate a now-ready paused routine; pause a broken active one).')
1773
- .option('--all', 'Check every routine (the default when no name is given)')
1774
- .option('--fix', 'Apply safe, deterministic activation repairs')
1775
- .option('--json', 'Machine-readable output')
1776
- .action(async (name, options) => {
1777
- const all = options.all || !name;
1778
- let targets;
1779
- if (all) {
1780
- targets = listAllJobs();
1781
- }
1782
- else {
1783
- const job = readJob(name);
1784
- if (!job) {
1785
- if (options.json) {
1786
- writeJson({ ok: false, error: `routine '${name}' not found` });
1787
- return;
1788
- }
1789
- console.error(chalk.red(`Routine '${name}' not found`));
1790
- process.exit(1);
1791
- }
1792
- targets = [job];
1793
- }
1794
- const thisDevice = normalizeHost(machineId());
1795
- const results = await Promise.all(targets.map(async (job) => {
1796
- const deviceMatch = !job.devices || job.devices.map(normalizeHost).includes(thisDevice);
1797
- const readiness = await evaluateActivationReadinessLive(job);
1798
- let action;
1799
- if (options.fix && deviceMatch) {
1800
- if (readiness.ready && !job.enabled) {
1801
- setJobEnabled(job.name, true);
1802
- action = 'activated';
1803
- }
1804
- else if (!readiness.ready && job.enabled) {
1805
- setJobEnabled(job.name, false);
1806
- action = 'paused';
1807
- }
1808
- }
1809
- return {
1810
- name: job.name,
1811
- ready: readiness.ready,
1812
- active: job.enabled,
1813
- deviceScoped: deviceMatch,
1814
- ...(readiness.readiness ? { readiness: readiness.readiness } : {}),
1815
- ...(action ? { action } : {}),
1816
- };
1817
- }));
1818
- if (options.fix && results.some((r) => r.action) && isDaemonRunning()) {
1819
- signalDaemonReload();
1820
- }
1821
- if (options.json) {
1822
- writeJson({ ok: true, results });
1823
- return;
1824
- }
1825
- const blocked = results.filter((r) => !r.ready);
1826
- for (const r of results) {
1827
- if (r.ready) {
1828
- console.log(`${chalk.green('✓')} ${r.name}${r.action === 'activated' ? chalk.gray(' (activated)') : ''}`);
1829
- }
1830
- else {
1831
- const rd = r.readiness;
1832
- console.log(`${chalk.red('✗')} ${r.name} — ${chalk.yellow(rd.code)}${r.action === 'paused' ? chalk.gray(' (paused)') : ''}`);
1833
- console.log(chalk.gray(` ${rd.message}`));
1834
- if (rd.repair)
1835
- console.log(chalk.gray(` repair: ${rd.repair}`));
1836
- }
1837
- }
1838
- if (blocked.length > 0 && !options.fix) {
1839
- console.log(chalk.gray(`\n${blocked.length} routine${blocked.length === 1 ? '' : 's'} blocked — re-run with --fix to pause them, or apply each repair above.`));
1840
- }
1841
- });
1842
- routinesCmd
1843
- .command('enable [name]')
1844
- .aliases(['resume'])
1845
- .description('Enable a routine so the daemon schedules it. Also materialises a project routine (from the current project or a registered one) on first enable — one step, no separate opt-in.')
1846
- .action(async (name) => {
1847
- await enableRoutineAction(name);
1848
- });
1849
- routinesCmd
1850
- .command('disable [name]')
1851
- .aliases(['pause'])
1852
- .description('Disable a routine. Stops scheduling future runs; turn it back on with: agents routines enable <name>.')
1853
- .action(async (name) => {
1854
- await disableRoutineAction(name);
1855
- });
1856
- routinesCmd
1857
- .command('devices [name]')
1858
- .description('View or change the devices where a routine is enabled. Without flags, opens an interactive picker (requires a TTY).')
1859
- .option('--set <devices>', 'Replace the enabled-device set with this comma-separated list')
1860
- .option('--clear', 'Disable the routine on every registered device')
1861
- .action(async (name, options) => {
1862
- const hasSet = options.set !== undefined;
1863
- if (hasSet && options.clear) {
1864
- console.log(chalk.red('--set and --clear are mutually exclusive'));
1865
- process.exit(1);
1866
- }
1867
- if (!name) {
1868
- name = await pickJob('Select routine', undefined, ['agents routines devices <name>']) ?? undefined;
1869
- if (!name)
1870
- return;
1871
- }
1872
- const job = readJob(name);
1873
- if (!job) {
1874
- console.log(chalk.red(`Job '${name}' not found`));
1875
- process.exit(1);
1876
- }
1877
- const applyDevices = async (selected) => {
1878
- const registry = await loadDevices();
1879
- const registered = Object.keys(registry).map(normalizeHost);
1880
- const all = [...new Set([...registered, machineId()].map(normalizeHost))].sort();
1881
- const selectedSet = new Set(selected.map(normalizeHost));
1882
- const unknown = [...selectedSet].filter((device) => !all.includes(device));
1883
- if (unknown.length > 0)
1884
- throw new Error(`Unknown device${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`);
1885
- const skipped = [];
1886
- const failedTargets = [];
1887
- for (const device of all) {
1888
- const action = selectedSet.has(device) ? 'resume' : 'pause';
1889
- const isTarget = selectedSet.has(device);
1890
- if (device === normalizeHost(machineId())) {
1891
- setJobEnabled(name, action === 'resume');
1892
- if (isDaemonRunning())
1893
- signalDaemonReload();
1894
- continue;
1895
- }
1896
- const launch = getCliLaunch(['routines', action, name, '--device', device]);
1897
- const result = spawnSync(launch.command, launch.args, { stdio: 'inherit', env: process.env });
1898
- if ((result.status ?? 1) !== 0) {
1899
- if (isTarget) {
1900
- failedTargets.push(device);
1901
- }
1902
- else {
1903
- skipped.push({ device, action });
1904
- }
1905
- }
1906
- }
1907
- for (const s of skipped) {
1908
- console.log(chalk.yellow(`Skipped ${s.action} of '${name}' on ${s.device} (unreachable; will sync when online)`));
1909
- }
1910
- if (failedTargets.length > 0) {
1911
- const offlineNote = skipped.length > 0
1912
- ? ` (also skipped offline: ${skipped.map((s) => s.device).join(', ')})`
1913
- : '';
1914
- throw new Error(`Could not enable '${name}' on: ${failedTargets.join(', ')}${offlineNote}`);
1915
- }
1916
- const offlineNote = skipped.length > 0
1917
- ? ` (${skipped.length} offline device${skipped.length === 1 ? '' : 's'} skipped)`
1918
- : '';
1919
- console.log(chalk.green(selected.length === 0
1920
- ? `Routine '${name}' disabled on every registered device${offlineNote}`
1921
- : `Routine '${name}' enabled on: ${selected.join(', ')}${offlineNote}`));
1922
- };
1923
- if (options.clear) {
1924
- await applyDevices([]);
1925
- return;
1926
- }
1927
- if (hasSet) {
1928
- await applyDevices(await parseAndValidateDevices(options.set));
1929
- return;
1930
- }
1931
- if (!isInteractiveTerminal()) {
1932
- requireInteractiveSelection('device allowlist', ['agents routines devices <name> --set a,b', 'agents routines devices <name> --clear']);
1933
- }
1934
- const registry = await loadDevices();
1935
- const registeredNames = Object.keys(registry).map((k) => normalizeHost(k)).sort();
1936
- if (registeredNames.length === 0) {
1937
- console.log(chalk.yellow('No devices registered. Enroll with: agents devices sync'));
1938
- return;
1939
- }
1940
- const currentSet = new Set(devicesWithRoutineEnabled(name).map(normalizeHost));
1941
- try {
1942
- const { checkbox } = await import('@inquirer/prompts');
1943
- const selected = await checkbox({
1944
- message: `Devices where '${name}' is enabled (space to toggle, enter to confirm):`,
1945
- choices: registeredNames.map((d) => ({
1946
- value: d,
1947
- name: d,
1948
- checked: currentSet.has(d),
1949
- })),
1950
- });
1951
- await applyDevices(selected);
1952
- }
1953
- catch (err) {
1954
- if (isPromptCancelled(err)) {
1955
- console.log(chalk.gray('Cancelled'));
1956
- return;
1957
- }
1958
- throw err;
1959
- }
1960
- });
1961
- routinesCmd
1962
- .command('start')
1963
- .description('Enable and reload the scheduler service. Usually unnecessary — it auto-starts when you add your first routine.')
1964
- .action(() => {
1965
- try {
1966
- assertDaemonEnabled();
1967
- assertSchedulerEnabled();
1968
- }
1969
- catch (err) {
1970
- console.error(chalk.red(err.message));
1971
- process.exit(1);
1972
- }
1973
- setDaemonServiceEnabled('scheduler', true);
1974
- let result;
1975
- try {
1976
- result = startDaemon();
1977
- }
1978
- catch (err) {
1979
- if (err instanceof RedirectedHomeDaemonError) {
1980
- console.error(chalk.red(err.message));
1981
- process.exit(1);
1982
- }
1983
- throw err;
1984
- }
1985
- if (result.method === 'already-running') {
1986
- const reloaded = signalDaemonReload();
1987
- console.log(reloaded
1988
- ? chalk.yellow(`Scheduler service enabled (shared daemon PID: ${result.pid}) — reloaded`)
1989
- : chalk.yellow(`Scheduler service enabled, but live reload is unavailable. Restart deliberately with: agents daemon restart`));
1990
- }
1991
- else if (result.pid) {
1992
- console.log(chalk.green(`Scheduler started (PID: ${result.pid})`));
1993
- }
1994
- else {
1995
- console.log(chalk.yellow('Scheduler start dispatched but no PID surfaced. Check `agents routines status`.'));
1996
- }
1997
- });
1998
- routinesCmd
1999
- .command('stop')
2000
- .description('Stop only the scheduler service. The shared daemon and its other services (usage sync, session index, watchdog, and the rest) stay running.')
2001
- .action(() => {
2002
- const daemonRunning = isDaemonRunning();
2003
- setDaemonServiceEnabled('scheduler', false);
2004
- if (daemonRunning && !signalDaemonReload()) {
2005
- console.log(chalk.yellow('Scheduler service disabled, but live reload is unavailable. It will stay off after the next daemon start.'));
2006
- return;
2007
- }
2008
- console.log(daemonRunning
2009
- ? chalk.green('Scheduler service stopped; shared daemon is still running')
2010
- : chalk.yellow('Scheduler service disabled; shared daemon was already stopped'));
2011
- });
2012
- routinesCmd
2013
- .command('status')
2014
- .description('Show scheduler service state, shared-daemon state, enabled routines, and upcoming runs.')
2015
- .option('--json', 'Emit machine-readable scheduler service + device gate + daemon + per-routine status (owner device, last fire, last error, in-flight run)')
2016
- .action((options) => {
2017
- try {
2018
- monitorRunningJobs();
2019
- }
2020
- catch { }
2021
- const status = getDaemonStatus();
2022
- const schedulerServiceEnabled = isDaemonServiceEnabled('scheduler');
2023
- const schedulerDeviceEnabled = isSchedulerEnabled();
2024
- const schedulerState = schedulerServiceEnabled && schedulerDeviceEnabled ? status.state : 'stopped';
2025
- if (options.json) {
2026
- const rows = buildRoutineStatusRows();
2027
- writeJson({
2028
- device: machineId(),
2029
- scheduler: {
2030
- state: schedulerState,
2031
- serviceEnabled: schedulerServiceEnabled,
2032
- deviceEnabled: schedulerDeviceEnabled,
2033
- daemonState: status.state,
2034
- pid: status.pid,
2035
- binaryPath: status.binaryPath,
2036
- heartbeat: status.heartbeat
2037
- ? {
2038
- lastTick: status.heartbeat.lastTick,
2039
- ageSec: Math.round((Date.now() - Date.parse(status.heartbeat.lastTick)) / 1000),
2040
- }
2041
- : null,
2042
- enabled: rows.filter((r) => r.enabled).length,
2043
- total: rows.length,
2044
- },
2045
- routines: rows,
2046
- });
2047
- return;
2048
- }
2049
- console.log(chalk.bold('Scheduler\n'));
2050
- const stateLabel = schedulerState === 'running'
2051
- ? chalk.green('running')
2052
- : chalk.gray('stopped');
2053
- console.log(` Status: ${stateLabel}`);
2054
- console.log(` Daemon: ${status.running ? chalk.green('running') : chalk.gray('stopped')}`);
2055
- if (status.pid)
2056
- console.log(` PID: ${status.pid}`);
2057
- if (status.binaryPath)
2058
- console.log(` Binary: ${chalk.gray(status.binaryPath)}`);
2059
- if (status.heartbeat) {
2060
- const ago = Math.round((Date.now() - Date.parse(status.heartbeat.lastTick)) / 1000);
2061
- console.log(` Heartbeat: ${chalk.gray(`${ago} sec ago`)}`);
2062
- }
2063
- const jobs = listAllJobs();
2064
- const enabled = jobs.filter((j) => j.enabled);
2065
- console.log(` Routines: ${enabled.length} enabled / ${jobs.length} total`);
2066
- if (schedulerState === 'running' && enabled.length > 0) {
2067
- const scheduler = new JobScheduler(async () => { });
2068
- scheduler.loadAll();
2069
- const scheduled = scheduler.listScheduled();
2070
- console.log(chalk.bold('\n Upcoming Runs\n'));
2071
- for (const job of scheduled) {
2072
- const next = job.nextRun ? job.nextRun.toLocaleString() : 'unknown';
2073
- console.log(` ${chalk.cyan(job.name.padEnd(24))} next: ${chalk.gray(next)}`);
2074
- }
2075
- scheduler.stopAll();
2076
- }
2077
- else if (schedulerState !== 'running' && jobs.length > 0) {
2078
- console.log(chalk.gray('\n Start the scheduler to begin firing routines: agents routines start'));
2079
- }
2080
- });
2081
- routinesCmd
2082
- .command('sync [path]')
2083
- .description('Refresh materialised project routines from their .agents/routines/*.yml sources. Definition-only — never changes what is enabled. With no path, refreshes every project you have enabled a routine from. Also runs automatically on daemon reload (SIGHUP).')
2084
- .option('--json', 'Emit machine-readable JSON')
2085
- .action(async (projectPath, options) => {
2086
- if (projectPath) {
2087
- const root = path.resolve(projectPath);
2088
- const sync = syncProjectRoutines(root);
2089
- if (isDaemonRunning())
2090
- signalDaemonReload();
2091
- if (options.json) {
2092
- writeJson({ ok: true, ...sync });
2093
- return;
2094
- }
2095
- if (sync.synced.length === 0 && sync.skipped.length === 0 && sync.removed.length === 0 && sync.errors.length === 0) {
2096
- console.log(chalk.gray(`No enabled routines materialised from ${displayProjectPath(root)}.`));
2097
- console.log(chalk.gray(' Enable one with: agents routines enable <name>'));
2098
- return;
2099
- }
2100
- printSyncResult(sync);
2101
- return;
2102
- }
2103
- const all = syncAllProjectRoutines();
2104
- if (isDaemonRunning())
2105
- signalDaemonReload();
2106
- if (options.json) {
2107
- writeJson({ ok: true, ...all });
2108
- return;
2109
- }
2110
- if (all.projects.length === 0 && all.missing.length === 0) {
2111
- console.log(chalk.gray('No project routines materialised yet.'));
2112
- console.log(chalk.gray(' Enable one with: agents routines enable <name>'));
2113
- return;
2114
- }
2115
- for (const p of all.projects)
2116
- printSyncResult(p);
2117
- for (const m of all.missing) {
2118
- console.log(chalk.yellow(`Missing project root for a materialised routine: ${displayProjectPath(m)}`));
2119
- }
2120
- });
2121
- routinesCmd
2122
- .command('scheduler-logs')
2123
- .description('Read scheduler log output (for debugging why a routine did not fire). Use --follow to stream.')
2124
- .option('-n, --lines <number>', 'Show this many recent lines (default: 50)', '50')
2125
- .option('-f, --follow', 'Stream log output in real time (like tail -f)')
2126
- .action(async (options) => {
2127
- if (options.follow) {
2128
- const { followFile } = await import('../lib/log-follow.js');
2129
- const logPath = getDaemonLogPath();
2130
- const recent = readDaemonLog(parseInt(options.lines, 10));
2131
- if (recent)
2132
- console.log(recent);
2133
- const stop = followFile(logPath, (text) => process.stdout.write(text), { fromEnd: true });
2134
- process.on('SIGINT', () => { stop(); process.exit(0); });
2135
- return;
2136
- }
2137
- const lines = parseInt(options.lines, 10);
2138
- const output = readDaemonLog(lines);
2139
- if (output) {
2140
- console.log(output);
2141
- }
2142
- else {
2143
- console.log(chalk.gray('No scheduler logs'));
2144
- }
2145
- });
2146
- for (const sub of routinesCmd.commands) {
2147
- addHostOption(sub);
2148
- }
2149
- }