@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.
Files changed (165) hide show
  1. package/CHANGELOG.md +8 -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/projects.js +15 -17
  89. package/dist/lib/session/active.d.ts +1 -3
  90. package/dist/lib/session/active.js +0 -4
  91. package/dist/lib/session/db.d.ts +0 -1
  92. package/dist/lib/session/db.js +4 -8
  93. package/dist/lib/session/discover.d.ts +0 -1
  94. package/dist/lib/session/discover.js +3 -128
  95. package/dist/lib/session/live-metadata.js +0 -2
  96. package/dist/lib/session/presentation.d.ts +0 -1
  97. package/dist/lib/session/presentation.js +3 -8
  98. package/dist/lib/session/selection.d.ts +0 -2
  99. package/dist/lib/session/selection.js +2 -12
  100. package/dist/lib/staleness/detectors/commands.d.ts +1 -1
  101. package/dist/lib/staleness/detectors/hooks.d.ts +1 -1
  102. package/dist/lib/staleness/detectors/mcp.d.ts +1 -1
  103. package/dist/lib/staleness/detectors/permissions.d.ts +1 -1
  104. package/dist/lib/staleness/detectors/plugins.d.ts +1 -1
  105. package/dist/lib/staleness/detectors/rules.d.ts +1 -1
  106. package/dist/lib/staleness/detectors/skills.d.ts +1 -1
  107. package/dist/lib/staleness/detectors/subagents.d.ts +1 -1
  108. package/dist/lib/staleness/detectors/workflows.d.ts +1 -1
  109. package/dist/lib/staleness/writers/commands.d.ts +1 -1
  110. package/dist/lib/staleness/writers/hooks.d.ts +1 -1
  111. package/dist/lib/staleness/writers/mcp.d.ts +1 -1
  112. package/dist/lib/staleness/writers/permissions.d.ts +1 -1
  113. package/dist/lib/staleness/writers/plugins.d.ts +1 -1
  114. package/dist/lib/staleness/writers/rules.d.ts +1 -1
  115. package/dist/lib/staleness/writers/skills.d.ts +1 -1
  116. package/dist/lib/staleness/writers/subagents.d.ts +1 -1
  117. package/dist/lib/staleness/writers/workflows.d.ts +1 -1
  118. package/dist/lib/startup/command-registry.js +5 -2
  119. package/dist/lib/state.d.ts +0 -3
  120. package/dist/lib/state.js +2 -25
  121. package/dist/lib/types.d.ts +0 -1
  122. package/dist/lib/watchdog/runner.d.ts +0 -2
  123. package/dist/lib/watchdog/runner.js +0 -2
  124. package/package.json +1 -1
  125. package/scripts/postinstall.js +2 -2
  126. package/dist/commands/routines.d.ts +0 -14
  127. package/dist/commands/routines.js +0 -2149
  128. package/dist/commands/routines.test-fixture.d.ts +0 -52
  129. package/dist/commands/routines.test-fixture.js +0 -254
  130. package/dist/lib/catchup.d.ts +0 -19
  131. package/dist/lib/catchup.js +0 -83
  132. package/dist/lib/daemon/catchup-service.d.ts +0 -18
  133. package/dist/lib/daemon/catchup-service.js +0 -21
  134. package/dist/lib/daemon/runner.d.ts +0 -91
  135. package/dist/lib/daemon/runner.js +0 -1927
  136. package/dist/lib/harness/adapters/droid.d.ts +0 -2
  137. package/dist/lib/harness/adapters/droid.js +0 -14
  138. package/dist/lib/overdue.d.ts +0 -9
  139. package/dist/lib/overdue.js +0 -74
  140. package/dist/lib/routine-activation.d.ts +0 -13
  141. package/dist/lib/routine-activation.js +0 -117
  142. package/dist/lib/routine-context.d.ts +0 -59
  143. package/dist/lib/routine-context.js +0 -181
  144. package/dist/lib/routine-notify-owner.d.ts +0 -4
  145. package/dist/lib/routine-notify-owner.js +0 -49
  146. package/dist/lib/routine-notify.d.ts +0 -17
  147. package/dist/lib/routine-notify.js +0 -138
  148. package/dist/lib/routine-process-cleanup.d.ts +0 -9
  149. package/dist/lib/routine-process-cleanup.js +0 -81
  150. package/dist/lib/routine-readiness.d.ts +0 -31
  151. package/dist/lib/routine-readiness.js +0 -256
  152. package/dist/lib/routines-format.d.ts +0 -7
  153. package/dist/lib/routines-format.js +0 -127
  154. package/dist/lib/routines-placement.d.ts +0 -16
  155. package/dist/lib/routines-placement.js +0 -60
  156. package/dist/lib/routines-project.d.ts +0 -49
  157. package/dist/lib/routines-project.js +0 -306
  158. package/dist/lib/sandbox.d.ts +0 -15
  159. package/dist/lib/sandbox.js +0 -309
  160. package/dist/lib/scheduler.d.ts +0 -23
  161. package/dist/lib/scheduler.js +0 -106
  162. package/dist/lib/scheduling/routines.d.ts +0 -264
  163. package/dist/lib/scheduling/routines.js +0 -1292
  164. package/dist/lib/triggers/webhook.d.ts +0 -26
  165. package/dist/lib/triggers/webhook.js +0 -181
