@phnx-labs/agents-cli 1.23.27 → 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.
- package/CHANGELOG.md +8 -0
- package/README.md +33 -82
- package/dist/bootstrap.js +0 -17
- package/dist/cli/command-registry.js +0 -2
- package/dist/commands/cloud.js +0 -58
- package/dist/commands/config.js +0 -4
- package/dist/commands/daemon-index.js +1 -1
- package/dist/commands/daemon.js +14 -63
- package/dist/commands/doctor.js +0 -12
- package/dist/commands/events.js +1 -1
- package/dist/commands/feed.d.ts +1 -3
- package/dist/commands/feed.js +1 -6
- package/dist/commands/fleet-capture.js +2 -4
- package/dist/commands/focus.d.ts +0 -1
- package/dist/commands/focus.js +2 -4
- package/dist/commands/inspect.d.ts +1 -19
- package/dist/commands/inspect.js +8 -474
- package/dist/commands/mine.js +1 -1
- package/dist/commands/prune.js +2 -64
- package/dist/commands/ps-roster.d.ts +0 -4
- package/dist/commands/ps-roster.js +2 -30
- package/dist/commands/ps.js +1 -4
- package/dist/commands/repo.d.ts +1 -1
- package/dist/commands/repo.js +4 -4
- package/dist/commands/sessions-browser.d.ts +0 -2
- package/dist/commands/sessions-browser.js +2 -32
- package/dist/commands/sessions-optimize.js +3 -4
- package/dist/commands/setup-mine.js +0 -1
- package/dist/commands/ssh.js +8 -9
- package/dist/commands/sync.js +1 -1
- package/dist/commands/update.js +2 -2
- package/dist/commands/watchdog.js +3 -4
- package/dist/lib/accounting/rotate.d.ts +0 -2
- package/dist/lib/accounting/rotate.js +1 -4
- package/dist/lib/agent-spec/agents.d.ts +0 -1
- package/dist/lib/agent-spec/agents.js +0 -8
- package/dist/lib/auth-health.d.ts +0 -1
- package/dist/lib/auth-health.js +0 -3
- package/dist/lib/cli-entry.d.ts +0 -1
- package/dist/lib/cli-entry.js +0 -36
- package/dist/lib/cloud/types.d.ts +0 -2
- package/dist/lib/config-keys.d.ts +1 -1
- package/dist/lib/config-keys.js +1 -4
- package/dist/lib/daemon/daemon.d.ts +0 -4
- package/dist/lib/daemon/daemon.js +6 -202
- package/dist/lib/daemon/heartbeat-service.d.ts +1 -1
- package/dist/lib/daemon/heartbeat-service.js +1 -8
- package/dist/lib/daemon-services.d.ts +1 -1
- package/dist/lib/daemon-services.js +1 -11
- package/dist/lib/device-config.d.ts +0 -2
- package/dist/lib/device-config.js +4 -22
- package/dist/lib/devices/config-migration.js +1 -3
- package/dist/lib/exec.d.ts +2 -5
- package/dist/lib/exec.js +18 -18
- package/dist/lib/factory/snapshot.d.ts +0 -5
- package/dist/lib/factory/snapshot.js +1 -28
- package/dist/lib/feed/events.d.ts +1 -11
- package/dist/lib/feed/events.js +0 -20
- package/dist/lib/feed/feed.d.ts +0 -2
- package/dist/lib/feed-outcome.d.ts +0 -2
- package/dist/lib/feed-outcome.js +0 -5
- package/dist/lib/fleet/capture.d.ts +0 -1
- package/dist/lib/fleet/capture.js +0 -3
- package/dist/lib/fleet/manifest.js +0 -6
- package/dist/lib/fleet/types.d.ts +0 -1
- package/dist/lib/harness/adapter.d.ts +0 -7
- package/dist/lib/harness/adapters/claude.js +0 -18
- package/dist/lib/harness/adapters/codex.js +0 -10
- package/dist/lib/harness/adapters/cursor.js +0 -11
- package/dist/lib/harness/adapters/kimi.js +0 -3
- package/dist/lib/harness/adapters/muse.js +0 -11
- package/dist/lib/harness/index.d.ts +1 -1
- package/dist/lib/harness/index.js +0 -2
- package/dist/lib/hosts/passthrough.js +2 -10
- package/dist/lib/hosts/ready.d.ts +0 -4
- package/dist/lib/hosts/ready.js +0 -9
- package/dist/lib/hosts/reconcile.d.ts +0 -1
- package/dist/lib/hosts/reconcile.js +0 -8
- package/dist/lib/installations/migrate.d.ts +0 -2
- package/dist/lib/installations/migrate.js +0 -145
- package/dist/lib/loop.js +1 -2
- package/dist/lib/menubar/snapshot.d.ts +0 -1
- package/dist/lib/menubar/snapshot.js +1 -4
- package/dist/lib/placement.d.ts +1 -2
- package/dist/lib/placement.js +4 -24
- package/dist/lib/profiles.d.ts +0 -1
- package/dist/lib/profiles.js +0 -6
- package/dist/lib/projects.js +15 -17
- package/dist/lib/session/active.d.ts +1 -3
- package/dist/lib/session/active.js +0 -4
- package/dist/lib/session/db.d.ts +0 -1
- package/dist/lib/session/db.js +4 -8
- package/dist/lib/session/discover.d.ts +0 -1
- package/dist/lib/session/discover.js +3 -128
- package/dist/lib/session/live-metadata.js +0 -2
- package/dist/lib/session/presentation.d.ts +0 -1
- package/dist/lib/session/presentation.js +3 -8
- package/dist/lib/session/selection.d.ts +0 -2
- package/dist/lib/session/selection.js +2 -12
- package/dist/lib/staleness/detectors/commands.d.ts +1 -1
- package/dist/lib/staleness/detectors/hooks.d.ts +1 -1
- package/dist/lib/staleness/detectors/mcp.d.ts +1 -1
- package/dist/lib/staleness/detectors/permissions.d.ts +1 -1
- package/dist/lib/staleness/detectors/plugins.d.ts +1 -1
- package/dist/lib/staleness/detectors/rules.d.ts +1 -1
- package/dist/lib/staleness/detectors/skills.d.ts +1 -1
- package/dist/lib/staleness/detectors/subagents.d.ts +1 -1
- package/dist/lib/staleness/detectors/workflows.d.ts +1 -1
- package/dist/lib/staleness/writers/commands.d.ts +1 -1
- package/dist/lib/staleness/writers/hooks.d.ts +1 -1
- package/dist/lib/staleness/writers/mcp.d.ts +1 -1
- package/dist/lib/staleness/writers/permissions.d.ts +1 -1
- package/dist/lib/staleness/writers/plugins.d.ts +1 -1
- package/dist/lib/staleness/writers/rules.d.ts +1 -1
- package/dist/lib/staleness/writers/skills.d.ts +1 -1
- package/dist/lib/staleness/writers/subagents.d.ts +1 -1
- package/dist/lib/staleness/writers/workflows.d.ts +1 -1
- package/dist/lib/startup/command-registry.js +5 -2
- package/dist/lib/state.d.ts +0 -3
- package/dist/lib/state.js +2 -25
- package/dist/lib/types.d.ts +0 -1
- package/dist/lib/watchdog/runner.d.ts +0 -2
- package/dist/lib/watchdog/runner.js +0 -2
- package/package.json +1 -1
- package/scripts/postinstall.js +2 -2
- package/dist/commands/routines.d.ts +0 -14
- package/dist/commands/routines.js +0 -2149
- package/dist/commands/routines.test-fixture.d.ts +0 -52
- package/dist/commands/routines.test-fixture.js +0 -254
- package/dist/lib/catchup.d.ts +0 -19
- package/dist/lib/catchup.js +0 -83
- package/dist/lib/daemon/catchup-service.d.ts +0 -18
- package/dist/lib/daemon/catchup-service.js +0 -21
- package/dist/lib/daemon/runner.d.ts +0 -91
- package/dist/lib/daemon/runner.js +0 -1927
- package/dist/lib/harness/adapters/droid.d.ts +0 -2
- package/dist/lib/harness/adapters/droid.js +0 -14
- package/dist/lib/overdue.d.ts +0 -9
- package/dist/lib/overdue.js +0 -74
- package/dist/lib/routine-activation.d.ts +0 -13
- package/dist/lib/routine-activation.js +0 -117
- package/dist/lib/routine-context.d.ts +0 -59
- package/dist/lib/routine-context.js +0 -181
- package/dist/lib/routine-notify-owner.d.ts +0 -4
- package/dist/lib/routine-notify-owner.js +0 -49
- package/dist/lib/routine-notify.d.ts +0 -17
- package/dist/lib/routine-notify.js +0 -138
- package/dist/lib/routine-process-cleanup.d.ts +0 -9
- package/dist/lib/routine-process-cleanup.js +0 -81
- package/dist/lib/routine-readiness.d.ts +0 -31
- package/dist/lib/routine-readiness.js +0 -256
- package/dist/lib/routines-format.d.ts +0 -7
- package/dist/lib/routines-format.js +0 -127
- package/dist/lib/routines-placement.d.ts +0 -16
- package/dist/lib/routines-placement.js +0 -60
- package/dist/lib/routines-project.d.ts +0 -49
- package/dist/lib/routines-project.js +0 -306
- package/dist/lib/sandbox.d.ts +0 -15
- package/dist/lib/sandbox.js +0 -309
- package/dist/lib/scheduler.d.ts +0 -23
- package/dist/lib/scheduler.js +0 -106
- package/dist/lib/scheduling/routines.d.ts +0 -264
- package/dist/lib/scheduling/routines.js +0 -1292
- package/dist/lib/triggers/webhook.d.ts +0 -26
- package/dist/lib/triggers/webhook.js +0 -181
|
@@ -1,1292 +0,0 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
import * as yaml from 'yaml';
|
|
4
|
-
import { Cron } from 'croner';
|
|
5
|
-
import { getRoutinesDir, getSystemRoutinesDir, getRunsDir, ensureAgentsDir, getProjectRoutinesDir } from '../state.js';
|
|
6
|
-
import * as os from 'os';
|
|
7
|
-
import { safeJoin, isSafeSegmentName } from '../paths.js';
|
|
8
|
-
import { isSafeProjectName, loadProjectDef, projectBasePath } from '../projects.js';
|
|
9
|
-
import { isCustomHarnessName } from '../profiles.js';
|
|
10
|
-
import { resolveRoutineExecutionContext, } from '../routine-context.js';
|
|
11
|
-
import { atomicWriteFileSync } from '../fs-atomic.js';
|
|
12
|
-
import { ALL_AGENT_IDS, ROUTINE_AGENT_IDS } from '../agents.js';
|
|
13
|
-
import { RUN_STRATEGIES } from '../accounting/rotate.js';
|
|
14
|
-
import { machineId, normalizeHost } from '../machine-id.js';
|
|
15
|
-
import { resolveActor } from '../actor.js';
|
|
16
|
-
import { percentile } from '../percentile.js';
|
|
17
|
-
import { enabledRoutineNames, devicesWithRoutineEnabled, replaceEnabledRoutines, routineEnabledOnThisDevice, setRoutineEnabledOnThisDevice, } from '../routine-activation.js';
|
|
18
|
-
import { humanizeCron, humanizeNextRun } from '../routines-format.js';
|
|
19
|
-
import { discoverProjectRoutines } from '../routines-project.js';
|
|
20
|
-
import { listProjectDefs } from '../projects.js';
|
|
21
|
-
import { monitorRunningJobs, isRunGenuinelyInFlight } from '../daemon/runner.js';
|
|
22
|
-
import { JobScheduler } from '../scheduler.js';
|
|
23
|
-
import { detectOverdueJobs } from '../overdue.js';
|
|
24
|
-
export function fireConditionLabel(job) {
|
|
25
|
-
if (job.schedule)
|
|
26
|
-
return humanizeCron(job.schedule, job.timezone);
|
|
27
|
-
if (job.trigger) {
|
|
28
|
-
if (job.trigger.type === 'github_event') {
|
|
29
|
-
const scope = job.trigger.repo
|
|
30
|
-
? ` (${job.trigger.repo}${job.trigger.branch ? `@${job.trigger.branch}` : ''})`
|
|
31
|
-
: '';
|
|
32
|
-
const filters = [
|
|
33
|
-
job.trigger.action ? `action=${job.trigger.action}` : null,
|
|
34
|
-
job.trigger.label ? `label=${job.trigger.label}` : null,
|
|
35
|
-
].filter(Boolean).join(', ');
|
|
36
|
-
return `on github:${job.trigger.event}${scope}${filters ? ` (${filters})` : ''}`;
|
|
37
|
-
}
|
|
38
|
-
const filters = [
|
|
39
|
-
job.trigger.action ? `action=${job.trigger.action}` : null,
|
|
40
|
-
job.trigger.teamKey ? `team=${job.trigger.teamKey}` : null,
|
|
41
|
-
job.trigger.label ? `label=${job.trigger.label}` : null,
|
|
42
|
-
job.trigger.stateTo ? `stateTo=${job.trigger.stateTo}` : null,
|
|
43
|
-
job.trigger.stateFrom ? `stateFrom=${job.trigger.stateFrom}` : null,
|
|
44
|
-
].filter(Boolean).join(', ');
|
|
45
|
-
return `on linear:${job.trigger.event}${filters ? ` (${filters})` : ''}`;
|
|
46
|
-
}
|
|
47
|
-
return '-';
|
|
48
|
-
}
|
|
49
|
-
export function nextRunForDisplay(job, scheduler) {
|
|
50
|
-
if (isPastOneShotRoutine(job))
|
|
51
|
-
return null;
|
|
52
|
-
return scheduler.getNextRun(job.name);
|
|
53
|
-
}
|
|
54
|
-
export function nextRunLabel(job, scheduler, now) {
|
|
55
|
-
if (isPastOneShotRoutine(job))
|
|
56
|
-
return 'expired';
|
|
57
|
-
return humanizeNextRun(scheduler.getNextRun(job.name) ?? null, now, job.timezone);
|
|
58
|
-
}
|
|
59
|
-
export function localLatestRun(job) {
|
|
60
|
-
return jobRunsOnThisDevice(job) ? getLatestRun(job.name) : null;
|
|
61
|
-
}
|
|
62
|
-
export function listJobsForDisplay(cwd) {
|
|
63
|
-
const jobs = listJobs(cwd);
|
|
64
|
-
const seen = new Set(jobs.map((j) => j.name));
|
|
65
|
-
for (const discovered of discoverProjectRoutines()) {
|
|
66
|
-
if (seen.has(discovered.name))
|
|
67
|
-
continue;
|
|
68
|
-
seen.add(discovered.name);
|
|
69
|
-
jobs.push(discovered.config);
|
|
70
|
-
}
|
|
71
|
-
return jobs;
|
|
72
|
-
}
|
|
73
|
-
export function buildRoutineListJson() {
|
|
74
|
-
try {
|
|
75
|
-
monitorRunningJobs();
|
|
76
|
-
}
|
|
77
|
-
catch { }
|
|
78
|
-
const jobs = listJobsForDisplay(process.cwd());
|
|
79
|
-
if (jobs.length === 0)
|
|
80
|
-
return [];
|
|
81
|
-
const scheduler = new JobScheduler(async () => { });
|
|
82
|
-
scheduler.loadAll();
|
|
83
|
-
try {
|
|
84
|
-
const overdueSet = new Set();
|
|
85
|
-
try {
|
|
86
|
-
for (const job of detectOverdueJobs())
|
|
87
|
-
overdueSet.add(job.name);
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
}
|
|
91
|
-
const now = new Date();
|
|
92
|
-
const knownProjectNames = new Set(listProjectDefs().map((project) => project.name));
|
|
93
|
-
return jobs.map((job) => {
|
|
94
|
-
const latestRun = localLatestRun(job);
|
|
95
|
-
const enabledDevices = devicesWithRoutineEnabled(job.name);
|
|
96
|
-
return {
|
|
97
|
-
name: job.name,
|
|
98
|
-
agent: job.agent ?? null,
|
|
99
|
-
workflow: job.workflow ?? null,
|
|
100
|
-
command: job.command ?? null,
|
|
101
|
-
repo: job.repo ?? null,
|
|
102
|
-
schedule: job.schedule ?? null,
|
|
103
|
-
scheduleHuman: fireConditionLabel(job),
|
|
104
|
-
trigger: job.trigger ?? null,
|
|
105
|
-
timezone: job.timezone ?? null,
|
|
106
|
-
devices: enabledDevices,
|
|
107
|
-
enabledDevices,
|
|
108
|
-
host: job.host ?? null,
|
|
109
|
-
hostStrategy: resolveHostStrategy(job),
|
|
110
|
-
source: job.source ?? null,
|
|
111
|
-
sourceRepo: job.source?.repo ?? job.repo ?? null,
|
|
112
|
-
sourceBranch: job.source?.branch ?? null,
|
|
113
|
-
runOnce: Boolean(job.runOnce),
|
|
114
|
-
catchup: job.catchup !== false,
|
|
115
|
-
oneShot: isOneShotRoutine(job),
|
|
116
|
-
expired: isPastOneShotRoutine(job, now),
|
|
117
|
-
runsHere: jobRunsOnThisDevice(job),
|
|
118
|
-
enabled: job.enabled,
|
|
119
|
-
overdue: overdueSet.has(job.name),
|
|
120
|
-
nextRun: nextRunForDisplay(job, scheduler)?.toISOString() ?? null,
|
|
121
|
-
nextRunHuman: nextRunLabel(job, scheduler, now),
|
|
122
|
-
lastStatus: latestRun?.status ?? null,
|
|
123
|
-
exitCode: latestRun?.exitCode ?? null,
|
|
124
|
-
failureReason: latestRun?.errorMessage ?? null,
|
|
125
|
-
lastRunStartedAt: latestRun?.startedAt ?? null,
|
|
126
|
-
lastRunCompletedAt: latestRun?.completedAt ?? null,
|
|
127
|
-
projects: job.projects ?? [],
|
|
128
|
-
projectGroup: computeProjectGroup(job.projects, knownProjectNames),
|
|
129
|
-
};
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
finally {
|
|
133
|
-
scheduler.stopAll();
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
export function buildRoutineStatusRows() {
|
|
137
|
-
try {
|
|
138
|
-
monitorRunningJobs();
|
|
139
|
-
}
|
|
140
|
-
catch { }
|
|
141
|
-
const jobs = listJobs();
|
|
142
|
-
if (jobs.length === 0)
|
|
143
|
-
return [];
|
|
144
|
-
const scheduler = new JobScheduler(async () => { });
|
|
145
|
-
scheduler.loadAll();
|
|
146
|
-
try {
|
|
147
|
-
const overdueSet = new Set();
|
|
148
|
-
try {
|
|
149
|
-
for (const job of detectOverdueJobs())
|
|
150
|
-
overdueSet.add(job.name);
|
|
151
|
-
}
|
|
152
|
-
catch {
|
|
153
|
-
}
|
|
154
|
-
const now = new Date();
|
|
155
|
-
return jobs.map((job) => {
|
|
156
|
-
const latestRun = localLatestRun(job);
|
|
157
|
-
const inFlight = latestRun && isRunGenuinelyInFlight(latestRun)
|
|
158
|
-
? {
|
|
159
|
-
runId: latestRun.runId,
|
|
160
|
-
pid: latestRun.pid,
|
|
161
|
-
startedAt: latestRun.startedAt,
|
|
162
|
-
triggerKind: latestRun.triggerKind ?? null,
|
|
163
|
-
}
|
|
164
|
-
: null;
|
|
165
|
-
return {
|
|
166
|
-
name: job.name,
|
|
167
|
-
ownerDevice: routineOwnerDevice(job),
|
|
168
|
-
ambiguousDevicePin: hasAmbiguousDevicePin(job),
|
|
169
|
-
enabledDevices: devicesWithRoutineEnabled(job.name),
|
|
170
|
-
runsHere: jobRunsOnThisDevice(job),
|
|
171
|
-
enabled: job.enabled,
|
|
172
|
-
overdue: overdueSet.has(job.name),
|
|
173
|
-
nextRun: nextRunForDisplay(job, scheduler)?.toISOString() ?? null,
|
|
174
|
-
lastStatus: latestRun?.status ?? null,
|
|
175
|
-
failureReason: latestRun?.errorMessage ?? null,
|
|
176
|
-
lastRunStartedAt: latestRun?.startedAt ?? null,
|
|
177
|
-
lastRunCompletedAt: latestRun?.completedAt ?? null,
|
|
178
|
-
inFlight,
|
|
179
|
-
};
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
finally {
|
|
183
|
-
scheduler.stopAll();
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
export const HOST_STRATEGIES = ['local', 'host', 'fleet', 'cloud'];
|
|
187
|
-
export const GITHUB_TRIGGER_EVENTS = [
|
|
188
|
-
'pull_request',
|
|
189
|
-
'push',
|
|
190
|
-
'issue_comment',
|
|
191
|
-
'workflow_run',
|
|
192
|
-
];
|
|
193
|
-
const LINEAR_TRIGGER_EVENTS = [
|
|
194
|
-
'Issue',
|
|
195
|
-
'IssueLabel',
|
|
196
|
-
'Comment',
|
|
197
|
-
'Project',
|
|
198
|
-
'Cycle',
|
|
199
|
-
];
|
|
200
|
-
export function normalizeTriggerEvent(input) {
|
|
201
|
-
const key = input.trim().toLowerCase();
|
|
202
|
-
const aliases = {
|
|
203
|
-
pull_request: 'pull_request',
|
|
204
|
-
pr: 'pull_request',
|
|
205
|
-
pr_opened: 'pull_request',
|
|
206
|
-
pull: 'pull_request',
|
|
207
|
-
push: 'push',
|
|
208
|
-
issue_comment: 'issue_comment',
|
|
209
|
-
comment: 'issue_comment',
|
|
210
|
-
workflow_run: 'workflow_run',
|
|
211
|
-
workflow: 'workflow_run',
|
|
212
|
-
};
|
|
213
|
-
return aliases[key] ?? null;
|
|
214
|
-
}
|
|
215
|
-
export function normalizeProjects(projects) {
|
|
216
|
-
if (!Array.isArray(projects) || projects.length === 0)
|
|
217
|
-
return undefined;
|
|
218
|
-
const out = [...new Set(projects.filter((p) => typeof p === 'string' && p !== ''))];
|
|
219
|
-
return out.length === 0 ? undefined : out;
|
|
220
|
-
}
|
|
221
|
-
export function computeProjectGroupKind(projects, knownProjectNames) {
|
|
222
|
-
const norm = normalizeProjects(projects);
|
|
223
|
-
if (!norm)
|
|
224
|
-
return { kind: 'operations' };
|
|
225
|
-
if (norm.length === 1 && norm[0] === '*')
|
|
226
|
-
return { kind: 'all' };
|
|
227
|
-
const hasUnknown = norm.some((p) => p !== '*' && !knownProjectNames.has(p));
|
|
228
|
-
if (hasUnknown)
|
|
229
|
-
return { kind: 'unknown' };
|
|
230
|
-
if (norm.length === 1)
|
|
231
|
-
return { kind: 'named', name: norm[0] };
|
|
232
|
-
return { kind: 'cross' };
|
|
233
|
-
}
|
|
234
|
-
export function projectGroupTitle(group) {
|
|
235
|
-
switch (group.kind) {
|
|
236
|
-
case 'named': return group.name;
|
|
237
|
-
case 'all': return 'All projects';
|
|
238
|
-
case 'cross': return 'Cross-project';
|
|
239
|
-
case 'operations': return 'Operations';
|
|
240
|
-
case 'unknown': return 'Unknown projects';
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
export function projectGroupKey(group) {
|
|
244
|
-
return group.kind === 'named' ? `named:${group.name}` : `special:${group.kind}`;
|
|
245
|
-
}
|
|
246
|
-
export function projectGroupOrder(group) {
|
|
247
|
-
switch (group.kind) {
|
|
248
|
-
case 'named': return 0;
|
|
249
|
-
case 'all': return 1;
|
|
250
|
-
case 'cross': return 2;
|
|
251
|
-
case 'operations': return 3;
|
|
252
|
-
case 'unknown': return 4;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
export function computeProjectGroup(projects, knownProjectNames) {
|
|
256
|
-
return projectGroupTitle(computeProjectGroupKind(projects, knownProjectNames));
|
|
257
|
-
}
|
|
258
|
-
function realFsProbe() {
|
|
259
|
-
return {
|
|
260
|
-
exists: (p) => fs.existsSync(p),
|
|
261
|
-
isDirectory: (p) => { try {
|
|
262
|
-
return fs.statSync(p).isDirectory();
|
|
263
|
-
}
|
|
264
|
-
catch {
|
|
265
|
-
return false;
|
|
266
|
-
} },
|
|
267
|
-
isWritable: (p) => { try {
|
|
268
|
-
fs.accessSync(p, fs.constants.W_OK);
|
|
269
|
-
return true;
|
|
270
|
-
}
|
|
271
|
-
catch {
|
|
272
|
-
return false;
|
|
273
|
-
} },
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
function jobRoutineKind(config) {
|
|
277
|
-
if (config.command)
|
|
278
|
-
return 'command';
|
|
279
|
-
if (config.workflow)
|
|
280
|
-
return 'workflow';
|
|
281
|
-
return 'agent';
|
|
282
|
-
}
|
|
283
|
-
export function resolveJobExecutionContext(config, opts = {}) {
|
|
284
|
-
const targetHome = opts.targetHome ?? os.homedir();
|
|
285
|
-
const mode = opts.mode ?? 'local';
|
|
286
|
-
const probe = opts.probe === null
|
|
287
|
-
? undefined
|
|
288
|
-
: (opts.probe ?? (mode === 'local' ? realFsProbe() : undefined));
|
|
289
|
-
let projectResolution = opts.projectResolution;
|
|
290
|
-
if (config.project !== undefined && projectResolution === undefined) {
|
|
291
|
-
const def = loadProjectDef(config.project);
|
|
292
|
-
projectResolution = def
|
|
293
|
-
? { defined: true, base: projectBasePath(def, true) }
|
|
294
|
-
: { defined: false };
|
|
295
|
-
}
|
|
296
|
-
return resolveRoutineExecutionContext({
|
|
297
|
-
name: config.name,
|
|
298
|
-
project: config.project,
|
|
299
|
-
cwd: config.cwd,
|
|
300
|
-
kind: jobRoutineKind(config),
|
|
301
|
-
mode,
|
|
302
|
-
targetHome,
|
|
303
|
-
projectResolution,
|
|
304
|
-
probe,
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
export function finalizeRunMeta(meta, status, exitCode, opts) {
|
|
308
|
-
meta.status = status;
|
|
309
|
-
meta.exitCode = exitCode;
|
|
310
|
-
meta.completedAt = opts?.completedAt ?? new Date().toISOString();
|
|
311
|
-
const started = Date.parse(meta.startedAt);
|
|
312
|
-
const completed = Date.parse(meta.completedAt);
|
|
313
|
-
meta.duration = Number.isFinite(started) && Number.isFinite(completed) && completed >= started
|
|
314
|
-
? completed - started
|
|
315
|
-
: 0;
|
|
316
|
-
if (opts?.errorMessage) {
|
|
317
|
-
meta.errorMessage = opts.errorMessage;
|
|
318
|
-
}
|
|
319
|
-
else {
|
|
320
|
-
delete meta.errorMessage;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
export function jobRunsOnThisDevice(config) {
|
|
324
|
-
if (config.dispatchedBy === undefined) {
|
|
325
|
-
const activated = routineEnabledOnThisDevice(config.name);
|
|
326
|
-
if (activated !== null)
|
|
327
|
-
return activated;
|
|
328
|
-
}
|
|
329
|
-
const owner = routineOwnerDevice(config);
|
|
330
|
-
if (owner === null)
|
|
331
|
-
return true;
|
|
332
|
-
return owner === machineId();
|
|
333
|
-
}
|
|
334
|
-
export function routineOwnerDevice(config) {
|
|
335
|
-
if (!Array.isArray(config.devices))
|
|
336
|
-
return null;
|
|
337
|
-
const devices = config.devices.map((d) => normalizeHost(String(d))).filter(Boolean);
|
|
338
|
-
if (devices.length === 0)
|
|
339
|
-
return null;
|
|
340
|
-
return [...devices].sort()[0];
|
|
341
|
-
}
|
|
342
|
-
export function hasAmbiguousDevicePin(config) {
|
|
343
|
-
if (!Array.isArray(config.devices))
|
|
344
|
-
return false;
|
|
345
|
-
const devices = new Set(config.devices.map((d) => normalizeHost(String(d))).filter(Boolean));
|
|
346
|
-
return devices.size > 1;
|
|
347
|
-
}
|
|
348
|
-
export function findAmbiguousDevicePins(cwd) {
|
|
349
|
-
return listJobs(cwd)
|
|
350
|
-
.filter((job) => job.enabled && hasAmbiguousDevicePin(job))
|
|
351
|
-
.map((job) => ({
|
|
352
|
-
name: job.name,
|
|
353
|
-
devices: (job.devices ?? []).map((d) => normalizeHost(d)),
|
|
354
|
-
owner: routineOwnerDevice(job) ?? '',
|
|
355
|
-
}));
|
|
356
|
-
}
|
|
357
|
-
export function resolveHostStrategy(config) {
|
|
358
|
-
if (config.hostStrategy)
|
|
359
|
-
return config.hostStrategy;
|
|
360
|
-
if (config.host)
|
|
361
|
-
return 'host';
|
|
362
|
-
return 'local';
|
|
363
|
-
}
|
|
364
|
-
export function parseHostStrategy(raw) {
|
|
365
|
-
if (raw === undefined || raw === null || raw === '')
|
|
366
|
-
return null;
|
|
367
|
-
const v = raw.trim().toLowerCase();
|
|
368
|
-
if (HOST_STRATEGIES.includes(v))
|
|
369
|
-
return v;
|
|
370
|
-
throw new Error(`Invalid placement '${raw}'. Use one of: ${HOST_STRATEGIES.join(', ')}`);
|
|
371
|
-
}
|
|
372
|
-
export function placementRequiresFiringPin(strategy) {
|
|
373
|
-
return strategy === 'host' || strategy === 'fleet' || strategy === 'cloud';
|
|
374
|
-
}
|
|
375
|
-
export function checkJobDeviceEligibility(config) {
|
|
376
|
-
if (jobRunsOnThisDevice(config))
|
|
377
|
-
return null;
|
|
378
|
-
const allowed = (config.devices ?? []).map((d) => normalizeHost(d));
|
|
379
|
-
const allowedLabel = allowed.join(', ');
|
|
380
|
-
const firstHost = routineOwnerDevice(config) ?? allowed[0] ?? 'HOST';
|
|
381
|
-
const message = `Job '${config.name}' can only run on: ${allowedLabel}`;
|
|
382
|
-
const suggestion = `agents routines run ${config.name} --device ${firstHost}`;
|
|
383
|
-
return { message, suggestion, allowedLabel, firstHost };
|
|
384
|
-
}
|
|
385
|
-
const JOB_DEFAULTS = {
|
|
386
|
-
mode: 'auto',
|
|
387
|
-
effort: 'auto',
|
|
388
|
-
timeout: '10m',
|
|
389
|
-
enabled: true,
|
|
390
|
-
};
|
|
391
|
-
function overlayUserRoutineDevices(job, userJob) {
|
|
392
|
-
if (job.devices !== undefined)
|
|
393
|
-
return job;
|
|
394
|
-
if (!userJob)
|
|
395
|
-
return job;
|
|
396
|
-
const merged = { ...job };
|
|
397
|
-
if (userJob.devices && userJob.devices.length > 0) {
|
|
398
|
-
merged.devices = userJob.devices;
|
|
399
|
-
}
|
|
400
|
-
else {
|
|
401
|
-
delete merged.devices;
|
|
402
|
-
}
|
|
403
|
-
return merged;
|
|
404
|
-
}
|
|
405
|
-
export function listJobs(cwd) {
|
|
406
|
-
ensureAgentsDir();
|
|
407
|
-
const seen = new Set();
|
|
408
|
-
const jobs = [];
|
|
409
|
-
const userDir = getRoutinesDir();
|
|
410
|
-
const dirs = [];
|
|
411
|
-
if (cwd) {
|
|
412
|
-
const projectDir = getProjectRoutinesDir(cwd);
|
|
413
|
-
if (projectDir)
|
|
414
|
-
dirs.push({ scope: 'project', path: projectDir });
|
|
415
|
-
}
|
|
416
|
-
dirs.push({ scope: 'user', path: userDir });
|
|
417
|
-
dirs.push({ scope: 'system', path: getSystemRoutinesDir() });
|
|
418
|
-
for (const { scope, path: dir } of dirs) {
|
|
419
|
-
if (!fs.existsSync(dir))
|
|
420
|
-
continue;
|
|
421
|
-
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.yml') || f.endsWith('.yaml'));
|
|
422
|
-
for (const file of files) {
|
|
423
|
-
let job = readJobFile(path.join(dir, file));
|
|
424
|
-
if (!job)
|
|
425
|
-
continue;
|
|
426
|
-
if (scope === 'project') {
|
|
427
|
-
job = overlayUserRoutineDevices(job, readJobFromDir(userDir, job.name));
|
|
428
|
-
}
|
|
429
|
-
if (seen.has(job.name))
|
|
430
|
-
continue;
|
|
431
|
-
seen.add(job.name);
|
|
432
|
-
jobs.push(job);
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
return jobs.map(applyDeviceActivation);
|
|
436
|
-
}
|
|
437
|
-
export function readJob(name, cwd) {
|
|
438
|
-
ensureAgentsDir();
|
|
439
|
-
const userDir = getRoutinesDir();
|
|
440
|
-
const dirs = [];
|
|
441
|
-
if (cwd) {
|
|
442
|
-
const projectDir = getProjectRoutinesDir(cwd);
|
|
443
|
-
if (projectDir)
|
|
444
|
-
dirs.push({ scope: 'project', path: projectDir });
|
|
445
|
-
}
|
|
446
|
-
dirs.push({ scope: 'user', path: userDir });
|
|
447
|
-
dirs.push({ scope: 'system', path: getSystemRoutinesDir() });
|
|
448
|
-
for (const { scope, path: dir } of dirs) {
|
|
449
|
-
const job = readJobFromDir(dir, name);
|
|
450
|
-
if (job) {
|
|
451
|
-
if (scope === 'project')
|
|
452
|
-
return applyDeviceActivation(overlayUserRoutineDevices(job, readJobFromDir(userDir, name)));
|
|
453
|
-
return applyDeviceActivation(job);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
return null;
|
|
457
|
-
}
|
|
458
|
-
function applyDeviceActivation(job) {
|
|
459
|
-
const activated = routineEnabledOnThisDevice(job.name);
|
|
460
|
-
return activated === null ? job : { ...job, enabled: activated };
|
|
461
|
-
}
|
|
462
|
-
function readJobFromDir(dir, name) {
|
|
463
|
-
for (const ext of ['.yml', '.yaml']) {
|
|
464
|
-
const filePath = safeJoin(dir, name + ext);
|
|
465
|
-
if (fs.existsSync(filePath)) {
|
|
466
|
-
return readJobFile(filePath);
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
return null;
|
|
470
|
-
}
|
|
471
|
-
export function readJobFileResult(filePath) {
|
|
472
|
-
let content;
|
|
473
|
-
try {
|
|
474
|
-
content = fs.readFileSync(filePath, 'utf-8');
|
|
475
|
-
}
|
|
476
|
-
catch (err) {
|
|
477
|
-
return { config: null, problem: `unreadable: ${err.message}` };
|
|
478
|
-
}
|
|
479
|
-
let parsed;
|
|
480
|
-
try {
|
|
481
|
-
parsed = yaml.parse(content);
|
|
482
|
-
}
|
|
483
|
-
catch (err) {
|
|
484
|
-
return { config: null, problem: `invalid YAML: ${err.message.split('\n')[0]}` };
|
|
485
|
-
}
|
|
486
|
-
if (!parsed || typeof parsed !== 'object') {
|
|
487
|
-
return { config: null, problem: 'not a YAML map' };
|
|
488
|
-
}
|
|
489
|
-
if (Object.prototype.hasOwnProperty.call(parsed, 'device')) {
|
|
490
|
-
return { config: null, problem: 'legacy `device:` key — inert until migrated to `devices:`' };
|
|
491
|
-
}
|
|
492
|
-
if (Object.prototype.hasOwnProperty.call(parsed, 'devices')
|
|
493
|
-
&& parsed.devices !== undefined
|
|
494
|
-
&& parsed.devices !== null
|
|
495
|
-
&& !Array.isArray(parsed.devices)) {
|
|
496
|
-
return { config: null, problem: '`devices:` must be a list — routine is inert' };
|
|
497
|
-
}
|
|
498
|
-
if (Object.prototype.hasOwnProperty.call(parsed, 'dispatchedBy')) {
|
|
499
|
-
return { config: null, problem: '`dispatchedBy:` is a runtime-only webhook marker, not a routine field — routine is inert' };
|
|
500
|
-
}
|
|
501
|
-
return {
|
|
502
|
-
config: {
|
|
503
|
-
...JOB_DEFAULTS,
|
|
504
|
-
...parsed,
|
|
505
|
-
name: parsed.name || path.basename(filePath).replace(/\.ya?ml$/, ''),
|
|
506
|
-
enabled: Object.prototype.hasOwnProperty.call(parsed, 'enabled') ? parsed.enabled !== false : false,
|
|
507
|
-
},
|
|
508
|
-
problem: null,
|
|
509
|
-
};
|
|
510
|
-
}
|
|
511
|
-
function readJobFile(filePath) {
|
|
512
|
-
return readJobFileResult(filePath).config;
|
|
513
|
-
}
|
|
514
|
-
export function writeJob(config) {
|
|
515
|
-
ensureAgentsDir();
|
|
516
|
-
if (!config.actor)
|
|
517
|
-
config.actor = resolveActor().id;
|
|
518
|
-
if (!config.createdAt)
|
|
519
|
-
config.createdAt = new Date().toISOString();
|
|
520
|
-
const jobsDir = getRoutinesDir();
|
|
521
|
-
const ymlPath = safeJoin(jobsDir, config.name + '.yml');
|
|
522
|
-
const yamlPath = safeJoin(jobsDir, config.name + '.yaml');
|
|
523
|
-
const ymlExists = fs.existsSync(ymlPath);
|
|
524
|
-
const yamlExists = fs.existsSync(yamlPath);
|
|
525
|
-
if (ymlExists && yamlExists) {
|
|
526
|
-
throw new Error(`Routine '${config.name}' has both .yml and .yaml files; resolve the ambiguity before editing.`);
|
|
527
|
-
}
|
|
528
|
-
const filePath = ymlExists ? ymlPath : yamlExists ? yamlPath : ymlPath;
|
|
529
|
-
const output = { ...config };
|
|
530
|
-
if (output.mode === 'auto')
|
|
531
|
-
delete output.mode;
|
|
532
|
-
if (output.effort === 'auto')
|
|
533
|
-
delete output.effort;
|
|
534
|
-
if (output.timeout === '10m')
|
|
535
|
-
delete output.timeout;
|
|
536
|
-
delete output.enabled;
|
|
537
|
-
if (output.runOnce === false || output.runOnce === undefined)
|
|
538
|
-
delete output.runOnce;
|
|
539
|
-
if (output.catchup === true || output.catchup === undefined)
|
|
540
|
-
delete output.catchup;
|
|
541
|
-
delete output.devices;
|
|
542
|
-
delete output.dispatchedBy;
|
|
543
|
-
const normProjects = normalizeProjects(output.projects);
|
|
544
|
-
if (normProjects)
|
|
545
|
-
output.projects = normProjects;
|
|
546
|
-
else
|
|
547
|
-
delete output.projects;
|
|
548
|
-
let existingText = null;
|
|
549
|
-
if (ymlExists || yamlExists) {
|
|
550
|
-
try {
|
|
551
|
-
existingText = fs.readFileSync(filePath, 'utf-8');
|
|
552
|
-
}
|
|
553
|
-
catch {
|
|
554
|
-
existingText = null;
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
atomicWriteFileSync(filePath, serializeJob(output, existingText));
|
|
558
|
-
}
|
|
559
|
-
export function serializeJob(output, existingText) {
|
|
560
|
-
if (existingText == null)
|
|
561
|
-
return yaml.stringify(output);
|
|
562
|
-
const doc = yaml.parseDocument(existingText);
|
|
563
|
-
if (doc.errors.length > 0 || !yaml.isMap(doc.contents))
|
|
564
|
-
return yaml.stringify(output);
|
|
565
|
-
const existing = (doc.toJS() ?? {});
|
|
566
|
-
for (const [key, value] of Object.entries(output)) {
|
|
567
|
-
if (JSON.stringify(existing[key]) !== JSON.stringify(value))
|
|
568
|
-
doc.set(key, value);
|
|
569
|
-
}
|
|
570
|
-
for (const key of Object.keys(existing)) {
|
|
571
|
-
if (!(key in output))
|
|
572
|
-
doc.delete(key);
|
|
573
|
-
}
|
|
574
|
-
return doc.toString({ flowCollectionPadding: false });
|
|
575
|
-
}
|
|
576
|
-
export function deleteJob(name) {
|
|
577
|
-
const jobsDir = getRoutinesDir();
|
|
578
|
-
for (const ext of ['.yml', '.yaml']) {
|
|
579
|
-
const filePath = safeJoin(jobsDir, name + ext);
|
|
580
|
-
if (fs.existsSync(filePath)) {
|
|
581
|
-
fs.unlinkSync(filePath);
|
|
582
|
-
return true;
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
return false;
|
|
586
|
-
}
|
|
587
|
-
export function setJobEnabled(name, enabled) {
|
|
588
|
-
const job = readJob(name);
|
|
589
|
-
if (!job)
|
|
590
|
-
throw new Error(`Job '${name}' not found`);
|
|
591
|
-
const legacyEnabled = enabledRoutineNames() === null
|
|
592
|
-
? listJobs().filter((candidate) => candidate.enabled && jobRunsOnThisDevice(candidate)).map((candidate) => candidate.name)
|
|
593
|
-
: [];
|
|
594
|
-
setRoutineEnabledOnThisDevice(name, enabled, legacyEnabled);
|
|
595
|
-
}
|
|
596
|
-
export function migrateLegacyRoutineActivation() {
|
|
597
|
-
if (enabledRoutineNames() !== null)
|
|
598
|
-
return false;
|
|
599
|
-
const jobs = listJobs();
|
|
600
|
-
if (!jobs.some((job) => job.enabled || Array.isArray(job.devices)))
|
|
601
|
-
return false;
|
|
602
|
-
replaceEnabledRoutines(jobs.filter((job) => job.enabled && jobRunsOnThisDevice(job)).map((job) => job.name));
|
|
603
|
-
return true;
|
|
604
|
-
}
|
|
605
|
-
export function validateJob(config) {
|
|
606
|
-
const errors = [];
|
|
607
|
-
if (!config.name || typeof config.name !== 'string') {
|
|
608
|
-
errors.push('name is required');
|
|
609
|
-
}
|
|
610
|
-
else if (!isSafeSegmentName(config.name)) {
|
|
611
|
-
errors.push(`invalid name ${JSON.stringify(config.name)}: must be a single path segment ` +
|
|
612
|
-
`(no '/', '\\\\', or null bytes, and not '.' or '..')`);
|
|
613
|
-
}
|
|
614
|
-
const hasSchedule = Boolean(config.schedule && typeof config.schedule === 'string');
|
|
615
|
-
const hasTrigger = config.trigger !== undefined;
|
|
616
|
-
if (!hasSchedule && !hasTrigger) {
|
|
617
|
-
errors.push('schedule (cron expression) or trigger is required');
|
|
618
|
-
}
|
|
619
|
-
if (config.schedule !== undefined) {
|
|
620
|
-
if (typeof config.schedule !== 'string') {
|
|
621
|
-
errors.push('schedule must be a cron expression string');
|
|
622
|
-
}
|
|
623
|
-
else {
|
|
624
|
-
try {
|
|
625
|
-
new Cron(config.schedule);
|
|
626
|
-
}
|
|
627
|
-
catch {
|
|
628
|
-
errors.push(`invalid cron expression: "${config.schedule}"`);
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
if (config.trigger !== undefined) {
|
|
633
|
-
errors.push(...validateTrigger(config.trigger));
|
|
634
|
-
}
|
|
635
|
-
const hasAgent = Boolean(config.agent && typeof config.agent === 'string');
|
|
636
|
-
const hasWorkflow = Boolean(config.workflow && typeof config.workflow === 'string');
|
|
637
|
-
const hasCommand = Boolean(config.command && typeof config.command === 'string');
|
|
638
|
-
const strategy = resolveHostStrategy(config);
|
|
639
|
-
const set = [hasAgent, hasWorkflow, hasCommand].filter(Boolean).length;
|
|
640
|
-
if (set === 0) {
|
|
641
|
-
errors.push('exactly one of agent, workflow, or command is required');
|
|
642
|
-
}
|
|
643
|
-
else if (set > 1) {
|
|
644
|
-
errors.push('exactly one of agent, workflow, or command may be set (not more)');
|
|
645
|
-
}
|
|
646
|
-
if (config.command !== undefined && (typeof config.command !== 'string' || config.command.trim() === '')) {
|
|
647
|
-
errors.push('command must be a non-empty shell command string');
|
|
648
|
-
}
|
|
649
|
-
if (hasAgent && config.agent && !ALL_AGENT_IDS.includes(config.agent) && !isCustomHarnessName(config.agent)) {
|
|
650
|
-
errors.push(`agent must be one of: ${ALL_AGENT_IDS.join(', ')}, or a custom harness (agents harness list)`);
|
|
651
|
-
}
|
|
652
|
-
else if (hasAgent && config.agent && strategy === 'local' &&
|
|
653
|
-
!ROUTINE_AGENT_IDS.includes(config.agent) &&
|
|
654
|
-
!isCustomHarnessName(config.agent)) {
|
|
655
|
-
errors.push(`agent '${config.agent}' is not supported by the local routine daemon; use one of: ` +
|
|
656
|
-
`${ROUTINE_AGENT_IDS.join(', ')} (or set hostStrategy: host/fleet/cloud to run it elsewhere)`);
|
|
657
|
-
}
|
|
658
|
-
if (hasWorkflow && config.workflow) {
|
|
659
|
-
if (!/^[a-z0-9][a-z0-9_-]*$/.test(config.workflow)) {
|
|
660
|
-
errors.push('workflow must be a lowercase alphanumeric name (hyphens and underscores allowed, e.g. autodev)');
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
if (config.resume !== undefined) {
|
|
664
|
-
const RESUMABLE_AGENTS = ['claude', 'codex'];
|
|
665
|
-
if (typeof config.resume !== 'string' || config.resume.trim() === '') {
|
|
666
|
-
errors.push('resume must be a non-empty session id string');
|
|
667
|
-
}
|
|
668
|
-
if (hasWorkflow) {
|
|
669
|
-
errors.push('resume cannot be combined with workflow (resume reopens an existing agent session)');
|
|
670
|
-
}
|
|
671
|
-
if (config.loop) {
|
|
672
|
-
errors.push('resume cannot be combined with loop');
|
|
673
|
-
}
|
|
674
|
-
if (hasAgent && config.agent && !RESUMABLE_AGENTS.includes(config.agent)) {
|
|
675
|
-
errors.push(`resume is only supported for agents with native --resume (${RESUMABLE_AGENTS.join(', ')}); got '${config.agent}'`);
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
if (config.strategy !== undefined) {
|
|
679
|
-
if (!RUN_STRATEGIES.includes(config.strategy)) {
|
|
680
|
-
errors.push(`strategy must be one of: ${RUN_STRATEGIES.join(', ')}`);
|
|
681
|
-
}
|
|
682
|
-
if (!hasAgent) {
|
|
683
|
-
errors.push('strategy only applies to agent routines (drop it for workflow/command routines)');
|
|
684
|
-
}
|
|
685
|
-
if (config.version) {
|
|
686
|
-
errors.push(`strategy ${config.strategy} conflicts with version ${config.version} — an exact pin leaves nothing to select; drop strategy or the version pin`);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
if (config.mode && !['plan', 'edit', 'auto', 'skip', 'full'].includes(config.mode)) {
|
|
690
|
-
errors.push("mode must be plan, edit, auto, or skip ('full' accepted as alias for skip)");
|
|
691
|
-
}
|
|
692
|
-
if (config.effort && !['low', 'medium', 'high', 'xhigh', 'max', 'auto'].includes(config.effort)) {
|
|
693
|
-
errors.push('effort must be low, medium, high, xhigh, max, or auto');
|
|
694
|
-
}
|
|
695
|
-
if (!hasCommand && (!config.prompt || typeof config.prompt !== 'string')) {
|
|
696
|
-
errors.push('prompt is required');
|
|
697
|
-
}
|
|
698
|
-
if (config.timeout && !parseTimeout(config.timeout)) {
|
|
699
|
-
errors.push('timeout must be like 10m, 2h, 3d, 1w (max 1w)');
|
|
700
|
-
}
|
|
701
|
-
if (config.endAt !== undefined) {
|
|
702
|
-
if (typeof config.endAt !== 'string' || !isParseableDate(config.endAt)) {
|
|
703
|
-
errors.push('endAt must be a parseable ISO 8601 / RFC3339 timestamp (e.g., 2026-12-31T23:59:00Z)');
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
if (config.device !== undefined) {
|
|
707
|
-
errors.push('singular "device" key is no longer supported — replace with devices: [<name>] (an array)');
|
|
708
|
-
}
|
|
709
|
-
if (config.hostStrategy !== undefined) {
|
|
710
|
-
if (!HOST_STRATEGIES.includes(config.hostStrategy)) {
|
|
711
|
-
errors.push(`hostStrategy must be one of: ${HOST_STRATEGIES.join(', ')}`);
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
if (config.host !== undefined) {
|
|
715
|
-
if (typeof config.host !== 'string' || config.host.trim() === '') {
|
|
716
|
-
errors.push('host must be a non-empty machine name (a registered host, device, capability tag, or user@host)');
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
if (strategy === 'host' && (!config.host || config.host.trim() === '')) {
|
|
720
|
-
errors.push("hostStrategy: host requires host: (set via --run-on or host: in YAML)");
|
|
721
|
-
}
|
|
722
|
-
if (config.host === 'auto' && strategy !== 'fleet') {
|
|
723
|
-
errors.push("host: auto requires hostStrategy: fleet (set via --run-on auto) — 'auto' is a fire-time device pick, not a machine name");
|
|
724
|
-
}
|
|
725
|
-
if (strategy === 'host' || strategy === 'fleet' || strategy === 'cloud') {
|
|
726
|
-
if (config.workflow) {
|
|
727
|
-
errors.push(`${strategy} placement can't be combined with workflow: yet — run the workflow locally or convert it to a plain prompt`);
|
|
728
|
-
}
|
|
729
|
-
if (config.loop) {
|
|
730
|
-
errors.push(`${strategy} placement can't be combined with loop: yet (the loop driver and its signal files live on the firing machine)`);
|
|
731
|
-
}
|
|
732
|
-
if (config.command) {
|
|
733
|
-
errors.push(`${strategy} placement can't be combined with command: yet (a plain shell command has no agent to place remotely)`);
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
if (config.remoteCwd !== undefined && strategy !== 'host' && strategy !== 'fleet') {
|
|
737
|
-
errors.push('remoteCwd only applies to host/fleet-placed routines — set hostStrategy: host|fleet, or drop it');
|
|
738
|
-
}
|
|
739
|
-
if (config.project === null) {
|
|
740
|
-
errors.push('project is null — quote YAML values that look like null literals');
|
|
741
|
-
}
|
|
742
|
-
else if (config.project !== undefined && (typeof config.project !== 'string' || config.project.trim() === '')) {
|
|
743
|
-
errors.push('project (the singular execution anchor) must be a non-empty project name');
|
|
744
|
-
}
|
|
745
|
-
if (config.cwd === null) {
|
|
746
|
-
errors.push('cwd is null — a bare ~ is YAML null; quote it as "~" for the home directory');
|
|
747
|
-
}
|
|
748
|
-
else if (config.cwd !== undefined && (typeof config.cwd !== 'string' || config.cwd.trim() === '')) {
|
|
749
|
-
errors.push('cwd (the portable execution directory) must be a non-empty path string');
|
|
750
|
-
}
|
|
751
|
-
if (config.cwd !== undefined && config.remoteCwd !== undefined) {
|
|
752
|
-
errors.push('cwd and remoteCwd both set — remoteCwd is the legacy form of cwd; keep only cwd');
|
|
753
|
-
}
|
|
754
|
-
if (config.source !== undefined) {
|
|
755
|
-
if (!config.source || typeof config.source !== 'object') {
|
|
756
|
-
errors.push('source must be an object');
|
|
757
|
-
}
|
|
758
|
-
else {
|
|
759
|
-
if (config.source.kind !== 'project') {
|
|
760
|
-
errors.push("source.kind must be 'project'");
|
|
761
|
-
}
|
|
762
|
-
if (typeof config.source.projectPath !== 'string' || config.source.projectPath.trim() === '') {
|
|
763
|
-
errors.push('source.projectPath must be a non-empty absolute path');
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
if (config.devices !== undefined) {
|
|
768
|
-
if (!Array.isArray(config.devices)) {
|
|
769
|
-
errors.push('devices must be an array of device names (as shown by `agents devices`)');
|
|
770
|
-
}
|
|
771
|
-
else {
|
|
772
|
-
for (const d of config.devices) {
|
|
773
|
-
if (typeof d !== 'string' || d.trim() === '') {
|
|
774
|
-
errors.push('each entry in devices must be a non-empty device name');
|
|
775
|
-
break;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
if (hasAmbiguousDevicePin(config)) {
|
|
781
|
-
errors.push(`devices lists ${new Set(config.devices.map((d) => normalizeHost(String(d)))).size} devices; a routine runs on exactly one. ` +
|
|
782
|
-
'Pin the single device that should own it, e.g. devices: [yosemite-s0]. ' +
|
|
783
|
-
'Omit devices entirely for a routine that genuinely belongs on every machine.');
|
|
784
|
-
}
|
|
785
|
-
if (config.catchup !== undefined && typeof config.catchup !== 'boolean') {
|
|
786
|
-
errors.push('catchup must be a boolean (false to skip running a missed fire late)');
|
|
787
|
-
}
|
|
788
|
-
if (config.projects !== undefined) {
|
|
789
|
-
if (!Array.isArray(config.projects)) {
|
|
790
|
-
errors.push('projects must be an array of project names (or ["*"] for all projects)');
|
|
791
|
-
}
|
|
792
|
-
else if (config.projects.length === 1 && config.projects[0] === '*') {
|
|
793
|
-
}
|
|
794
|
-
else if (config.projects.includes('*')) {
|
|
795
|
-
errors.push('projects: "*" (all projects) must be the sole entry');
|
|
796
|
-
}
|
|
797
|
-
else {
|
|
798
|
-
for (const p of config.projects) {
|
|
799
|
-
if (typeof p !== 'string' || p.trim() === '') {
|
|
800
|
-
errors.push('each entry in projects must be a non-empty project name');
|
|
801
|
-
break;
|
|
802
|
-
}
|
|
803
|
-
if (!isSafeProjectName(p)) {
|
|
804
|
-
errors.push(`invalid project name "${p}": must start with a letter or digit, contain only letters, digits, dots, hyphens, or underscores`);
|
|
805
|
-
break;
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
return errors;
|
|
811
|
-
}
|
|
812
|
-
export function validateTrigger(trigger) {
|
|
813
|
-
const errors = [];
|
|
814
|
-
if (!trigger || typeof trigger !== 'object') {
|
|
815
|
-
return ['trigger must be an object'];
|
|
816
|
-
}
|
|
817
|
-
const t = trigger;
|
|
818
|
-
if (t.type !== 'github_event' && t.type !== 'linear_event') {
|
|
819
|
-
errors.push("trigger.type must be 'github_event' or 'linear_event'");
|
|
820
|
-
return errors;
|
|
821
|
-
}
|
|
822
|
-
if (t.type === 'github_event') {
|
|
823
|
-
const github = t;
|
|
824
|
-
if (!github.event || !GITHUB_TRIGGER_EVENTS.includes(github.event)) {
|
|
825
|
-
errors.push(`trigger.event must be one of: ${GITHUB_TRIGGER_EVENTS.join(', ')}`);
|
|
826
|
-
}
|
|
827
|
-
if (github.repo !== undefined && (typeof github.repo !== 'string' || !/^[^/\s]+\/[^/\s]+$/.test(github.repo))) {
|
|
828
|
-
errors.push('trigger.repo must be in owner/name form');
|
|
829
|
-
}
|
|
830
|
-
if (github.branch !== undefined && typeof github.branch !== 'string') {
|
|
831
|
-
errors.push('trigger.branch must be a string');
|
|
832
|
-
}
|
|
833
|
-
if (github.action !== undefined && typeof github.action !== 'string') {
|
|
834
|
-
errors.push('trigger.action must be a string');
|
|
835
|
-
}
|
|
836
|
-
if (github.label !== undefined && typeof github.label !== 'string') {
|
|
837
|
-
errors.push('trigger.label must be a string');
|
|
838
|
-
}
|
|
839
|
-
return errors;
|
|
840
|
-
}
|
|
841
|
-
const linear = t;
|
|
842
|
-
if (!linear.event || !LINEAR_TRIGGER_EVENTS.includes(linear.event)) {
|
|
843
|
-
errors.push(`trigger.event must be one of: ${LINEAR_TRIGGER_EVENTS.join(', ')}`);
|
|
844
|
-
}
|
|
845
|
-
if (linear.action !== undefined && typeof linear.action !== 'string') {
|
|
846
|
-
errors.push('trigger.action must be a string');
|
|
847
|
-
}
|
|
848
|
-
if (linear.teamKey !== undefined && (typeof linear.teamKey !== 'string' || !/^[A-Z][A-Z0-9]*$/.test(linear.teamKey))) {
|
|
849
|
-
errors.push('trigger.teamKey must be an uppercase Linear team key');
|
|
850
|
-
}
|
|
851
|
-
if (linear.label !== undefined && typeof linear.label !== 'string') {
|
|
852
|
-
errors.push('trigger.label must be a string');
|
|
853
|
-
}
|
|
854
|
-
if (linear.stateTo !== undefined && typeof linear.stateTo !== 'string') {
|
|
855
|
-
errors.push('trigger.stateTo must be a string');
|
|
856
|
-
}
|
|
857
|
-
if (linear.stateFrom !== undefined && typeof linear.stateFrom !== 'string') {
|
|
858
|
-
errors.push('trigger.stateFrom must be a string');
|
|
859
|
-
}
|
|
860
|
-
return errors;
|
|
861
|
-
}
|
|
862
|
-
function isParseableDate(value) {
|
|
863
|
-
if (!value.trim())
|
|
864
|
-
return false;
|
|
865
|
-
const ts = Date.parse(value);
|
|
866
|
-
return Number.isFinite(ts);
|
|
867
|
-
}
|
|
868
|
-
export function isPastEndAt(config, now = new Date()) {
|
|
869
|
-
if (!config.endAt)
|
|
870
|
-
return false;
|
|
871
|
-
const end = Date.parse(config.endAt);
|
|
872
|
-
if (!Number.isFinite(end))
|
|
873
|
-
return false;
|
|
874
|
-
return now.getTime() >= end;
|
|
875
|
-
}
|
|
876
|
-
export function parseOneShotLikeSchedule(schedule) {
|
|
877
|
-
if (!schedule)
|
|
878
|
-
return null;
|
|
879
|
-
const parts = schedule.trim().split(/\s+/);
|
|
880
|
-
if (parts.length !== 5)
|
|
881
|
-
return null;
|
|
882
|
-
const [minuteRaw, hourRaw, dayRaw, monthRaw, weekdayRaw] = parts;
|
|
883
|
-
if (weekdayRaw !== '*')
|
|
884
|
-
return null;
|
|
885
|
-
if (![minuteRaw, hourRaw, dayRaw, monthRaw].every((p) => /^\d+$/.test(p)))
|
|
886
|
-
return null;
|
|
887
|
-
const minute = parseInt(minuteRaw, 10);
|
|
888
|
-
const hour = parseInt(hourRaw, 10);
|
|
889
|
-
const day = parseInt(dayRaw, 10);
|
|
890
|
-
const month = parseInt(monthRaw, 10);
|
|
891
|
-
if (minute < 0 || minute > 59)
|
|
892
|
-
return null;
|
|
893
|
-
if (hour < 0 || hour > 23)
|
|
894
|
-
return null;
|
|
895
|
-
if (month < 1 || month > 12)
|
|
896
|
-
return null;
|
|
897
|
-
if (day < 1 || day > 31)
|
|
898
|
-
return null;
|
|
899
|
-
return { minute, hour, day, month };
|
|
900
|
-
}
|
|
901
|
-
export function isOneShotLikeSchedule(schedule) {
|
|
902
|
-
return parseOneShotLikeSchedule(schedule) !== null;
|
|
903
|
-
}
|
|
904
|
-
export function isOneShotRoutine(config) {
|
|
905
|
-
return Boolean(config.runOnce || isOneShotLikeSchedule(config.schedule));
|
|
906
|
-
}
|
|
907
|
-
function zonedParts(date, timezone) {
|
|
908
|
-
const parts = new Intl.DateTimeFormat('en-US', {
|
|
909
|
-
timeZone: timezone,
|
|
910
|
-
year: 'numeric',
|
|
911
|
-
month: 'numeric',
|
|
912
|
-
day: 'numeric',
|
|
913
|
-
hour: 'numeric',
|
|
914
|
-
minute: 'numeric',
|
|
915
|
-
hour12: false,
|
|
916
|
-
hourCycle: 'h23',
|
|
917
|
-
}).formatToParts(date);
|
|
918
|
-
const get = (type) => parseInt(parts.find((p) => p.type === type)?.value ?? '0', 10);
|
|
919
|
-
return {
|
|
920
|
-
year: get('year'),
|
|
921
|
-
month: get('month'),
|
|
922
|
-
day: get('day'),
|
|
923
|
-
hour: get('hour'),
|
|
924
|
-
minute: get('minute'),
|
|
925
|
-
};
|
|
926
|
-
}
|
|
927
|
-
function zonedDateToUtc(year, parts, timezone) {
|
|
928
|
-
const targetUtc = Date.UTC(year, parts.month - 1, parts.day, parts.hour, parts.minute, 0, 0);
|
|
929
|
-
let candidate = new Date(targetUtc);
|
|
930
|
-
for (let i = 0; i < 4; i++) {
|
|
931
|
-
const actual = zonedParts(candidate, timezone);
|
|
932
|
-
const actualUtc = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute, 0, 0);
|
|
933
|
-
const delta = actualUtc - targetUtc;
|
|
934
|
-
if (delta === 0)
|
|
935
|
-
break;
|
|
936
|
-
candidate = new Date(candidate.getTime() - delta);
|
|
937
|
-
}
|
|
938
|
-
const verify = zonedParts(candidate, timezone);
|
|
939
|
-
if (verify.year !== year ||
|
|
940
|
-
verify.month !== parts.month ||
|
|
941
|
-
verify.day !== parts.day ||
|
|
942
|
-
verify.hour !== parts.hour ||
|
|
943
|
-
verify.minute !== parts.minute) {
|
|
944
|
-
return null;
|
|
945
|
-
}
|
|
946
|
-
return candidate;
|
|
947
|
-
}
|
|
948
|
-
export function oneShotScheduleFireDate(schedule, now = new Date(), timezone) {
|
|
949
|
-
const parts = parseOneShotLikeSchedule(schedule);
|
|
950
|
-
if (!parts)
|
|
951
|
-
return null;
|
|
952
|
-
if (timezone) {
|
|
953
|
-
try {
|
|
954
|
-
const year = zonedParts(now, timezone).year;
|
|
955
|
-
return zonedDateToUtc(year, parts, timezone);
|
|
956
|
-
}
|
|
957
|
-
catch {
|
|
958
|
-
return null;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
const fireAt = new Date(now.getFullYear(), parts.month - 1, parts.day, parts.hour, parts.minute, 0, 0);
|
|
962
|
-
if (fireAt.getFullYear() !== now.getFullYear() ||
|
|
963
|
-
fireAt.getMonth() !== parts.month - 1 ||
|
|
964
|
-
fireAt.getDate() !== parts.day ||
|
|
965
|
-
fireAt.getHours() !== parts.hour ||
|
|
966
|
-
fireAt.getMinutes() !== parts.minute) {
|
|
967
|
-
return null;
|
|
968
|
-
}
|
|
969
|
-
return fireAt;
|
|
970
|
-
}
|
|
971
|
-
export function isPastOneShotRoutine(config, now = new Date()) {
|
|
972
|
-
if (!isOneShotRoutine(config))
|
|
973
|
-
return false;
|
|
974
|
-
const fireAt = oneShotScheduleFireDate(config.schedule, now, config.timezone);
|
|
975
|
-
return Boolean(fireAt && now.getTime() >= fireAt.getTime());
|
|
976
|
-
}
|
|
977
|
-
export function hasCompletedOneShotRun(config, now = new Date()) {
|
|
978
|
-
if (!isPastOneShotRoutine(config, now))
|
|
979
|
-
return false;
|
|
980
|
-
const fireAt = oneShotScheduleFireDate(config.schedule, now, config.timezone);
|
|
981
|
-
if (!fireAt)
|
|
982
|
-
return false;
|
|
983
|
-
const latest = getLatestRun(config.name);
|
|
984
|
-
if (!latest || latest.status === 'running')
|
|
985
|
-
return false;
|
|
986
|
-
const startedAt = Date.parse(latest.startedAt);
|
|
987
|
-
return Number.isFinite(startedAt) && startedAt >= fireAt.getTime() - 60_000;
|
|
988
|
-
}
|
|
989
|
-
export function shouldPurgeCompletedOneShotRoutine(config, now = new Date()) {
|
|
990
|
-
return hasCompletedOneShotRun(config, now);
|
|
991
|
-
}
|
|
992
|
-
export function resolveJobPrompt(config) {
|
|
993
|
-
const now = new Date();
|
|
994
|
-
const tz = config.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
995
|
-
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
996
|
-
const localDayName = new Intl.DateTimeFormat('en-US', { timeZone: tz, weekday: 'long' }).format(now);
|
|
997
|
-
const localDay = days.includes(localDayName) ? localDayName : days[now.getDay()];
|
|
998
|
-
const localDate = now.toLocaleDateString('en-CA', { timeZone: tz });
|
|
999
|
-
const localTime = now.toLocaleTimeString('en-GB', { timeZone: tz, hour12: false });
|
|
1000
|
-
let prompt = config.prompt;
|
|
1001
|
-
prompt = prompt.replace(/\{day\}/g, localDay);
|
|
1002
|
-
prompt = prompt.replace(/\{date\}/g, localDate);
|
|
1003
|
-
prompt = prompt.replace(/\{time\}/g, localTime);
|
|
1004
|
-
prompt = prompt.replace(/\{job_name\}/g, config.name);
|
|
1005
|
-
if (config.variables) {
|
|
1006
|
-
for (const [key, value] of Object.entries(config.variables)) {
|
|
1007
|
-
prompt = prompt.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
const latestRun = getLatestCompletedRun(config.name);
|
|
1011
|
-
if (latestRun) {
|
|
1012
|
-
const reportPath = path.join(getJobRunsDir(config.name), latestRun.runId, 'report.md');
|
|
1013
|
-
if (fs.existsSync(reportPath)) {
|
|
1014
|
-
const report = fs.readFileSync(reportPath, 'utf-8');
|
|
1015
|
-
prompt = prompt.replace(/\{last_report\}/g, report);
|
|
1016
|
-
}
|
|
1017
|
-
else {
|
|
1018
|
-
prompt = prompt.replace(/\{last_report\}/g, '(no previous report)');
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
else {
|
|
1022
|
-
prompt = prompt.replace(/\{last_report\}/g, '(no previous report)');
|
|
1023
|
-
}
|
|
1024
|
-
return prompt;
|
|
1025
|
-
}
|
|
1026
|
-
export function parseTimeout(timeout) {
|
|
1027
|
-
const match = timeout.match(/^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$/);
|
|
1028
|
-
if (!match)
|
|
1029
|
-
return null;
|
|
1030
|
-
const weeks = parseInt(match[1] || '0', 10);
|
|
1031
|
-
const days = parseInt(match[2] || '0', 10);
|
|
1032
|
-
const hours = parseInt(match[3] || '0', 10);
|
|
1033
|
-
const minutes = parseInt(match[4] || '0', 10);
|
|
1034
|
-
const ms = ((weeks * 7 + days) * 24 * 60 + hours * 60 + minutes) * 60 * 1000;
|
|
1035
|
-
if (ms <= 0)
|
|
1036
|
-
return null;
|
|
1037
|
-
const ONE_WEEK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1038
|
-
if (ms > ONE_WEEK_MS)
|
|
1039
|
-
return null;
|
|
1040
|
-
return ms;
|
|
1041
|
-
}
|
|
1042
|
-
export function listRuns(jobName) {
|
|
1043
|
-
const jobRunsDir = getJobRunsDir(jobName);
|
|
1044
|
-
if (!fs.existsSync(jobRunsDir))
|
|
1045
|
-
return [];
|
|
1046
|
-
const entries = fs.readdirSync(jobRunsDir, { withFileTypes: true })
|
|
1047
|
-
.filter((e) => e.isDirectory())
|
|
1048
|
-
.map((e) => e.name)
|
|
1049
|
-
.sort();
|
|
1050
|
-
const runs = [];
|
|
1051
|
-
for (const runId of entries) {
|
|
1052
|
-
const meta = readRunMeta(jobName, runId);
|
|
1053
|
-
if (meta)
|
|
1054
|
-
runs.push(meta);
|
|
1055
|
-
}
|
|
1056
|
-
return runs;
|
|
1057
|
-
}
|
|
1058
|
-
export function getLatestRun(jobName) {
|
|
1059
|
-
const runs = listRuns(jobName);
|
|
1060
|
-
return runs.length > 0 ? runs[runs.length - 1] : null;
|
|
1061
|
-
}
|
|
1062
|
-
export function getLatestCompletedRun(jobName) {
|
|
1063
|
-
const runs = listRuns(jobName);
|
|
1064
|
-
for (let i = runs.length - 1; i >= 0; i--) {
|
|
1065
|
-
if (runs[i].status === 'completed')
|
|
1066
|
-
return runs[i];
|
|
1067
|
-
}
|
|
1068
|
-
return null;
|
|
1069
|
-
}
|
|
1070
|
-
export function routineStats(jobName) {
|
|
1071
|
-
const runs = listRuns(jobName);
|
|
1072
|
-
const failed = runs.filter((r) => r.status === 'failed' || r.status === 'timeout').length;
|
|
1073
|
-
const missed = runs.filter((r) => r.status === 'missed').length;
|
|
1074
|
-
const durations = runs
|
|
1075
|
-
.map((r) => r.duration)
|
|
1076
|
-
.filter((d) => typeof d === 'number' && Number.isFinite(d))
|
|
1077
|
-
.sort((a, b) => a - b);
|
|
1078
|
-
const avgMs = durations.length > 0
|
|
1079
|
-
? Math.round(durations.reduce((sum, d) => sum + d, 0) / durations.length)
|
|
1080
|
-
: 0;
|
|
1081
|
-
return {
|
|
1082
|
-
count: runs.length,
|
|
1083
|
-
failed,
|
|
1084
|
-
missed,
|
|
1085
|
-
avgMs,
|
|
1086
|
-
p50: Math.round(percentile(durations, 50)),
|
|
1087
|
-
p95: Math.round(percentile(durations, 95)),
|
|
1088
|
-
};
|
|
1089
|
-
}
|
|
1090
|
-
export function writeRunMeta(meta) {
|
|
1091
|
-
ensureAgentsDir();
|
|
1092
|
-
const runDir = path.join(getJobRunsDir(meta.jobName), meta.runId);
|
|
1093
|
-
fs.mkdirSync(runDir, { recursive: true });
|
|
1094
|
-
fs.writeFileSync(path.join(runDir, 'meta.json'), JSON.stringify(meta, null, 2), 'utf-8');
|
|
1095
|
-
}
|
|
1096
|
-
export function readRunMeta(jobName, runId) {
|
|
1097
|
-
const metaPath = path.join(getJobRunsDir(jobName), runId, 'meta.json');
|
|
1098
|
-
if (!fs.existsSync(metaPath))
|
|
1099
|
-
return null;
|
|
1100
|
-
try {
|
|
1101
|
-
return JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
|
|
1102
|
-
}
|
|
1103
|
-
catch {
|
|
1104
|
-
return null;
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
export function getJobRunsDir(jobName) {
|
|
1108
|
-
return safeJoin(getRunsDir(), jobName);
|
|
1109
|
-
}
|
|
1110
|
-
export function getRunDir(jobName, runId) {
|
|
1111
|
-
return path.join(getJobRunsDir(jobName), runId);
|
|
1112
|
-
}
|
|
1113
|
-
export function slotRunId(scheduledFor) {
|
|
1114
|
-
const iso = typeof scheduledFor === 'string' ? scheduledFor : scheduledFor.toISOString();
|
|
1115
|
-
return iso.replace(/[:.]/g, '-');
|
|
1116
|
-
}
|
|
1117
|
-
const HOUR_MS = 60 * 60 * 1000;
|
|
1118
|
-
const DAY_MS = 24 * HOUR_MS;
|
|
1119
|
-
const SLOT_LOOKBACK_WINDOWS_MS = [HOUR_MS, DAY_MS, 7 * DAY_MS, 32 * DAY_MS, 93 * DAY_MS, 400 * DAY_MS];
|
|
1120
|
-
export function alignedSlotForFire(cron, at) {
|
|
1121
|
-
for (const window of SLOT_LOOKBACK_WINDOWS_MS) {
|
|
1122
|
-
let cursor = new Date(at.getTime() - window);
|
|
1123
|
-
let last = null;
|
|
1124
|
-
for (let i = 0; i < 20000; i++) {
|
|
1125
|
-
const next = cron.nextRun(cursor);
|
|
1126
|
-
if (!next || next.getTime() > at.getTime())
|
|
1127
|
-
break;
|
|
1128
|
-
last = next;
|
|
1129
|
-
cursor = next;
|
|
1130
|
-
}
|
|
1131
|
-
if (last)
|
|
1132
|
-
return last;
|
|
1133
|
-
}
|
|
1134
|
-
return null;
|
|
1135
|
-
}
|
|
1136
|
-
export function claimRunSlot(jobName, runId) {
|
|
1137
|
-
const runDir = getRunDir(jobName, runId);
|
|
1138
|
-
fs.mkdirSync(path.dirname(runDir), { recursive: true });
|
|
1139
|
-
try {
|
|
1140
|
-
fs.mkdirSync(runDir);
|
|
1141
|
-
return true;
|
|
1142
|
-
}
|
|
1143
|
-
catch (err) {
|
|
1144
|
-
if (err.code === 'EEXIST')
|
|
1145
|
-
return false;
|
|
1146
|
-
throw err;
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
export function discoverJobsFromRepo(repoPath) {
|
|
1150
|
-
const jobsPath = path.join(repoPath, 'routines');
|
|
1151
|
-
if (!fs.existsSync(jobsPath))
|
|
1152
|
-
return [];
|
|
1153
|
-
return fs.readdirSync(jobsPath)
|
|
1154
|
-
.filter((f) => f.endsWith('.yml') || f.endsWith('.yaml'))
|
|
1155
|
-
.map((f) => ({
|
|
1156
|
-
name: f.replace(/\.ya?ml$/, ''),
|
|
1157
|
-
path: path.join(jobsPath, f),
|
|
1158
|
-
}));
|
|
1159
|
-
}
|
|
1160
|
-
export function jobExists(name) {
|
|
1161
|
-
return readJob(name) !== null;
|
|
1162
|
-
}
|
|
1163
|
-
export function isCanonicalRoutineSource(sourcePath, name) {
|
|
1164
|
-
const jobsDir = getRoutinesDir();
|
|
1165
|
-
const real = (p) => {
|
|
1166
|
-
try {
|
|
1167
|
-
return fs.realpathSync(p);
|
|
1168
|
-
}
|
|
1169
|
-
catch {
|
|
1170
|
-
return path.resolve(p);
|
|
1171
|
-
}
|
|
1172
|
-
};
|
|
1173
|
-
const source = real(sourcePath);
|
|
1174
|
-
return ['.yml', '.yaml'].some((ext) => real(safeJoin(jobsDir, name + ext)) === source);
|
|
1175
|
-
}
|
|
1176
|
-
export function getJobPath(name) {
|
|
1177
|
-
const jobsDir = getRoutinesDir();
|
|
1178
|
-
for (const ext of ['.yml', '.yaml']) {
|
|
1179
|
-
const filePath = safeJoin(jobsDir, name + ext);
|
|
1180
|
-
if (fs.existsSync(filePath)) {
|
|
1181
|
-
return filePath;
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
return null;
|
|
1185
|
-
}
|
|
1186
|
-
export function resolveJobFilePath(name) {
|
|
1187
|
-
const userPath = getJobPath(name);
|
|
1188
|
-
if (userPath)
|
|
1189
|
-
return userPath;
|
|
1190
|
-
for (const ext of ['.yml', '.yaml']) {
|
|
1191
|
-
const filePath = safeJoin(getSystemRoutinesDir(), name + ext);
|
|
1192
|
-
if (fs.existsSync(filePath))
|
|
1193
|
-
return filePath;
|
|
1194
|
-
}
|
|
1195
|
-
return null;
|
|
1196
|
-
}
|
|
1197
|
-
export function parseAtTime(atTime) {
|
|
1198
|
-
const timeMatch = atTime.match(/^(\d{1,2}):(\d{2})$/);
|
|
1199
|
-
if (timeMatch) {
|
|
1200
|
-
const hour = parseInt(timeMatch[1], 10);
|
|
1201
|
-
const minute = parseInt(timeMatch[2], 10);
|
|
1202
|
-
if (hour < 0 || hour > 23 || minute < 0 || minute > 59)
|
|
1203
|
-
return null;
|
|
1204
|
-
const now = new Date();
|
|
1205
|
-
let targetDate = new Date();
|
|
1206
|
-
targetDate.setHours(hour, minute, 0, 0);
|
|
1207
|
-
if (targetDate <= now) {
|
|
1208
|
-
targetDate.setDate(targetDate.getDate() + 1);
|
|
1209
|
-
}
|
|
1210
|
-
const day = targetDate.getDate();
|
|
1211
|
-
const month = targetDate.getMonth() + 1;
|
|
1212
|
-
return { schedule: `${minute} ${hour} ${day} ${month} *`, runOnce: true };
|
|
1213
|
-
}
|
|
1214
|
-
const dateTimeMatch = atTime.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})$/);
|
|
1215
|
-
if (dateTimeMatch) {
|
|
1216
|
-
const year = parseInt(dateTimeMatch[1], 10);
|
|
1217
|
-
const month = parseInt(dateTimeMatch[2], 10);
|
|
1218
|
-
const day = parseInt(dateTimeMatch[3], 10);
|
|
1219
|
-
const hour = parseInt(dateTimeMatch[4], 10);
|
|
1220
|
-
const minute = parseInt(dateTimeMatch[5], 10);
|
|
1221
|
-
if (month < 1 || month > 12 || day < 1 || day > 31)
|
|
1222
|
-
return null;
|
|
1223
|
-
if (hour < 0 || hour > 23 || minute < 0 || minute > 59)
|
|
1224
|
-
return null;
|
|
1225
|
-
return { schedule: `${minute} ${hour} ${day} ${month} *`, runOnce: true };
|
|
1226
|
-
}
|
|
1227
|
-
return null;
|
|
1228
|
-
}
|
|
1229
|
-
function listJobsWithRuns() {
|
|
1230
|
-
const runsDir = getRunsDir();
|
|
1231
|
-
if (!fs.existsSync(runsDir))
|
|
1232
|
-
return [];
|
|
1233
|
-
return fs.readdirSync(runsDir, { withFileTypes: true })
|
|
1234
|
-
.filter((e) => e.isDirectory())
|
|
1235
|
-
.map((e) => e.name);
|
|
1236
|
-
}
|
|
1237
|
-
export function countAllRuns() {
|
|
1238
|
-
let total = 0;
|
|
1239
|
-
for (const jobName of listJobsWithRuns()) {
|
|
1240
|
-
total += listRuns(jobName).length;
|
|
1241
|
-
}
|
|
1242
|
-
return total;
|
|
1243
|
-
}
|
|
1244
|
-
export function previewRunsPrune(keep) {
|
|
1245
|
-
const toPrune = [];
|
|
1246
|
-
for (const jobName of listJobsWithRuns()) {
|
|
1247
|
-
const runs = listRuns(jobName);
|
|
1248
|
-
if (runs.length > keep) {
|
|
1249
|
-
const toRemove = runs.slice(0, runs.length - keep);
|
|
1250
|
-
for (const run of toRemove) {
|
|
1251
|
-
toPrune.push({ jobName, runId: run.runId, startedAt: run.startedAt });
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
}
|
|
1255
|
-
return toPrune;
|
|
1256
|
-
}
|
|
1257
|
-
export function pruneRuns(keep) {
|
|
1258
|
-
let deleted = 0;
|
|
1259
|
-
let bytesFreed = 0;
|
|
1260
|
-
for (const jobName of listJobsWithRuns()) {
|
|
1261
|
-
const runs = listRuns(jobName);
|
|
1262
|
-
if (runs.length <= keep)
|
|
1263
|
-
continue;
|
|
1264
|
-
const toRemove = runs.slice(0, runs.length - keep);
|
|
1265
|
-
for (const run of toRemove) {
|
|
1266
|
-
const runDir = getRunDir(jobName, run.runId);
|
|
1267
|
-
bytesFreed += getDirSize(runDir);
|
|
1268
|
-
fs.rmSync(runDir, { recursive: true, force: true });
|
|
1269
|
-
deleted++;
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
return { deleted, bytesFreed };
|
|
1273
|
-
}
|
|
1274
|
-
function getDirSize(dirPath) {
|
|
1275
|
-
if (!fs.existsSync(dirPath))
|
|
1276
|
-
return 0;
|
|
1277
|
-
let size = 0;
|
|
1278
|
-
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
|
1279
|
-
for (const entry of entries) {
|
|
1280
|
-
const fullPath = path.join(dirPath, entry.name);
|
|
1281
|
-
if (entry.isDirectory()) {
|
|
1282
|
-
size += getDirSize(fullPath);
|
|
1283
|
-
}
|
|
1284
|
-
else {
|
|
1285
|
-
try {
|
|
1286
|
-
size += fs.statSync(fullPath).size;
|
|
1287
|
-
}
|
|
1288
|
-
catch { }
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
|
-
return size;
|
|
1292
|
-
}
|