@@ -1,138 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { getRunDir } from './scheduling/routines.js';
4
- import { notifyDesktop } from './menubar/notify-desktop.js';
5
- export function routineKind(r) {
6
- if (r.command)
7
- return 'command';
8
- if (r.workflow)
9
- return 'workflow';
10
- return 'agent';
11
- }
12
- export function routineAgent(r) {
13
- const kind = routineKind(r);
14
- if (kind === 'command')
15
- return undefined;
16
- if (kind === 'workflow')
17
- return 'claude';
18
- return r.agent?.trim() || undefined;
19
- }
20
- function routineLabel(r) {
21
- if (r.command)
22
- return 'command';
23
- if (r.workflow)
24
- return `workflow ${r.workflow}`;
25
- return `agent ${r.agent ?? 'unknown'}`;
26
- }
27
- export function formatDuration(ms) {
28
- if (ms === undefined || !Number.isFinite(ms) || ms < 0)
29
- return null;
30
- const totalSec = Math.round(ms / 1000);
31
- if (totalSec < 60)
32
- return `${totalSec}s`;
33
- const min = Math.floor(totalSec / 60);
34
- const sec = totalSec % 60;
35
- if (min < 60)
36
- return sec ? `${min}m ${sec}s` : `${min}m`;
37
- const hr = Math.floor(min / 60);
38
- const remMin = min % 60;
39
- return remMin ? `${hr}h ${remMin}m` : `${hr}h`;
40
- }
41
- export function notableSnippet(report, maxLen = 140) {
42
- if (!report)
43
- return null;
44
- const firstLine = report
45
- .split('\n')
46
- .map((l) => l.trim())
47
- .find((l) => l.length > 0);
48
- if (!firstLine)
49
- return null;
50
- return firstLine.length > maxLen ? `${firstLine.slice(0, maxLen - 1).trimEnd()}…` : firstLine;
51
- }
52
- function openAction(filePath) {
53
- return filePath ? `open:${filePath}` : undefined;
54
- }
55
- export function routineStartNotification(config) {
56
- if (routineKind(config) === 'command')
57
- return null;
58
- return {
59
- title: 'Routine started',
60
- subtitle: config.name,
61
- body: `Running ${routineLabel(config)}`,
62
- action: 'routines:list',
63
- agent: routineAgent(config),
64
- };
65
- }
66
- export function routineStartFailedNotification(config, error) {
67
- return {
68
- title: 'Routine failed',
69
- subtitle: config.name,
70
- body: `Failed to start: ${error}`,
71
- action: 'routines:list',
72
- agent: routineAgent(config),
73
- };
74
- }
75
- export function routineFinishNotification(meta, opts = {}) {
76
- const kind = routineKind(meta);
77
- const ok = meta.status === 'completed';
78
- if (kind === 'command' && ok)
79
- return null;
80
- const action = openAction(opts.artifactPath) ?? 'routines:list';
81
- if (ok) {
82
- const snippet = notableSnippet(opts.report);
83
- const dur = formatDuration(meta.duration);
84
- return {
85
- title: 'Routine finished',
86
- subtitle: meta.jobName,
87
- body: snippet ?? (dur ? `Completed in ${dur}` : 'Completed'),
88
- action,
89
- agent: routineAgent(meta),
90
- };
91
- }
92
- const reason = meta.status === 'timeout'
93
- ? 'Timed out'
94
- : meta.errorMessage
95
- ? meta.errorMessage
96
- : `Exited with code ${meta.exitCode ?? '?'}`;
97
- return {
98
- title: 'Routine failed',
99
- subtitle: meta.jobName,
100
- body: reason,
101
- action,
102
- agent: routineAgent(meta),
103
- };
104
- }
105
- function loadRunArtifacts(meta) {
106
- try {
107
- const runDir = getRunDir(meta.jobName, meta.runId);
108
- const reportPath = path.join(runDir, 'report.md');
109
- const stdoutPath = path.join(runDir, 'stdout.log');
110
- let report = null;
111
- let artifactPath = null;
112
- if (fs.existsSync(reportPath)) {
113
- report = fs.readFileSync(reportPath, 'utf-8');
114
- artifactPath = reportPath;
115
- }
116
- else if (fs.existsSync(stdoutPath)) {
117
- artifactPath = stdoutPath;
118
- }
119
- return { report, artifactPath };
120
- }
121
- catch {
122
- return { report: null, artifactPath: null };
123
- }
124
- }
125
- export function notifyRoutineStart(config) {
126
- const n = routineStartNotification(config);
127
- if (n)
128
- notifyDesktop(n);
129
- }
130
- export function notifyRoutineStartFailed(config, error) {
131
- notifyDesktop(routineStartFailedNotification(config, error));
132
- }
133
- export function notifyRoutineFinish(meta) {
134
- const { report, artifactPath } = loadRunArtifacts(meta);
135
- const n = routineFinishNotification(meta, { report, artifactPath });
136
- if (n)
137
- notifyDesktop(n);
138
- }
@@ -1,9 +0,0 @@
1
- import type { RunMeta } from './scheduling/routines.js';
2
- interface RoutineProcessCleanupOptions {
3
- runsDir?: string;
4
- alive?: (pid: number) => boolean;
5
- owns?: (meta: RunMeta) => Promise<boolean> | boolean;
6
- terminate?: (pid: number) => void;
7
- }
8
- export declare function reapTerminalRoutineProcesses(opts?: RoutineProcessCleanupOptions): Promise<number[]>;
9
- export {};
@@ -1,81 +0,0 @@
1
- import * as fsp from 'fs/promises';
2
- import * as path from 'path';
3
- import { execFileBounded } from './exec-bounded.js';
4
- import { isAlive, killTree } from './platform/index.js';
5
- import { getRunsDir } from './state.js';
6
- const IDENTITY_PROBE_TIMEOUT_MS = 5_000;
7
- async function processMatchesRun(meta) {
8
- if (!meta.pid || !meta.spawnedAt)
9
- return false;
10
- if (process.platform === 'win32') {
11
- const res = await execFileBounded('powershell.exe', [
12
- '-NoProfile',
13
- '-NonInteractive',
14
- '-Command',
15
- `(Get-Process -Id ${meta.pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString("o")`,
16
- ], { timeoutMs: IDENTITY_PROBE_TIMEOUT_MS });
17
- if (res.code !== 0)
18
- return false;
19
- const processStart = Date.parse(res.stdout.trim());
20
- return Number.isFinite(processStart) && Math.abs(processStart - meta.spawnedAt) < 30_000;
21
- }
22
- const res = await execFileBounded('ps', ['-p', String(meta.pid), '-o', 'etime='], { timeoutMs: IDENTITY_PROBE_TIMEOUT_MS });
23
- if (res.code !== 0)
24
- return false;
25
- const elapsed = res.stdout.trim();
26
- if (!elapsed)
27
- return false;
28
- const fields = elapsed.replace(/-/g, ':').split(':').reverse();
29
- const seconds = Number(fields[0] ?? 0)
30
- + Number(fields[1] ?? 0) * 60
31
- + Number(fields[2] ?? 0) * 3600
32
- + Number(fields[3] ?? 0) * 86400;
33
- return Math.abs((Date.now() - seconds * 1000) - meta.spawnedAt) < 30_000;
34
- }
35
- export async function reapTerminalRoutineProcesses(opts = {}) {
36
- const runsDir = opts.runsDir ?? getRunsDir();
37
- const alive = opts.alive ?? isAlive;
38
- const owns = opts.owns ?? processMatchesRun;
39
- const terminate = opts.terminate ?? ((pid) => killTree(process.platform === 'win32' ? pid : -pid));
40
- let jobs;
41
- try {
42
- jobs = await fsp.readdir(runsDir, { withFileTypes: true });
43
- }
44
- catch {
45
- return [];
46
- }
47
- const reaped = [];
48
- for (const job of jobs) {
49
- if (!job.isDirectory())
50
- continue;
51
- const jobDir = path.join(runsDir, job.name);
52
- let runs;
53
- try {
54
- runs = await fsp.readdir(jobDir, { withFileTypes: true });
55
- }
56
- catch {
57
- continue;
58
- }
59
- for (const run of runs) {
60
- if (!run.isDirectory())
61
- continue;
62
- try {
63
- const meta = JSON.parse(await fsp.readFile(path.join(jobDir, run.name, 'meta.json'), 'utf-8'));
64
- if (!['failed', 'timeout'].includes(meta.status) || !meta.pid || meta.hostTaskId || meta.cloudTaskId)
65
- continue;
66
- const completedAt = Date.parse(meta.completedAt ?? '');
67
- if (!Number.isFinite(completedAt) || Date.now() - completedAt < 5_000)
68
- continue;
69
- if (!alive(meta.pid))
70
- continue;
71
- if (!(await owns(meta)))
72
- continue;
73
- terminate(meta.pid);
74
- reaped.push(meta.pid);
75
- }
76
- catch {
77
- }
78
- }
79
- }
80
- return reaped;
81
- }
@@ -1,31 +0,0 @@
1
- import type { JobConfig } from './scheduling/routines.js';
2
- import { type RoutineReadinessResult, type RoutineReadiness } from './routine-context.js';
3
- import { type AuthVerdict } from './auth-health.js';
4
- export declare function fireTimeAuthReadiness(agent: string, version: string): RoutineReadiness | null;
5
- export declare function evaluateActivationReadiness(config: JobConfig, deps?: {
6
- probeAgent?: (agent: string) => boolean;
7
- }): RoutineReadinessResult;
8
- interface RemoteProjectDefinition {
9
- name: string;
10
- root?: string;
11
- defaultPath?: string;
12
- }
13
- export declare function parseRemoteProjectSnapshot(stdout: string): {
14
- home: string;
15
- projects: RemoteProjectDefinition[];
16
- } | undefined;
17
- export declare function buildRemoteWorkspaceProbe(cwd: string, windows: boolean): string;
18
- export declare function probeOutputHasSentinel(stdout: string, sentinel: string): boolean;
19
- export declare function decideRoutineAuthReadiness(row: {
20
- verdict: AuthVerdict;
21
- } | undefined, launchable: boolean): {
22
- ok: boolean;
23
- reason?: string;
24
- };
25
- export declare function decideHostAuthFromPing(stdout: string, agent: string): {
26
- ok: boolean;
27
- reason?: string;
28
- } | null;
29
- export declare function evaluateActivationReadinessLive(config: JobConfig): Promise<RoutineReadinessResult>;
30
- export declare function evaluateHostActivationReadiness(config: JobConfig): Promise<RoutineReadinessResult>;
31
- export {};
@@ -1,256 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as TOML from 'smol-toml';
4
- import { resolveJobExecutionContext, resolveHostStrategy } from './scheduling/routines.js';
5
- import { evaluateRoutineReadiness } from './routine-context.js';
6
- import { readAuthHealth } from './auth-health.js';
7
- import { machineId } from './machine-id.js';
8
- import { getVersionHomePath, isVersionInstalled, resolveVersion } from './installations/versions.js';
9
- import { probeLocalFleetAuth } from './auth-health.js';
10
- import { resolveHostRunTarget } from './hosts/run-target.js';
11
- import { hostIdentityArgs, sshTargetFor } from './hosts/types.js';
12
- import { probeHost } from './hosts/ready.js';
13
- import { sshExec, shellQuote } from './ssh-exec.js';
14
- import { encodePowershell, powershellQuote, POWERSHELL_PROGRESS_SILENCE } from './hosts/remote-cmd.js';
15
- /**
16
- * Verdicts that make a FIRE-TIME auth preflight block the run: the last live
17
- * probe found the account either server-rejected (`revoked`) or with no
18
- * credential at all (`unconfigured` — the "Please run /login" / "no account
19
- * signed in" case, which is the most common way a routine's dispatch account
20
- * goes dead). Everything else fails OPEN: `rate_limited` is still authenticated,
21
- * `expired` self-heals on the next refresh, `unverified` means signed-in but no
22
- * live probe endpoint (codex/grok), and `error` is indeterminate — none of those
23
- * should stop a fire. This is deliberately BROADER than {@link isDeadVerdict}
24
- * (display-only, `revoked` alone): a signed-out account must block a fire, not
25
- * just paint a red cell.
26
- */
27
- function fireBlockingAuthVerdict(verdict) {
28
- return verdict === 'revoked' || verdict === 'unconfigured';
29
- }
30
- export function fireTimeAuthReadiness(agent, version) {
31
- // Fire-time auth is cache-only and fail-open unless the last verdict proves signed-out/revoked.
32
- const health = readAuthHealth(machineId(), agent, version);
33
- if (!health || !fireBlockingAuthVerdict(health.verdict))
34
- return null;
35
- const who = health.account ? ` (${health.account})` : '';
36
- return {
37
- code: 'agent_auth_failed',
38
- message: `the ${agent}${who} account is signed out — the last auth probe returned '${health.verdict}', so this run would fail authentication`,
39
- repair: `agents run ${agent}@${version} -- login`,
40
- };
41
- }
42
- export function evaluateActivationReadiness(config, deps = {}) {
43
- const strategy = resolveHostStrategy(config);
44
- const mode = strategy;
45
- const context = resolveJobExecutionContext(config, {
46
- mode,
47
- probe: mode === 'local' ? undefined : null,
48
- });
49
- const pinnedLocally = mode === 'local' ? config.version : undefined;
50
- const probeAgent = deps.probeAgent ?? ((agent) => pinnedLocally
51
- ? isVersionInstalled(agent, pinnedLocally)
52
- : resolveVersion(agent) !== undefined);
53
- return evaluateRoutineReadiness(context, {
54
- agentInstalled: config.agent && !config.workflow && !config.command
55
- ? () => probeAgent(config.agent)
56
- : undefined,
57
- }, { agent: config.agent, version: pinnedLocally });
58
- }
59
- export function parseRemoteProjectSnapshot(stdout) {
60
- const lines = stdout.split(/\r?\n/);
61
- const homeLine = lines.shift();
62
- if (!homeLine?.startsWith('__HOME__'))
63
- return undefined;
64
- const home = homeLine.slice('__HOME__'.length);
65
- if (!home)
66
- return undefined;
67
- try {
68
- const projects = JSON.parse(lines.join('\n'));
69
- if (!Array.isArray(projects))
70
- return undefined;
71
- if (!projects.every((entry) => entry && typeof entry === 'object' && typeof entry.name === 'string')) {
72
- return undefined;
73
- }
74
- return { home, projects: projects };
75
- }
76
- catch {
77
- return undefined;
78
- }
79
- }
80
- export function buildRemoteWorkspaceProbe(cwd, windows) {
81
- if (windows) {
82
- return `powershell -NoProfile -EncodedCommand ${encodePowershell(`$d=${powershellQuote(cwd)}; if (-not (Test-Path -LiteralPath $d -PathType Container)) { exit 1 }; $p=Join-Path $d ([IO.Path]::GetRandomFileName()); try { New-Item -ItemType File -Path $p -ErrorAction Stop | Out-Null; Remove-Item -LiteralPath $p -Force -ErrorAction Stop; exit 0 } catch { exit 1 }`)}`;
83
- }
84
- const pattern = path.posix.join(cwd, '.agents-routine-readiness.XXXXXX');
85
- return `probe_path=$(mktemp ${shellQuote(pattern)}) && rm -f "$probe_path"`;
86
- }
87
- export function probeOutputHasSentinel(stdout, sentinel) {
88
- const containsExact = (value) => {
89
- if (value === sentinel)
90
- return true;
91
- if (Array.isArray(value))
92
- return value.some(containsExact);
93
- if (value && typeof value === 'object')
94
- return Object.values(value).some(containsExact);
95
- return false;
96
- };
97
- return stdout.split(/\r?\n/).some((line) => {
98
- const trimmed = line.trim();
99
- if (trimmed === sentinel)
100
- return true;
101
- try {
102
- return containsExact(JSON.parse(trimmed));
103
- }
104
- catch {
105
- return false;
106
- }
107
- });
108
- }
109
- function codexWorkspaceTrusted(version, cwd) {
110
- try {
111
- const configPath = path.join(getVersionHomePath('codex', version), '.codex', 'config.toml');
112
- const parsed = TOML.parse(fs.readFileSync(configPath, 'utf-8'));
113
- const projects = parsed.projects;
114
- return Object.entries(projects ?? {}).some(([root, project]) => {
115
- if (project.trust_level !== 'trusted')
116
- return false;
117
- const relative = path.relative(root, cwd);
118
- return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
119
- });
120
- }
121
- catch {
122
- return false;
123
- }
124
- }
125
- const ROUTINE_AUTH_ACCEPTED = new Set([
126
- 'live', 'rate_limited', 'unverified', 'no_evidence',
127
- ]);
128
- export function decideRoutineAuthReadiness(row, launchable) {
129
- // Local and remote probes share absent-row semantics: launchability proves token-backed readiness.
130
- if (row && ROUTINE_AUTH_ACCEPTED.has(row.verdict))
131
- return { ok: true };
132
- if (!row)
133
- return launchable ? { ok: true } : { ok: false, reason: 'unconfigured' };
134
- return { ok: false, reason: row.verdict };
135
- }
136
- export function decideHostAuthFromPing(stdout, agent) {
137
- // Unparseable output is a probe failure, never evidence that a credential is absent.
138
- let payload;
139
- try {
140
- payload = JSON.parse(stdout);
141
- }
142
- catch {
143
- return null;
144
- }
145
- if (!payload || typeof payload !== 'object')
146
- return null;
147
- const { rows, launchable } = payload;
148
- const verdict = rows?.find((row) => row.agent === agent)?.health?.verdict;
149
- const row = verdict ? { verdict } : undefined;
150
- return decideRoutineAuthReadiness(row, launchable?.includes(agent) ?? false);
151
- }
152
- export async function evaluateActivationReadinessLive(config) {
153
- const structural = evaluateActivationReadiness(config);
154
- if (!structural.ready)
155
- return structural;
156
- const mode = resolveHostStrategy(config);
157
- if (mode === 'host' && config.host)
158
- return evaluateHostActivationReadiness(config);
159
- if (mode !== 'local' || !config.agent || config.workflow || config.command)
160
- return structural;
161
- const version = resolveVersion(config.agent);
162
- if (!version)
163
- return structural;
164
- const context = resolveJobExecutionContext(config, { mode: 'local' });
165
- const rows = await probeLocalFleetAuth({ agents: [config.agent] });
166
- const row = rows.find((candidate) => candidate.version === version);
167
- const { collectRunCandidates } = await import('./accounting/rotate.js');
168
- const launchable = (await collectRunCandidates(config.agent)).some((candidate) => candidate.signedIn);
169
- const authVerdict = decideRoutineAuthReadiness(row?.health, launchable);
170
- return evaluateRoutineReadiness(context, {
171
- agentInstalled: () => true,
172
- ...(config.agent === 'codex' && context.absoluteCwd
173
- ? { codexTrusted: () => codexWorkspaceTrusted(version, context.absoluteCwd) }
174
- : {}),
175
- authOk: () => authVerdict,
176
- }, { agent: config.agent });
177
- }
178
- export async function evaluateHostActivationReadiness(config) {
179
- const host = await resolveHostRunTarget(config.host);
180
- const target = sshTargetFor(host);
181
- const identity = hostIdentityArgs(host);
182
- if (!probeHost(target, host.os, identity).reachable) {
183
- return evaluateRoutineReadiness(resolveJobExecutionContext(config, { mode: 'host', probe: null }), {
184
- targetReachable: () => false,
185
- }, { agent: config.agent });
186
- }
187
- const windows = host.os?.toLowerCase().includes('win') ?? false;
188
- const homeCommand = windows
189
- ? `powershell -NoProfile -EncodedCommand ${encodePowershell(`${POWERSHELL_PROGRESS_SILENCE}; Write-Output ("__HOME__" + $HOME); & agents projects list --json`)}`
190
- : `bash -lc ${shellQuote('printf "__HOME__%s\\n" "$HOME"; agents projects list --json')}`;
191
- const projectResult = sshExec(target, homeCommand, { timeoutMs: 20_000, extraSshArgs: identity });
192
- if (projectResult.code !== 0) {
193
- return evaluateRoutineReadiness(resolveJobExecutionContext(config, { mode: 'host', probe: null }), {
194
- targetReachable: () => false,
195
- }, { agent: config.agent });
196
- }
197
- const snapshot = parseRemoteProjectSnapshot(projectResult.stdout);
198
- if (!snapshot) {
199
- return evaluateRoutineReadiness(resolveJobExecutionContext(config, { mode: 'host', probe: null }), {
200
- targetReachable: () => false,
201
- }, { agent: config.agent });
202
- }
203
- const targetHome = snapshot.home;
204
- const defs = snapshot.projects;
205
- const def = config.project ? defs.find((candidate) => candidate.name === config.project) : undefined;
206
- const projectResolution = config.project
207
- ? (def ? { defined: true, base: def.defaultPath ?? def.root } : { defined: false })
208
- : undefined;
209
- const unprobed = resolveJobExecutionContext(config, { mode: 'host', targetHome, probe: null, projectResolution });
210
- if (!unprobed.ready || !unprobed.absoluteCwd)
211
- return { context: unprobed, ready: false, readiness: unprobed.readiness };
212
- const check = buildRemoteWorkspaceProbe(unprobed.absoluteCwd, windows);
213
- const fsResult = sshExec(target, check, { timeoutMs: 12_000, extraSshArgs: identity });
214
- if (fsResult.code !== 0) {
215
- return evaluateRoutineReadiness({ ...unprobed, ready: false, readiness: {
216
- code: 'workspace_not_writable',
217
- message: `the execution directory is missing or not writable on ${host.name}: ${unprobed.resolvedCwd}`,
218
- } });
219
- }
220
- if (config.agent && !config.workflow && !config.command) {
221
- // A failed live probe stays distinct from an absent auth row.
222
- if (config.agent === 'codex') {
223
- const args = ['run', 'codex', 'Reply with exactly ROUTINE_READY', '--mode', 'plan', '--timeout', '45s', '--json'];
224
- const command = windows
225
- ? `powershell -NoProfile -EncodedCommand ${encodePowershell(`${POWERSHELL_PROGRESS_SILENCE}; Set-Location -LiteralPath ${powershellQuote(unprobed.absoluteCwd)}; & agents ${args.map(powershellQuote).join(' ')}`)}`
226
- : `cd ${shellQuote(unprobed.absoluteCwd)} && agents ${args.map(shellQuote).join(' ')}`;
227
- const probe = sshExec(target, command, { timeoutMs: 60_000, extraSshArgs: identity });
228
- if (probe.code !== 0 || !probeOutputHasSentinel(probe.stdout, 'ROUTINE_READY')) {
229
- const detail = `${probe.stderr}\n${probe.stdout}`.trim();
230
- const untrusted = detail.includes('trusted directory') || detail.includes('trusted workspace');
231
- return evaluateRoutineReadiness(unprobed, {
232
- ...(untrusted ? { codexTrusted: () => false } : { authOk: () => ({ ok: false, reason: detail || 'probe failed' }) }),
233
- }, { agent: config.agent });
234
- }
235
- }
236
- else {
237
- const pingArgs = ['devices', 'ping', '--local', '--json'];
238
- const command = windows
239
- ? `powershell -NoProfile -EncodedCommand ${encodePowershell(`${POWERSHELL_PROGRESS_SILENCE}; & agents ${pingArgs.map(powershellQuote).join(' ')}`)}`
240
- : `agents ${pingArgs.map(shellQuote).join(' ')}`;
241
- const probe = sshExec(target, command, { timeoutMs: 30_000, extraSshArgs: identity });
242
- const decision = probe.code === 0 ? decideHostAuthFromPing(probe.stdout, config.agent) : null;
243
- if (!decision) {
244
- return evaluateRoutineReadiness(unprobed, {
245
- authOk: () => ({ ok: false, reason: `devices ping --local failed on ${host.name}` }),
246
- }, { agent: config.agent });
247
- }
248
- if (!decision.ok) {
249
- return evaluateRoutineReadiness(unprobed, {
250
- authOk: () => decision,
251
- }, { agent: config.agent });
252
- }
253
- }
254
- }
255
- return { context: unprobed, ready: true };
256
- }
@@ -1,7 +0,0 @@
1
- export declare function humanizeCron(expr: string, _tz?: string): string;
2
- export declare function humanizeNextRun(date: Date | null, now: Date, tz?: string): string;
3
- export declare const REPO_DISPLAY_MAX = 24;
4
- export declare function formatRepoLink(repo: unknown): {
5
- display: string;
6
- href: string | null;
7
- };
@@ -1,127 +0,0 @@
1
- const DAY_NAMES = ['Sundays', 'Mondays', 'Tuesdays', 'Wednesdays', 'Thursdays', 'Fridays', 'Saturdays'];
2
- export function humanizeCron(expr, _tz) {
3
- try {
4
- const parts = expr.trim().split(/\s+/);
5
- if (parts.length !== 5)
6
- return expr;
7
- const [minute, hour, dom, month, dow] = parts;
8
- if (minute === '*' && hour === '*' && dom === '*' && month === '*' && dow === '*') {
9
- return 'every minute';
10
- }
11
- const everyMinMatch = minute.match(/^\*\/(\d+)$/);
12
- if (everyMinMatch && hour === '*' && dom === '*' && month === '*' && dow === '*') {
13
- const n = parseInt(everyMinMatch[1], 10);
14
- return `every ${n} minute${n === 1 ? '' : 's'}`;
15
- }
16
- const everyHourMatch = hour.match(/^\*\/(\d+)$/);
17
- if (everyHourMatch && minute === '0' && dom === '*' && month === '*' && dow === '*') {
18
- const n = parseInt(everyHourMatch[1], 10);
19
- return `every ${n} hour${n === 1 ? '' : 's'}`;
20
- }
21
- const hourNum = /^\d+$/.test(hour) ? parseInt(hour, 10) : null;
22
- const minNum = /^\d+$/.test(minute) ? parseInt(minute, 10) : null;
23
- if (hourNum === null || minNum === null)
24
- return expr;
25
- const timeStr = formatTime12(hourNum, minNum);
26
- if (dom === '*' && month === '*' && dow === '*') {
27
- return `daily at ${timeStr}`;
28
- }
29
- if (dom === '*' && month === '*' && dow === '1-5') {
30
- return `weekdays at ${timeStr}`;
31
- }
32
- if (dom === '*' && month === '*' && /^\d$/.test(dow)) {
33
- const dayIdx = parseInt(dow, 10);
34
- if (dayIdx >= 0 && dayIdx <= 6) {
35
- return `${DAY_NAMES[dayIdx]} at ${timeStr}`;
36
- }
37
- }
38
- if (/^\d+$/.test(dom) && month === '*' && dow === '*') {
39
- const d = parseInt(dom, 10);
40
- return `monthly on day ${d} at ${timeStr}`;
41
- }
42
- if (everyHourMatch && dom === '*' && month === '*' && dow === '*') {
43
- const n = parseInt(everyHourMatch[1], 10);
44
- return `every ${n} hour${n === 1 ? '' : 's'} at :${String(minNum).padStart(2, '0')}`;
45
- }
46
- return expr;
47
- }
48
- catch {
49
- return expr;
50
- }
51
- }
52
- function formatTime12(hour, minute) {
53
- const period = hour < 12 ? 'AM' : 'PM';
54
- const h = hour % 12 === 0 ? 12 : hour % 12;
55
- const m = String(minute).padStart(2, '0');
56
- return `${h}:${m} ${period}`;
57
- }
58
- const WEEKDAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
59
- const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
60
- export function humanizeNextRun(date, now, tz) {
61
- if (!date)
62
- return '-';
63
- try {
64
- const locale = 'en-US';
65
- const tzOpts = tz ? { timeZone: tz } : {};
66
- const toYMD = (d) => {
67
- const fmt = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'numeric', day: 'numeric', ...tzOpts });
68
- const parts = fmt.formatToParts(d);
69
- const get = (type) => parseInt(parts.find((p) => p.type === type)?.value ?? '0', 10);
70
- return { y: get('year'), m: get('month'), day: get('day') };
71
- };
72
- const nowYMD = toYMD(now);
73
- const dateYMD = toYMD(date);
74
- const nowMidnight = Date.UTC(nowYMD.y, nowYMD.m - 1, nowYMD.day);
75
- const dateMidnight = Date.UTC(dateYMD.y, dateYMD.m - 1, dateYMD.day);
76
- const diffDays = Math.round((dateMidnight - nowMidnight) / 86400000);
77
- const timeFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', hour12: true, ...tzOpts });
78
- const timeStr = timeFmt.format(date);
79
- if (diffDays === 0)
80
- return `today ${timeStr}`;
81
- if (diffDays === 1)
82
- return `tomorrow ${timeStr}`;
83
- if (diffDays < 7) {
84
- const weekdayIdx = new Intl.DateTimeFormat(locale, { weekday: 'short', ...tzOpts })
85
- .formatToParts(date)
86
- .find((p) => p.type === 'weekday')?.value;
87
- return `${weekdayIdx ?? WEEKDAY_NAMES[date.getDay()]} ${timeStr}`;
88
- }
89
- const monthName = MONTH_NAMES[dateYMD.m - 1];
90
- return `${monthName} ${dateYMD.day}, ${timeStr}`;
91
- }
92
- catch {
93
- return date.toLocaleString();
94
- }
95
- }
96
- export const REPO_DISPLAY_MAX = 24;
97
- export function formatRepoLink(repo) {
98
- if (repo == null || typeof repo !== 'string' || repo.trim() === '') {
99
- return { display: '-', href: null };
100
- }
101
- const trimmed = repo.trim();
102
- let display;
103
- let href;
104
- if (trimmed.startsWith('https://') || trimmed.startsWith('http://')) {
105
- try {
106
- const url = new URL(trimmed);
107
- display = url.hostname + url.pathname.replace(/\/$/, '');
108
- href = trimmed;
109
- }
110
- catch {
111
- display = trimmed;
112
- href = null;
113
- }
114
- }
115
- else if (/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(trimmed)) {
116
- display = trimmed;
117
- href = `https://github.com/${trimmed}/pulls`;
118
- }
119
- else {
120
- display = trimmed;
121
- href = null;
122
- }
123
- if (display.length > REPO_DISPLAY_MAX) {
124
- display = display.slice(0, REPO_DISPLAY_MAX - 1) + '…';
125
- }
126
- return { display, href };
127
- }
@@ -1,16 +0,0 @@
1
- import type { JobConfig } from './scheduling/routines.js';
2
- import { type DevicePlatform } from './devices/registry.js';
3
- export type PlacementTarget = {
4
- mode: 'local';
5
- } | {
6
- mode: 'host';
7
- host: string;
8
- } | {
9
- mode: 'cloud';
10
- };
11
- export declare function pickFleetDevice(_config?: Pick<JobConfig, 'devices'>, platform?: DevicePlatform): string | null;
12
- export declare function resolvePlacementTarget(config: JobConfig, deps?: {
13
- resolveDeviceAuto?: (agent?: string) => Promise<{
14
- pickedDeviceKey: string;
15
- }>;
16
- }): Promise<PlacementTarget>;