@phnx-labs/agents-cli 1.23.28 → 1.23.30

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 (171) hide show
  1. package/CHANGELOG.md +10 -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/answer-router.d.ts +1 -1
  38. package/dist/lib/answer-router.js +9 -10
  39. package/dist/lib/auth-health.d.ts +0 -1
  40. package/dist/lib/auth-health.js +0 -3
  41. package/dist/lib/cli-entry.d.ts +0 -1
  42. package/dist/lib/cli-entry.js +0 -36
  43. package/dist/lib/cloud/types.d.ts +0 -2
  44. package/dist/lib/config-keys.d.ts +1 -1
  45. package/dist/lib/config-keys.js +1 -4
  46. package/dist/lib/daemon/daemon.d.ts +0 -4
  47. package/dist/lib/daemon/daemon.js +6 -202
  48. package/dist/lib/daemon/heartbeat-service.d.ts +1 -1
  49. package/dist/lib/daemon/heartbeat-service.js +1 -8
  50. package/dist/lib/daemon-services.d.ts +1 -1
  51. package/dist/lib/daemon-services.js +1 -11
  52. package/dist/lib/device-config.d.ts +0 -2
  53. package/dist/lib/device-config.js +4 -22
  54. package/dist/lib/devices/config-migration.js +1 -3
  55. package/dist/lib/exec.d.ts +2 -5
  56. package/dist/lib/exec.js +18 -18
  57. package/dist/lib/factory/snapshot.d.ts +0 -5
  58. package/dist/lib/factory/snapshot.js +1 -28
  59. package/dist/lib/feed/events.d.ts +1 -11
  60. package/dist/lib/feed/events.js +0 -20
  61. package/dist/lib/feed/feed.d.ts +1 -3
  62. package/dist/lib/feed/feed.js +18 -1
  63. package/dist/lib/feed-outcome.d.ts +0 -2
  64. package/dist/lib/feed-outcome.js +0 -5
  65. package/dist/lib/fleet/capture.d.ts +0 -1
  66. package/dist/lib/fleet/capture.js +0 -3
  67. package/dist/lib/fleet/manifest.js +0 -6
  68. package/dist/lib/fleet/types.d.ts +0 -1
  69. package/dist/lib/harness/adapter.d.ts +0 -7
  70. package/dist/lib/harness/adapters/claude.js +0 -18
  71. package/dist/lib/harness/adapters/codex.js +0 -10
  72. package/dist/lib/harness/adapters/cursor.js +0 -11
  73. package/dist/lib/harness/adapters/kimi.js +0 -3
  74. package/dist/lib/harness/adapters/muse.js +0 -11
  75. package/dist/lib/harness/index.d.ts +1 -1
  76. package/dist/lib/harness/index.js +0 -2
  77. package/dist/lib/hosts/passthrough.js +2 -10
  78. package/dist/lib/hosts/ready.d.ts +0 -4
  79. package/dist/lib/hosts/ready.js +0 -9
  80. package/dist/lib/hosts/reconcile.d.ts +0 -1
  81. package/dist/lib/hosts/reconcile.js +0 -8
  82. package/dist/lib/installations/migrate.d.ts +0 -2
  83. package/dist/lib/installations/migrate.js +0 -145
  84. package/dist/lib/loop.js +1 -2
  85. package/dist/lib/menubar/snapshot.d.ts +0 -1
  86. package/dist/lib/menubar/snapshot.js +1 -4
  87. package/dist/lib/placement.d.ts +1 -2
  88. package/dist/lib/placement.js +4 -24
  89. package/dist/lib/profiles.d.ts +0 -1
  90. package/dist/lib/profiles.js +0 -6
  91. package/dist/lib/session/active.d.ts +4 -3
  92. package/dist/lib/session/active.js +3 -4
  93. package/dist/lib/session/db.d.ts +7 -5
  94. package/dist/lib/session/db.js +11 -14
  95. package/dist/lib/session/discover.d.ts +3 -2
  96. package/dist/lib/session/discover.js +12 -129
  97. package/dist/lib/session/live-metadata.js +0 -2
  98. package/dist/lib/session/presentation.d.ts +0 -1
  99. package/dist/lib/session/presentation.js +3 -8
  100. package/dist/lib/session/selection.d.ts +0 -2
  101. package/dist/lib/session/selection.js +2 -12
  102. package/dist/lib/session/session-cache.d.ts +2 -1
  103. package/dist/lib/session/session-cache.js +1 -0
  104. package/dist/lib/session/title.d.ts +10 -0
  105. package/dist/lib/session/title.js +9 -0
  106. package/dist/lib/staleness/detectors/commands.d.ts +1 -1
  107. package/dist/lib/staleness/detectors/hooks.d.ts +1 -1
  108. package/dist/lib/staleness/detectors/mcp.d.ts +1 -1
  109. package/dist/lib/staleness/detectors/permissions.d.ts +1 -1
  110. package/dist/lib/staleness/detectors/plugins.d.ts +1 -1
  111. package/dist/lib/staleness/detectors/rules.d.ts +1 -1
  112. package/dist/lib/staleness/detectors/skills.d.ts +1 -1
  113. package/dist/lib/staleness/detectors/subagents.d.ts +1 -1
  114. package/dist/lib/staleness/detectors/workflows.d.ts +1 -1
  115. package/dist/lib/staleness/writers/commands.d.ts +1 -1
  116. package/dist/lib/staleness/writers/hooks.d.ts +1 -1
  117. package/dist/lib/staleness/writers/mcp.d.ts +1 -1
  118. package/dist/lib/staleness/writers/permissions.d.ts +1 -1
  119. package/dist/lib/staleness/writers/plugins.d.ts +1 -1
  120. package/dist/lib/staleness/writers/rules.d.ts +1 -1
  121. package/dist/lib/staleness/writers/skills.d.ts +1 -1
  122. package/dist/lib/staleness/writers/subagents.d.ts +1 -1
  123. package/dist/lib/staleness/writers/workflows.d.ts +1 -1
  124. package/dist/lib/startup/command-registry.js +5 -2
  125. package/dist/lib/state.d.ts +0 -3
  126. package/dist/lib/state.js +2 -25
  127. package/dist/lib/types.d.ts +0 -1
  128. package/dist/lib/watchdog/runner.d.ts +0 -2
  129. package/dist/lib/watchdog/runner.js +0 -2
  130. package/package.json +2 -2
  131. package/scripts/postinstall.js +2 -2
  132. package/dist/commands/routines.d.ts +0 -14
  133. package/dist/commands/routines.js +0 -2149
  134. package/dist/commands/routines.test-fixture.d.ts +0 -52
  135. package/dist/commands/routines.test-fixture.js +0 -254
  136. package/dist/lib/catchup.d.ts +0 -19
  137. package/dist/lib/catchup.js +0 -83
  138. package/dist/lib/daemon/catchup-service.d.ts +0 -18
  139. package/dist/lib/daemon/catchup-service.js +0 -21
  140. package/dist/lib/daemon/runner.d.ts +0 -91
  141. package/dist/lib/daemon/runner.js +0 -1927
  142. package/dist/lib/harness/adapters/droid.d.ts +0 -2
  143. package/dist/lib/harness/adapters/droid.js +0 -14
  144. package/dist/lib/overdue.d.ts +0 -9
  145. package/dist/lib/overdue.js +0 -74
  146. package/dist/lib/routine-activation.d.ts +0 -13
  147. package/dist/lib/routine-activation.js +0 -117
  148. package/dist/lib/routine-context.d.ts +0 -59
  149. package/dist/lib/routine-context.js +0 -181
  150. package/dist/lib/routine-notify-owner.d.ts +0 -4
  151. package/dist/lib/routine-notify-owner.js +0 -49
  152. package/dist/lib/routine-notify.d.ts +0 -17
  153. package/dist/lib/routine-notify.js +0 -138
  154. package/dist/lib/routine-process-cleanup.d.ts +0 -9
  155. package/dist/lib/routine-process-cleanup.js +0 -81
  156. package/dist/lib/routine-readiness.d.ts +0 -31
  157. package/dist/lib/routine-readiness.js +0 -256
  158. package/dist/lib/routines-format.d.ts +0 -7
  159. package/dist/lib/routines-format.js +0 -127
  160. package/dist/lib/routines-placement.d.ts +0 -16
  161. package/dist/lib/routines-placement.js +0 -60
  162. package/dist/lib/routines-project.d.ts +0 -49
  163. package/dist/lib/routines-project.js +0 -306
  164. package/dist/lib/sandbox.d.ts +0 -15
  165. package/dist/lib/sandbox.js +0 -309
  166. package/dist/lib/scheduler.d.ts +0 -23
  167. package/dist/lib/scheduler.js +0 -106
  168. package/dist/lib/scheduling/routines.d.ts +0 -264
  169. package/dist/lib/scheduling/routines.js +0 -1292
  170. package/dist/lib/triggers/webhook.d.ts +0 -26
  171. package/dist/lib/triggers/webhook.js +0 -181
@@ -1,1927 +0,0 @@
1
- import { spawn, execFileSync } from 'child_process';
2
- import * as fs from 'fs';
3
- import * as fsp from 'fs/promises';
4
- import * as path from 'path';
5
- import * as os from 'os';
6
- import { getCliLaunch, getAgentsBinDir } from '../cli-entry.js';
7
- import { resolveJobPrompt, parseTimeout, writeRunMeta, listRuns, getJobRunsDir, getRunDir, checkJobDeviceEligibility, finalizeRunMeta, resolveJobExecutionContext, slotRunId, claimRunSlot, readRunMeta, resolveHostStrategy, } from '../scheduling/routines.js';
8
- import { getRunsDir, getUserAgentsDir, readMeta, getDaemonDir } from '../state.js';
9
- import { shortCodexHome } from '../codex-home.js';
10
- import { prepareJobHome, buildSpawnEnv, getJobHomePath, assertSandboxForwardsHostGhAuth, linkVersionAuth } from '../sandbox.js';
11
- import { resolveModel, buildReasoningFlags } from '../models.js';
12
- import { createTimer, redactPrompt, emitRoutineEnd, emitRoutineEndAsync } from '../feed/events.js';
13
- import { resolveHarnessAdapter } from '../harness/index.js';
14
- import { applyAddDirs } from '../add-dir.js';
15
- import { normalizeMode, resolveHeadlessMode, buildExecEnv, detectRateLimit, detectAuthFailure, isAuthFailureFromLog, authFailureReason, AGENT_COMMANDS, } from '../exec.js';
16
- import { resolveActor } from '../actor.js';
17
- import { loadTask as loadHostTask } from '../hosts/tasks.js';
18
- import { reconcileTask as reconcileHostTask, reconcileTaskAsync as reconcileHostTaskAsync } from '../hosts/reconcile.js';
19
- import { backgroundSpawnOptions, isAlive, killTree } from '../platform/process.js';
20
- import { execFileBounded } from '../exec-bounded.js';
21
- import lockfile from 'proper-lockfile';
22
- import { ensureLockTarget } from '../fs-atomic.js';
23
- import { logAndContinueOnLockCompromised } from '../lock-compromise.js';
24
- import { walkForFiles } from '../fs-walk.js';
25
- import { getBinaryPath, isVersionInstalled, resolveVersion, getVersionHomePath } from '../installations/versions.js';
26
- import { resolveClaudeSetupToken } from '../claude-account-token.js';
27
- import { getConfiguredRunStrategy, resolveRunVersion, resolveAccountCandidate, rotationFailoverChain, readinessFromCandidate, formatNoHealthyAccountError, formatNoVerifiedUsageError, } from '../accounting/rotate.js';
28
- import { isHeadedDeviceRole, selfConfiguredDeviceRole } from '../device-config.js';
29
- import { isSelfUpdatingAgent, ROUTINE_AGENT_IDS, isAgentHardDeprecated, hardDeprecationError } from '../agents.js';
30
- import { isCustomHarnessName, readProfile } from '../profiles.js';
31
- import { findAccount, findUnifiedAccount, listNativeAccounts, resolveAccountSelection, resolveCredentialAccount } from '../account-registry.js';
32
- import { recordRunAuthOutcome } from '../auth-health.js';
33
- /**
34
- * Record a routine run's auth outcome as a per-account FACT (PHNX-4116). A worker
35
- * runs entirely through routines and never probes, so an auth failure here — or a
36
- * clean success that clears a stale failure — is the honest evidence `agents view`
37
- * renders as `last used ok` / `last auth failure`. Best-effort: resolves the slot
38
- * from the routine's account name so the fact lands on the right row, and never
39
- * throws (a run it cannot attribute is simply not recorded).
40
- */
41
- function recordRoutineAuthOutcome(agent, accountName, version, outcome) {
42
- try {
43
- const accountId = accountName
44
- ? listNativeAccounts(readMeta()).find((a) => a.agent === agent && a.name === accountName)?.id ?? null
45
- : null;
46
- recordRunAuthOutcome({ agent, accountId, version: version ?? null, account: accountName, outcome });
47
- }
48
- catch { }
49
- }
50
- export class RoutineAlreadyRunningError extends Error {
51
- constructor(jobName, runId) {
52
- super(`Routine '${jobName}' already has a running execution (${runId})`);
53
- this.name = 'RoutineAlreadyRunningError';
54
- }
55
- }
56
- const ROUTINE_LAUNCH_LOCK_STALE_MS = 30_000;
57
- const ROUTINE_LAUNCH_LOCK_WAIT_MS = 10_000;
58
- // Only a live, within-timeout running record holds the slot; dead/stale running and terminal records release it.
59
- function activeRoutineRun(config) {
60
- const timeoutMs = parseTimeout(config.timeout) || 10 * 60 * 1000;
61
- const now = Date.now();
62
- const runs = listRuns(config.name);
63
- for (let i = runs.length - 1; i >= 0; i--) {
64
- const run = runs[i];
65
- if (run.status !== 'running')
66
- continue;
67
- const startedAt = Date.parse(run.startedAt);
68
- const limit = run.timeoutMs ?? timeoutMs;
69
- if (Number.isFinite(startedAt) && now - startedAt >= limit)
70
- continue;
71
- if (!run.pid)
72
- return run;
73
- if (isPidOurs(run.pid, run.spawnedAt))
74
- return run;
75
- }
76
- return null;
77
- }
78
- export function activeRunSkipStreak(runs) {
79
- let streak = 0;
80
- for (let i = runs.length - 1; i >= 0; i--) {
81
- const run = runs[i];
82
- if (run.status === 'skipped' && run.skipReason === 'active_run') {
83
- streak++;
84
- continue;
85
- }
86
- break;
87
- }
88
- return streak;
89
- }
90
- const SKIP_STREAK_ALERT_THRESHOLD = 3;
91
- // The long-lived daemon never records its own pid as a provisional child claim.
92
- export function launcherClaimPid() {
93
- try {
94
- const daemonPid = parseInt(fs.readFileSync(path.join(getDaemonDir(), 'daemon.pid'), 'utf-8').trim(), 10);
95
- if (Number.isFinite(daemonPid) && daemonPid === process.pid)
96
- return null;
97
- }
98
- catch { }
99
- return process.pid;
100
- }
101
- async function withRoutineLock(config, launch) {
102
- const target = path.join(getJobRunsDir(config.name), '.launch-claim');
103
- ensureLockTarget(target, '', 0o700);
104
- const release = await lockfile.lock(target, {
105
- stale: ROUTINE_LAUNCH_LOCK_STALE_MS,
106
- retries: {
107
- retries: Math.ceil(ROUTINE_LAUNCH_LOCK_WAIT_MS / 100),
108
- factor: 1,
109
- minTimeout: 100,
110
- maxTimeout: 100,
111
- },
112
- onCompromised: logAndContinueOnLockCompromised('routines launch'),
113
- });
114
- try {
115
- return await launch();
116
- }
117
- finally {
118
- await release();
119
- }
120
- }
121
- function assertRunnablePlacement(config) {
122
- const strategy = resolveHostStrategy(config);
123
- if (strategy === 'host' || strategy === 'fleet') {
124
- if (config.workflow)
125
- throw new Error(`Routine '${config.name}' runs a workflow bundle, which can't execute on a host yet — remove 'host:' or 'workflow:'.`);
126
- if (config.loop)
127
- throw new Error(`Routine '${config.name}' uses 'loop:', which can't execute on a host yet — remove 'host:' or 'loop:'.`);
128
- if (config.command)
129
- throw new Error(`Routine '${config.name}' uses 'command:', which can't execute on a host yet — remove 'host:' or 'command:'.`);
130
- }
131
- if (strategy === 'cloud') {
132
- if (config.workflow)
133
- throw new Error(`Routine '${config.name}' runs a workflow bundle, which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'workflow:'.`);
134
- if (config.loop)
135
- throw new Error(`Routine '${config.name}' uses 'loop:', which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'loop:'.`);
136
- if (config.command)
137
- throw new Error(`Routine '${config.name}' uses 'command:', which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'command:'.`);
138
- }
139
- }
140
- function writeTerminalRecord(config, runId, status, trigger, extra) {
141
- fs.mkdirSync(getRunDir(config.name, runId), { recursive: true });
142
- const now = new Date().toISOString();
143
- const scheduledForIso = trigger.scheduledFor
144
- ? (typeof trigger.scheduledFor === 'string' ? trigger.scheduledFor : trigger.scheduledFor.toISOString())
145
- : undefined;
146
- const meta = {
147
- jobName: config.name,
148
- runId,
149
- ...runProvenance(config),
150
- ...(config.workflow ? { workflow: config.workflow } : config.command ? { command: config.command } : config.agent ? { agent: config.agent } : {}),
151
- triggerKind: trigger.kind,
152
- ...(scheduledForIso ? { scheduledFor: scheduledForIso } : {}),
153
- pid: null,
154
- spawnedAt: Date.now(),
155
- status,
156
- startedAt: now,
157
- completedAt: now,
158
- exitCode: null,
159
- duration: 0,
160
- ...extra,
161
- };
162
- writeRunMeta(meta);
163
- return meta;
164
- }
165
- function writeActiveClaim(config, attempt) {
166
- const now = new Date().toISOString();
167
- const meta = {
168
- jobName: config.name,
169
- runId: attempt.runId,
170
- ...runProvenance(config),
171
- ...attempt.stamp,
172
- ...(config.workflow ? { workflow: config.workflow } : config.command ? { command: config.command } : config.agent ? { agent: config.agent } : {}),
173
- pid: launcherClaimPid(),
174
- spawnedAt: Date.now() - process.uptime() * 1000,
175
- status: 'running',
176
- startedAt: now,
177
- completedAt: null,
178
- exitCode: null,
179
- timeoutMs: parseTimeout(config.timeout) || 10 * 60 * 1000,
180
- };
181
- writeRunMeta(meta);
182
- return meta;
183
- }
184
- // Schedule and catchup deliveries atomically claim the same (routine, UTC slot).
185
- function allocateRoutineAttempt(config, trigger) {
186
- const scheduledForIso = trigger.scheduledFor
187
- ? (typeof trigger.scheduledFor === 'string' ? trigger.scheduledFor : trigger.scheduledFor.toISOString())
188
- : undefined;
189
- let runId;
190
- if (scheduledForIso) {
191
- runId = slotRunId(scheduledForIso);
192
- if (!claimRunSlot(config.name, runId)) {
193
- const existing = readRunMeta(config.name, runId);
194
- if (existing)
195
- return { proceed: false, terminal: existing };
196
- return {
197
- proceed: false,
198
- terminal: writeTerminalRecord(config, generateRunId(), 'skipped', trigger, {
199
- skipReason: 'duplicate_slot',
200
- activeRunId: runId,
201
- errorMessage: 'duplicate schedule-slot delivery — the slot is already claimed',
202
- }),
203
- };
204
- }
205
- }
206
- else {
207
- runId = generateRunId();
208
- fs.mkdirSync(getRunDir(config.name, runId), { recursive: true });
209
- }
210
- const active = activeRoutineRun(config);
211
- if (active && active.runId !== runId) {
212
- return {
213
- proceed: false,
214
- terminal: writeTerminalRecord(config, runId, 'skipped', trigger, {
215
- skipReason: 'active_run',
216
- activeRunId: active.runId,
217
- errorMessage: `skipped — '${config.name}' already has an active run (${active.runId})`,
218
- }),
219
- };
220
- }
221
- const eligibility = checkJobDeviceEligibility(config);
222
- if (eligibility) {
223
- return {
224
- proceed: false,
225
- terminal: writeTerminalRecord(config, runId, 'skipped', trigger, {
226
- skipReason: 'wrong_owner',
227
- errorMessage: eligibility.message,
228
- }),
229
- };
230
- }
231
- if (!config.workflow && config.agent && !isCustomHarnessName(config.agent) && isAgentHardDeprecated(config.agent)) {
232
- const reason = hardDeprecationError(config.agent);
233
- return {
234
- proceed: false,
235
- terminal: writeTerminalRecord(config, runId, 'blocked', trigger, {
236
- readiness: { code: 'agent_unavailable', message: reason },
237
- errorMessage: reason,
238
- }),
239
- };
240
- }
241
- try {
242
- assertRunnablePlacement(config);
243
- }
244
- catch (err) {
245
- const message = err.message;
246
- return {
247
- proceed: false,
248
- terminal: writeTerminalRecord(config, runId, 'blocked', trigger, {
249
- readiness: { code: 'placement_unsupported', message },
250
- errorMessage: message,
251
- }),
252
- };
253
- }
254
- const mode = resolveHostStrategy(config);
255
- const ctx = resolveJobExecutionContext(config, {
256
- mode,
257
- probe: mode === 'local' ? undefined : null,
258
- });
259
- const stamp = {
260
- triggerKind: trigger.kind,
261
- ...(scheduledForIso ? { scheduledFor: scheduledForIso } : {}),
262
- ...(config.project ? { project: config.project } : {}),
263
- ...(config.cwd ? { requestedCwd: config.cwd } : {}),
264
- ...(ctx.resolvedCwd ? { resolvedCwd: ctx.resolvedCwd } : {}),
265
- };
266
- if (!ctx.ready) {
267
- return {
268
- proceed: false,
269
- terminal: writeTerminalRecord(config, runId, 'blocked', trigger, {
270
- ...stamp,
271
- readiness: ctx.readiness,
272
- errorMessage: `blocked: ${ctx.readiness?.code ?? 'not_ready'}${ctx.readiness?.message ? ` — ${ctx.readiness.message}` : ''}`,
273
- }),
274
- };
275
- }
276
- return { proceed: true, attempt: { runId, stamp } };
277
- }
278
- function surfaceWedgedRoutine(config, terminal) {
279
- if (terminal.status !== 'skipped' || terminal.skipReason !== 'active_run')
280
- return;
281
- const streak = activeRunSkipStreak(listRuns(config.name));
282
- if (streak !== SKIP_STREAK_ALERT_THRESHOLD)
283
- return;
284
- const stuck = terminal.activeRunId ?? 'unknown';
285
- process.stderr.write(`[agents] routine '${config.name}' skipped ${streak} consecutive scheduled runs — ` +
286
- `its active-run slot is still held by ${stuck}; the routine is not firing on schedule.\n`);
287
- }
288
- async function runWithAttempt(config, trigger, run, wrapTerminal) {
289
- const claimed = await withRoutineLock(config, async () => {
290
- const alloc = allocateRoutineAttempt(config, trigger);
291
- if (!alloc.proceed)
292
- return { terminal: alloc.terminal };
293
- writeActiveClaim(config, alloc.attempt);
294
- return { attempt: alloc.attempt };
295
- });
296
- if ('terminal' in claimed) {
297
- surfaceWedgedRoutine(config, claimed.terminal);
298
- return wrapTerminal(claimed.terminal);
299
- }
300
- try {
301
- return await run(claimed.attempt);
302
- }
303
- catch (err) {
304
- const message = err.message;
305
- const existing = readRunMeta(config.name, claimed.attempt.runId);
306
- if (existing) {
307
- finalizeRunMeta(existing, 'failed', 1, { errorMessage: message });
308
- writeRunMeta(existing);
309
- return wrapTerminal(existing);
310
- }
311
- return wrapTerminal(writeTerminalRecord(config, claimed.attempt.runId, 'blocked', trigger, {
312
- ...claimed.attempt.stamp,
313
- readiness: { code: 'target_unreachable', message },
314
- errorMessage: message,
315
- }));
316
- }
317
- }
318
- // Never signal this process; timeout callbacks own their child, while reconciliation birth-time-verifies recorded pids before calling here.
319
- function terminateRoutineTree(pid) {
320
- if (!pid)
321
- return;
322
- if (pid === process.pid)
323
- return;
324
- if (process.platform === 'win32') {
325
- killTree(pid);
326
- return;
327
- }
328
- try {
329
- process.kill(-pid, 'SIGKILL');
330
- }
331
- catch { }
332
- try {
333
- process.kill(pid, 'SIGKILL');
334
- }
335
- catch { }
336
- }
337
- const ROUTINE_TRANSCRIPT_SPECS = {
338
- claude: [{ root: ['.claude', 'projects'], ext: '.jsonl' }],
339
- codex: [{ root: ['.codex', 'sessions'], ext: '.jsonl' }],
340
- cursor: [{ root: ['.cursor', 'projects'], ext: '.jsonl' }],
341
- antigravity: [{ root: ['.gemini', 'antigravity-cli', 'conversations'], ext: '.db' }],
342
- droid: [{ root: ['.factory', 'sessions'], ext: '.jsonl' }],
343
- kimi: [
344
- { root: ['.kimi-code', 'sessions'], ext: '.json' },
345
- { root: ['.kimi-code', 'sessions'], ext: '.jsonl' },
346
- ],
347
- grok: [{ root: ['.grok', 'sessions'], ext: '.json' }],
348
- muse: [{ root: ['.local', 'share', 'muse', 'sessions'], ext: '.jsonl' }],
349
- };
350
- export function routineSpawnCwd(config) {
351
- const ctx = resolveJobExecutionContext(config, { mode: 'local' });
352
- return ctx.absoluteCwd ?? os.homedir();
353
- }
354
- export function bakeRoutineArgv(agent) {
355
- if (!ROUTINE_AGENT_IDS.includes(agent))
356
- return undefined;
357
- const template = AGENT_COMMANDS[agent];
358
- if (!template)
359
- return undefined;
360
- const json = template.jsonFlags ?? [];
361
- const cmd = [...template.base];
362
- if (agent === 'kimi') {
363
- cmd.push('--prompt', '{prompt}', ...json);
364
- return cmd;
365
- }
366
- if (agent === 'claude') {
367
- const verbose = json.includes('--verbose') ? ['--verbose'] : [];
368
- const jsonRest = json.filter((flag) => flag !== '--verbose');
369
- cmd.push(template.promptFlag, ...verbose, '{prompt}', ...jsonRest, ...(template.modeFlags.plan ?? []));
370
- return cmd;
371
- }
372
- if (template.promptFlag === 'positional') {
373
- cmd.push('{prompt}', ...json);
374
- }
375
- else {
376
- cmd.push(template.promptFlag, '{prompt}', ...json);
377
- }
378
- return cmd;
379
- }
380
- export function buildJobCommand(config, resolvedPrompt, forwardAccount = true) {
381
- if (config.workflow) {
382
- const cmd = ['agents', 'run', config.workflow, resolvedPrompt, '--mode', config.mode];
383
- if (config.account && forwardAccount)
384
- cmd.push('--account', config.account);
385
- return cmd;
386
- }
387
- const agent = config.agent;
388
- if (config.resume) {
389
- const cmd = ['agents', 'run', agent, '--resume', config.resume, resolvedPrompt, '--mode', config.mode];
390
- if (config.account && forwardAccount)
391
- cmd.push('--account', config.account);
392
- return cmd;
393
- }
394
- if (isCustomHarnessName(agent)) {
395
- const cmd = ['agents', 'run', agent, resolvedPrompt, '--mode', config.mode];
396
- if (config.account && forwardAccount)
397
- cmd.push('--account', config.account);
398
- return cmd;
399
- }
400
- if (config.account && forwardAccount && !findAccount(config.account)) {
401
- const spec = config.version
402
- ? `${agent}@${config.version}#${config.account}`
403
- : `${agent}#${config.account}`;
404
- return ['agents', 'run', spec, resolvedPrompt, '--mode', config.mode];
405
- }
406
- const template = bakeRoutineArgv(agent);
407
- if (!template) {
408
- throw new Error(`Unsupported agent for daemon jobs: ${agent}. ` +
409
- `If '${agent}' was a custom harness, its profile no longer exists on this device — ` +
410
- `recreate it (agents harness add ${agent} ...) or point the routine at another agent.`);
411
- }
412
- let cmd = template.map((part) => part.replace('{prompt}', resolvedPrompt));
413
- const mode = normalizeMode(config.mode);
414
- const routineAdapter = resolveHarnessAdapter(agent);
415
- if (routineAdapter.routineModeArgs) {
416
- routineAdapter.routineModeArgs(cmd, { mode, config, resolveHeadlessMode });
417
- appendModelAndReasoning(cmd, config);
418
- }
419
- // A leading dash would turn a YAML directory into an injected harness flag.
420
- if (config.allow?.dirs?.length && agent !== 'codex') {
421
- for (const dir of config.allow.dirs) {
422
- if (dir.startsWith('-')) {
423
- throw new Error(`allow.dirs entries must not start with '-': ${JSON.stringify(dir)}`);
424
- }
425
- }
426
- applyAddDirs(agent, cmd, config.allow.dirs, {
427
- cwd: routineSpawnCwd(config),
428
- });
429
- }
430
- return cmd;
431
- }
432
- function appendModelAndReasoning(cmd, config) {
433
- const agent = config.agent;
434
- const model = config.config?.model;
435
- if (model) {
436
- const modelFlag = AGENT_COMMANDS[agent].modelFlag;
437
- if (!modelFlag) {
438
- throw new Error(`Agent ${agent} does not support routine model selection`);
439
- }
440
- if (config.version) {
441
- const resolved = resolveModel(agent, config.version, model);
442
- if (resolved.warning) {
443
- process.stderr.write(`[agents] ${resolved.warning}\n`);
444
- }
445
- cmd.push(modelFlag, resolved.forwarded);
446
- }
447
- else {
448
- cmd.push(modelFlag, model);
449
- }
450
- }
451
- const reasoning = config.config?.reasoning;
452
- if (reasoning) {
453
- const flags = buildReasoningFlags(agent, reasoning);
454
- if (flags.length > 0)
455
- cmd.push(...flags);
456
- }
457
- }
458
- function generateRunId() {
459
- return new Date().toISOString().replace(/[:.]/g, '-');
460
- }
461
- const CONFIG_DIR_RELOCATED_AGENTS = new Set(['claude', 'codex']);
462
- function usesSharedTranscriptHome(agent, version) {
463
- return Boolean(version) && CONFIG_DIR_RELOCATED_AGENTS.has(agent);
464
- }
465
- function routineTranscriptSourceRoots(agent, version, overlayHome, spec) {
466
- if (usesSharedTranscriptHome(agent, version)) {
467
- const roots = [path.join(getVersionHomePath(agent, version), ...spec.root)];
468
- if (agent === 'codex') {
469
- roots.push(path.join(shortCodexHome(getUserAgentsDir(), version), ...spec.root.slice(1)));
470
- }
471
- return roots;
472
- }
473
- return [path.join(overlayHome, ...spec.root)];
474
- }
475
- function transcriptBasePath(runDir) {
476
- return path.join(runDir, '.transcript-base.json');
477
- }
478
- // Shared version homes contain sibling transcripts, so snapshot before spawn and archive only newly-created files.
479
- export function snapshotRoutineTranscriptBase(meta, runDir, overlayHome) {
480
- if (!meta.agent)
481
- return;
482
- const specs = ROUTINE_TRANSCRIPT_SPECS[meta.agent];
483
- if (!specs)
484
- return;
485
- const home = overlayHome ?? getJobHomePath(meta.jobName);
486
- const preexisting = new Set();
487
- for (const spec of specs) {
488
- for (const root of routineTranscriptSourceRoots(meta.agent, meta.version, home, spec)) {
489
- if (!fs.existsSync(root))
490
- continue;
491
- for (const f of walkForFiles(root, spec.ext, 100_000))
492
- preexisting.add(f);
493
- }
494
- }
495
- try {
496
- fs.mkdirSync(runDir, { recursive: true });
497
- fs.writeFileSync(transcriptBasePath(runDir), JSON.stringify([...preexisting]), { mode: 0o600 });
498
- }
499
- catch {
500
- }
501
- }
502
- function readTranscriptBase(runDir) {
503
- try {
504
- const arr = JSON.parse(fs.readFileSync(transcriptBasePath(runDir), 'utf-8'));
505
- if (Array.isArray(arr))
506
- return new Set(arr.filter((x) => typeof x === 'string'));
507
- }
508
- catch {
509
- }
510
- return null;
511
- }
512
- export function archiveRoutineTranscripts(meta, runDir, overlayHome) {
513
- if (!meta.agent)
514
- return;
515
- const specs = ROUTINE_TRANSCRIPT_SPECS[meta.agent];
516
- if (!specs)
517
- return;
518
- const home = overlayHome ?? getJobHomePath(meta.jobName);
519
- const shared = usesSharedTranscriptHome(meta.agent, meta.version);
520
- const base = readTranscriptBase(runDir);
521
- if (shared && base === null)
522
- return;
523
- for (const spec of specs) {
524
- const destRoot = path.join(runDir, 'sessions', meta.agent, spec.root[spec.root.length - 1]);
525
- for (const sourceRoot of routineTranscriptSourceRoots(meta.agent, meta.version, home, spec)) {
526
- if (!fs.existsSync(sourceRoot))
527
- continue;
528
- for (const sourcePath of walkForFiles(sourceRoot, spec.ext, 100_000)) {
529
- if (base?.has(sourcePath))
530
- continue;
531
- const rel = path.relative(sourceRoot, sourcePath);
532
- if (rel.startsWith('..') || path.isAbsolute(rel))
533
- continue;
534
- const destPath = path.join(destRoot, rel);
535
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
536
- try {
537
- fs.copyFileSync(sourcePath, destPath);
538
- fs.chmodSync(destPath, 0o600);
539
- }
540
- catch {
541
- }
542
- }
543
- }
544
- }
545
- }
546
- function buildShellCommand(command) {
547
- return process.platform === 'win32'
548
- ? ['cmd', '/c', command]
549
- : ['/bin/sh', '-c', command];
550
- }
551
- // Command routines inherit real HOME/base PATH then prepend this CLI's bin; only agent routines receive overlay/version-home isolation.
552
- function commandSpawnEnv(config) {
553
- const env = { ...process.env };
554
- if (config.timezone)
555
- env.TZ = config.timezone;
556
- const sep = process.platform === 'win32' ? ';' : ':';
557
- const binDir = getAgentsBinDir();
558
- const existing = env.PATH ?? '';
559
- if (!existing.split(sep).includes(binDir)) {
560
- env.PATH = existing ? `${binDir}${sep}${existing}` : binDir;
561
- }
562
- return env;
563
- }
564
- function shSingleQuote(s) {
565
- return `'${s.replace(/'/g, `'\\''`)}'`;
566
- }
567
- // Bind bare `agents` inside a command routine to the exact binary running this daemon.
568
- function agentsShellFunction() {
569
- const launch = getCliLaunch(['__ac_placeholder__']);
570
- const parts = [launch.command];
571
- if (launch.args.length > 0 && launch.args[0] !== '__ac_placeholder__' && fs.existsSync(launch.args[0])) {
572
- parts.push(launch.args[0]);
573
- }
574
- const invocation = parts.map(shSingleQuote).join(' ');
575
- return `agents() { ${invocation} "$@"; }`;
576
- }
577
- function wrapCommandRoutine(command) {
578
- if (process.platform === 'win32')
579
- return command;
580
- return `${agentsShellFunction()}\n${command}`;
581
- }
582
- function readCommandExitCode(runDir) {
583
- try {
584
- const raw = fs.readFileSync(path.join(runDir, 'exit-code'), 'utf-8').trim();
585
- if (!/^-?\d+$/.test(raw))
586
- return null;
587
- return parseInt(raw, 10);
588
- }
589
- catch {
590
- return null;
591
- }
592
- }
593
- export function claudeVersionIsAuthenticated(version) {
594
- if (!isVersionInstalled('claude', version))
595
- return true;
596
- const binary = getBinaryPath('claude', version);
597
- if (!binary)
598
- return false;
599
- const env = buildRoutineSpawnEnv(process.env, 'claude', version);
600
- env.HOME = process.env.AGENTS_REAL_HOME || os.homedir();
601
- try {
602
- const raw = execFileSync(binary, ['auth', 'status', '--json'], {
603
- encoding: 'utf8',
604
- timeout: 5_000,
605
- env,
606
- stdio: ['ignore', 'pipe', 'ignore'],
607
- });
608
- return JSON.parse(raw).loggedIn === true;
609
- }
610
- catch {
611
- return false;
612
- }
613
- }
614
- export async function resolveRoutineLaunch(config, cwd = process.cwd(), deps = {}) {
615
- if (config.workflow) {
616
- return { chain: [], rotation: null, pinned: false };
617
- }
618
- if (config.agent && isCustomHarnessName(config.agent)) {
619
- return { chain: [], rotation: null, pinned: false };
620
- }
621
- const agent = config.agent;
622
- const { findAccount, findUnifiedAccount, resolveAccountSelection, resolveCredentialAccount } = await import('../account-registry.js');
623
- const meta = (deps.readMeta ?? readMeta)();
624
- const explicitCredential = config.account
625
- ? (deps.findCredentialAccount?.(config.account) ?? (deps.resolveCredentialAccount !== undefined || findAccount(config.account) !== null))
626
- : false;
627
- const selectedCredential = config.account
628
- ? (explicitCredential ? config.account : undefined)
629
- : resolveAccountSelection(undefined, agent, meta)?.id;
630
- if (selectedCredential) {
631
- const unified = findUnifiedAccount(selectedCredential, meta);
632
- if (unified?.kind !== 'native')
633
- (deps.resolveCredentialAccount ?? resolveCredentialAccount)(selectedCredential, agent);
634
- }
635
- if (config.account && !explicitCredential) {
636
- const unified = findUnifiedAccount(config.account, meta, undefined, agent);
637
- if (unified?.kind === 'native' && unified.agent !== agent) {
638
- throw new Error(`Routine '${config.name}' account '${config.account}' is a ${unified.agent} login and cannot authenticate ${agent}.`);
639
- }
640
- const identity = unified?.kind === 'native' ? unified.identityKey : config.account;
641
- const accountVersion = deps.resolveAccountVersion
642
- ? await deps.resolveAccountVersion(agent, identity)
643
- : (await (deps.resolveAccountCandidate ?? resolveAccountCandidate)(agent, identity))?.version ?? null;
644
- if (accountVersion) {
645
- if (config.version && config.version !== accountVersion) {
646
- throw new Error(`Routine '${config.name}' account '${config.account}' is signed in at ${agent}@${accountVersion}, not pinned ${agent}@${config.version}.`);
647
- }
648
- return {
649
- chain: [{ agent, version: config.version ?? accountVersion }],
650
- rotation: null,
651
- pinned: true,
652
- forwardAccount: true,
653
- };
654
- }
655
- throw new Error(`Routine '${config.name}' account '${config.account}' is not signed in for ${agent}; refusing to rotate to another account.`);
656
- }
657
- if (config.version) {
658
- const version = config.version;
659
- if (!isVersionInstalled(agent, version)) {
660
- process.stderr.write(`[agents] routine ${config.name}: pinned ${agent}@${version} is not installed\n`);
661
- }
662
- return {
663
- chain: [{ agent, version }],
664
- rotation: null,
665
- pinned: true,
666
- ...(config.account ? { forwardAccount: explicitCredential } : {}),
667
- };
668
- }
669
- const strategy = config.strategy ?? getConfiguredRunStrategy(agent, cwd);
670
- let version;
671
- let rotation = null;
672
- let exhausted;
673
- let noVerifiedUsage = false;
674
- try {
675
- const resolved = await (deps.resolveRunVersion ?? resolveRunVersion)(agent, strategy, cwd);
676
- version = resolved.version ?? undefined;
677
- rotation = resolved.rotation;
678
- exhausted = resolved.exhausted;
679
- noVerifiedUsage = resolved.noVerifiedUsage ?? false;
680
- if (noVerifiedUsage) {
681
- process.stderr.write(`[agents] routine ${config.name}: ${strategy} found no ${agent} account with fresh usage — refusing to route on stale data\n`);
682
- }
683
- else if (rotation) {
684
- const label = rotation.picked.email
685
- ? `${rotation.picked.email} · ${agent}@${rotation.picked.version}`
686
- : `${agent}@${rotation.picked.version}`;
687
- const ratio = `${rotation.healthy.length} of ${rotation.healthy.length + rotation.excluded.length} healthy`;
688
- process.stderr.write(`[agents] routine ${config.name}: ${strategy} picked ${label} (${ratio})\n`);
689
- if (rotation.excluded.length > 0) {
690
- const reasons = rotation.excluded
691
- .map((c) => {
692
- const r = readinessFromCandidate(c);
693
- const why = r.ready ? 'deduped' : r.reason;
694
- return `${c.agent}@${c.version}=${why}`;
695
- })
696
- .join(', ');
697
- process.stderr.write(`[agents] routine ${config.name}: skipped ${reasons}\n`);
698
- }
699
- }
700
- else if (!version && !exhausted) {
701
- process.stderr.write(`[agents] routine ${config.name}: strategy ${strategy} found no usable ${agent} version; ` +
702
- `falling back to default pin\n`);
703
- }
704
- }
705
- catch (err) {
706
- process.stderr.write(`[agents] routine ${config.name}: strategy ${strategy} skipped: ${err.message}\n`);
707
- }
708
- if (exhausted) {
709
- throw new Error(formatNoHealthyAccountError(agent, strategy, exhausted));
710
- }
711
- if (noVerifiedUsage) {
712
- throw new Error(formatNoVerifiedUsageError(agent, strategy, rotation?.healthy ?? []));
713
- }
714
- if (!version) {
715
- version = resolveVersion(agent, cwd) ?? undefined;
716
- }
717
- if (agent === 'claude' && version) {
718
- const checkClaudeAuth = deps.claudeVersionIsAuthenticated ?? claudeVersionIsAuthenticated;
719
- const authenticatedHealthy = rotation?.healthy.filter((candidate) => checkClaudeAuth(candidate.version));
720
- const authenticated = authenticatedHealthy?.find((candidate) => candidate.version === version) ?? authenticatedHealthy?.[0];
721
- if (rotation && (!authenticated || authenticatedHealthy.length === 0)) {
722
- throw new Error(`Routine '${config.name}' found no authenticated Claude account; run \`claude /login\` for an installed version or pin a provider profile.`);
723
- }
724
- if (!rotation && !checkClaudeAuth(version)) {
725
- throw new Error(`Routine '${config.name}' found no authenticated Claude account at claude@${version}; run \`claude /login\` for that version or remove the pin.`);
726
- }
727
- if (rotation && authenticated) {
728
- const rejected = rotation.healthy.filter((candidate) => !authenticatedHealthy.includes(candidate));
729
- if (rejected.length > 0 || rotation.picked !== authenticated) {
730
- rotation = { ...rotation, picked: authenticated, healthy: authenticatedHealthy, excluded: [...rotation.excluded, ...rejected] };
731
- }
732
- version = authenticated.version;
733
- }
734
- }
735
- if (!version) {
736
- process.stderr.write(`[agents] routine ${config.name}: no version of ${agent} configured — ` +
737
- `run: agents add ${agent}@<version> && agents use ${agent} <version>\n`);
738
- return { chain: [{ agent }], rotation: null, pinned: false };
739
- }
740
- const failover = rotationFailoverChain(rotation, version);
741
- if (failover.length > 0) {
742
- const labels = failover.map((f) => `${f.agent}@${f.version}`).join(', ');
743
- process.stderr.write(`[agents] routine ${config.name}: credit/rate-limit failover armed → ${labels}\n`);
744
- }
745
- return {
746
- chain: [{ agent, version }, ...failover],
747
- rotation,
748
- pinned: false,
749
- };
750
- }
751
- export function pinJobBinary(cmd, agent, version) {
752
- if (!version || cmd.length === 0)
753
- return cmd;
754
- if (!isVersionInstalled(agent, version))
755
- return cmd;
756
- const binary = getBinaryPath(agent, version);
757
- if (!binary || !fs.existsSync(binary))
758
- return cmd;
759
- const next = [...cmd];
760
- next[0] = binary;
761
- return next;
762
- }
763
- export async function assertRoutineAccountLocalForPlacement(config, mode, deps = {}) {
764
- if (!config.account)
765
- return;
766
- let account = deps.account;
767
- if (account === undefined) {
768
- const { findUnifiedAccount } = await import('../account-registry.js');
769
- account = findUnifiedAccount(config.account, (deps.readMeta ?? readMeta)());
770
- }
771
- if (!account) {
772
- throw new Error(`Routine '${config.name}' account '${config.account}' is unknown.`);
773
- }
774
- if (account?.kind === 'native') {
775
- throw new Error(`Routine '${config.name}' account '${config.account}' is a device-local ${account.agent} login and cannot run on a ${mode} placement. Use a provider account, or place this routine on the device that holds the login.`);
776
- }
777
- if (mode === 'cloud' && account?.kind === 'provider') {
778
- throw new Error(`Routine '${config.name}' account '${config.account}' is a provider credential; cloud placement cannot securely inject it (RUSH-2689). Run this routine locally or on a host that holds the bundle.`);
779
- }
780
- }
781
- export async function dispatchPlacedJob(config, target, attempt, deps = {}) {
782
- if (target.mode !== 'host' && target.mode !== 'cloud')
783
- return undefined;
784
- await assertRoutineAccountLocalForPlacement(config, target.mode, { account: deps.account });
785
- if (target.mode === 'host') {
786
- return (deps.host ?? executeJobOnHost)({ ...config, host: target.host }, { detached: false }, attempt);
787
- }
788
- return (deps.cloud ?? executeJobOnCloud)(config, { detached: false }, attempt);
789
- }
790
- export function buildHostDispatchOptions(config, ctx) {
791
- return {
792
- agent: config.agent,
793
- prompt: resolveJobPrompt(config),
794
- mode: normalizeMode(config.mode),
795
- effort: config.effort,
796
- model: config.config?.model,
797
- account: config.account,
798
- timeout: config.timeout,
799
- remoteCwd: ctx.remoteCwd,
800
- name: config.name,
801
- cwd: ctx.runDir,
802
- follow: !ctx.detached,
803
- };
804
- }
805
- export function dispatchesViaAgentsRun(config) {
806
- return Boolean(config.workflow
807
- || config.resume
808
- || (config.agent && isCustomHarnessName(config.agent))
809
- || (config.account && config.agent && !findAccount(config.account)));
810
- }
811
- /**
812
- * Inject a provider account's env into a routine spawn. Native accounts do not
813
- * belong here — they re-enter `agents run <agent>#<name>` so T5 slot resolution
814
- * picks the HOME. A provider-pinned routine stays on this path so the durable
815
- * credential is still in the child env (PHNX-3940 T5 seam / T7).
816
- */
817
- export function mergeRoutineProviderEnv(env, config, agent) {
818
- if (dispatchesViaAgentsRun({ ...config, agent }))
819
- return env;
820
- const meta = readMeta();
821
- const selected = resolveAccountSelection(config.account, agent, meta);
822
- if (!selected)
823
- return env;
824
- const unified = findUnifiedAccount(selected.id, meta, undefined, agent);
825
- if (unified?.kind !== 'provider')
826
- return env;
827
- Object.assign(env, resolveCredentialAccount(unified.name, agent).env);
828
- return env;
829
- }
830
- export function buildRoutineSpawnEnv(baseEnv, agent, version, timezone, overlayHome) {
831
- const execEnv = buildExecEnv({
832
- agent,
833
- version,
834
- mode: 'plan',
835
- effort: 'auto',
836
- headless: true,
837
- env: baseEnv,
838
- });
839
- const out = {};
840
- for (const [k, v] of Object.entries(execEnv)) {
841
- if (v !== undefined)
842
- out[k] = v;
843
- }
844
- const setupToken = agent === 'claude' && version
845
- ? resolveClaudeSetupToken(getVersionHomePath('claude', version))
846
- : null;
847
- if (isHeadedDeviceRole(selfConfiguredDeviceRole())) {
848
- if (setupToken && out.CLAUDE_CODE_OAUTH_TOKEN === setupToken)
849
- delete out.CLAUDE_CODE_OAUTH_TOKEN;
850
- }
851
- else if (setupToken) {
852
- out.CLAUDE_CODE_OAUTH_TOKEN = setupToken;
853
- }
854
- else {
855
- delete out.CLAUDE_CODE_OAUTH_TOKEN;
856
- }
857
- if (agent === 'cursor' && overlayHome) {
858
- out.XDG_CONFIG_HOME = path.join(overlayHome, '.config');
859
- }
860
- if (overlayHome && agent === 'claude')
861
- out.HOME = process.env.AGENTS_REAL_HOME || os.homedir();
862
- if (overlayHome && agent === 'codex')
863
- out.CODEX_HOME = path.join(overlayHome, '.codex');
864
- if (timezone)
865
- out.TZ = timezone;
866
- return out;
867
- }
868
- function spawnJobAttempt(cmd, env, attemptLogPath, timeoutMs, combinedLogPath, cwd = os.homedir()) {
869
- fs.writeFileSync(attemptLogPath, '', { mode: 0o600 });
870
- const stdoutFd = fs.openSync(attemptLogPath, 'a', 0o600);
871
- return new Promise((resolve) => {
872
- const child = spawn(cmd[0], cmd.slice(1), {
873
- stdio: ['ignore', stdoutFd, stdoutFd],
874
- ...backgroundSpawnOptions({ cwd, fdStdio: true }),
875
- env,
876
- });
877
- let settled = false;
878
- const finish = (result) => {
879
- if (settled)
880
- return;
881
- settled = true;
882
- try {
883
- fs.closeSync(stdoutFd);
884
- }
885
- catch { }
886
- let logText = '';
887
- try {
888
- logText = fs.readFileSync(attemptLogPath, 'utf-8');
889
- }
890
- catch { }
891
- if (combinedLogPath) {
892
- try {
893
- fs.appendFileSync(combinedLogPath, logText);
894
- }
895
- catch { }
896
- }
897
- resolve({ ...result, logText });
898
- };
899
- const timeoutTimer = setTimeout(() => {
900
- try {
901
- if (child.pid)
902
- process.kill(-child.pid, 'SIGTERM');
903
- }
904
- catch { }
905
- setTimeout(() => {
906
- try {
907
- if (child.pid)
908
- process.kill(-child.pid, 'SIGKILL');
909
- }
910
- catch { }
911
- }, 5000);
912
- finish({
913
- exitCode: null,
914
- status: 'timeout',
915
- pid: child.pid || null,
916
- logText: '',
917
- });
918
- }, timeoutMs);
919
- child.on('exit', (code) => {
920
- clearTimeout(timeoutTimer);
921
- finish({
922
- exitCode: code,
923
- status: code === 0 ? 'completed' : 'failed',
924
- pid: child.pid || null,
925
- logText: '',
926
- });
927
- });
928
- child.on('error', (err) => {
929
- clearTimeout(timeoutTimer);
930
- finish({
931
- exitCode: 1,
932
- status: 'failed',
933
- error: err.message,
934
- pid: child.pid || null,
935
- logText: '',
936
- });
937
- });
938
- child.unref();
939
- });
940
- }
941
- function runProvenance(config) {
942
- return { ...(config.actor ? { actor: config.actor } : {}), triggeredBy: resolveActor().id };
943
- }
944
- function injectRoutineActor(env, config) {
945
- if (config.actor && !env.AGENTS_ACTOR)
946
- env.AGENTS_ACTOR = config.actor;
947
- return env;
948
- }
949
- export async function executeJob(config, deps, trigger = { kind: 'manual' }) {
950
- return runWithAttempt(config, trigger, (attempt) => executeJobPlaced(config, deps, attempt), (meta) => ({ meta, reportPath: null }));
951
- }
952
- async function executeJobPlaced(config, deps, attempt) {
953
- {
954
- const { resolvePlacementTarget } = await import('../routines-placement.js');
955
- const target = await resolvePlacementTarget(config);
956
- const placed = await dispatchPlacedJob(config, target, attempt);
957
- if (placed)
958
- return placed;
959
- }
960
- if (config.command) {
961
- return executeCommandJobForeground(config, attempt);
962
- }
963
- const launch = await resolveRoutineLaunch(config);
964
- const primaryVersion = launch.chain[0]?.version ?? config.version;
965
- const timer = createTimer('agent.run', {
966
- agent: config.agent,
967
- version: primaryVersion,
968
- jobName: config.name,
969
- mode: config.mode,
970
- ...redactPrompt(config.prompt),
971
- schedule: config.schedule,
972
- });
973
- const resolvedPrompt = resolveJobPrompt(config);
974
- const useSandbox = config.sandbox !== false && !config.resume && !(config.agent && isCustomHarnessName(config.agent));
975
- const overlayHome = useSandbox ? prepareJobHome(config, primaryVersion) : undefined;
976
- const runId = attempt.runId;
977
- const runDir = getRunDir(config.name, runId);
978
- fs.mkdirSync(runDir, { recursive: true });
979
- const baseEnv = injectRoutineActor(useSandbox
980
- ? buildSpawnEnv(overlayHome, config.env)
981
- : { ...process.env }, config);
982
- const harnessName = !config.workflow && config.agent && isCustomHarnessName(config.agent)
983
- ? config.agent
984
- : undefined;
985
- const effectiveAgent = config.workflow
986
- ? 'claude'
987
- : harnessName
988
- ? readProfile(harnessName).host.agent
989
- : config.agent;
990
- mergeRoutineProviderEnv(baseEnv, config, effectiveAgent);
991
- // RUSH-2860: if this host holds gh auth, the sandbox child MUST see it.
992
- if (useSandbox)
993
- assertSandboxForwardsHostGhAuth(baseEnv);
994
- const meta = {
995
- jobName: config.name,
996
- runId,
997
- ...runProvenance(config),
998
- ...attempt.stamp,
999
- agent: effectiveAgent,
1000
- version: primaryVersion,
1001
- ...(config.workflow ? { workflow: config.workflow } : {}),
1002
- pid: null,
1003
- spawnedAt: Date.now(),
1004
- status: 'running',
1005
- startedAt: new Date().toISOString(),
1006
- completedAt: null,
1007
- exitCode: null,
1008
- };
1009
- writeRunMeta(meta);
1010
- snapshotRoutineTranscriptBase(meta, runDir, overlayHome);
1011
- const preflightVersion = launch.chain[0]?.version;
1012
- const { fireTimeAuthReadiness } = await import('../routine-readiness.js');
1013
- const authBlocker = preflightVersion ? fireTimeAuthReadiness(effectiveAgent, preflightVersion) : null;
1014
- if (authBlocker) {
1015
- process.stderr.write(`[agents] routine ${config.name}: ${effectiveAgent}@${preflightVersion} ${authBlocker.code} — skipping run (${authBlocker.repair})\n`);
1016
- meta.readiness = authBlocker;
1017
- finalizeRunMeta(meta, 'blocked', null, { errorMessage: `blocked: ${authBlocker.code} — ${authBlocker.message}` });
1018
- writeRunMeta(meta);
1019
- timer.end({ status: 'blocked', runId, error: authBlocker.code });
1020
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1021
- return { meta, reportPath: null };
1022
- }
1023
- const timeoutMs = parseTimeout(config.timeout) || 10 * 60 * 1000;
1024
- if (config.loop) {
1025
- const spawnEnv = buildRoutineSpawnEnv(baseEnv, effectiveAgent, primaryVersion, config.timezone, overlayHome);
1026
- const execOptions = {
1027
- agent: effectiveAgent,
1028
- harnessName,
1029
- version: isSelfUpdatingAgent(effectiveAgent) ? undefined : primaryVersion,
1030
- prompt: resolvedPrompt,
1031
- mode: normalizeMode(config.mode),
1032
- effort: config.effort,
1033
- env: spawnEnv,
1034
- json: true,
1035
- headless: true,
1036
- modeWarningContext: `routine ${config.name}`,
1037
- modeWarningState: {},
1038
- ...(config.config?.model ? { model: config.config.model } : {}),
1039
- ...(config.allow?.dirs ? {
1040
- addDirs: config.allow.dirs
1041
- .filter((d) => !d.startsWith('-'))
1042
- .map((d) => d.replace(/^~/, os.homedir())),
1043
- } : {}),
1044
- };
1045
- const { runLoop } = await import('../loop.js');
1046
- const loopResult = await runLoop(execOptions, config.loop, {
1047
- runId,
1048
- runDir,
1049
- agent: effectiveAgent,
1050
- version: primaryVersion,
1051
- }, deps);
1052
- const loopFailed = loopResult.stoppedBy === 'error';
1053
- finalizeRunMeta(meta, loopFailed ? 'failed' : 'completed', loopFailed ? 1 : 0, loopFailed ? { errorMessage: `loop stopped: ${loopResult.stoppedBy}` } : undefined);
1054
- writeRunMeta(meta);
1055
- timer.end({ status: meta.status, exitCode: meta.exitCode ?? undefined, runId });
1056
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1057
- return { meta, reportPath: null };
1058
- }
1059
- const baseCmd = buildJobCommand(config, resolvedPrompt, launch.forwardAccount !== false);
1060
- const stdoutPath = path.join(runDir, 'stdout.log');
1061
- fs.writeFileSync(stdoutPath, '', { mode: 0o600 });
1062
- const chain = launch.chain.length > 0
1063
- ? launch.chain
1064
- : [{ agent: effectiveAgent, version: primaryVersion }];
1065
- timer.mark('startup');
1066
- for (let i = 0; i < chain.length; i++) {
1067
- const entry = chain[i];
1068
- const attemptAgent = entry.agent;
1069
- const attemptVersion = entry.version;
1070
- const label = attemptVersion ? `${attemptAgent}@${attemptVersion}` : attemptAgent;
1071
- if (i === 0) {
1072
- process.stderr.write(`[agents] routine ${config.name}: running ${label}\n`);
1073
- }
1074
- meta.version = attemptVersion;
1075
- snapshotRoutineTranscriptBase(meta, runDir, overlayHome);
1076
- const viaAgentsRun = dispatchesViaAgentsRun(config);
1077
- if (overlayHome)
1078
- linkVersionAuth(overlayHome, attemptAgent, attemptVersion);
1079
- const cmd = viaAgentsRun
1080
- ? baseCmd
1081
- : pinJobBinary(baseCmd, attemptAgent, attemptVersion);
1082
- const spawnEnv = viaAgentsRun
1083
- ? (() => {
1084
- const e = { ...baseEnv };
1085
- if (config.timezone)
1086
- e.TZ = config.timezone;
1087
- return e;
1088
- })()
1089
- : buildRoutineSpawnEnv(baseEnv, attemptAgent, attemptVersion, config.timezone, overlayHome);
1090
- const elapsed = Date.now() - Date.parse(meta.startedAt);
1091
- const remaining = Math.max(1_000, timeoutMs - (Number.isFinite(elapsed) ? elapsed : 0));
1092
- const attemptLogPath = path.join(runDir, `stdout.attempt-${i}.log`);
1093
- const attempt = await spawnJobAttempt(cmd, spawnEnv, attemptLogPath, remaining, stdoutPath, routineSpawnCwd(config));
1094
- meta.pid = attempt.pid;
1095
- writeRunMeta(meta);
1096
- if (attempt.status === 'timeout') {
1097
- finalizeRunMeta(meta, 'timeout', null, { errorMessage: 'run timed out' });
1098
- writeRunMeta(meta);
1099
- timer.end({ status: 'timeout', runId });
1100
- const reportPath = extractAndSaveReport(stdoutPath, effectiveAgent, runDir);
1101
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1102
- return { meta, reportPath };
1103
- }
1104
- if (attempt.status === 'completed') {
1105
- if (isAuthFailureFromLog(attempt.logText, effectiveAgent, { processFailed: false })) {
1106
- const reason = authFailureReason(attempt.logText) ?? 'authentication_failed';
1107
- recordRoutineAuthOutcome(attemptAgent, config.account, attemptVersion, { ok: false, verdict: 'revoked', detail: reason });
1108
- finalizeRunMeta(meta, 'failed', attempt.exitCode ?? 1, { errorMessage: `auth_failed: ${reason}` });
1109
- writeRunMeta(meta);
1110
- timer.end({ status: 'failed', exitCode: meta.exitCode ?? undefined, runId, error: `auth_failed: ${reason}` });
1111
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1112
- return { meta, reportPath: null };
1113
- }
1114
- recordRoutineAuthOutcome(attemptAgent, config.account, attemptVersion, { ok: true });
1115
- finalizeRunMeta(meta, 'completed', 0);
1116
- writeRunMeta(meta);
1117
- timer.end({ status: 'completed', exitCode: 0, runId });
1118
- const reportPath = extractAndSaveReport(stdoutPath, effectiveAgent, runDir);
1119
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1120
- return { meta, reportPath };
1121
- }
1122
- const isLast = i === chain.length - 1;
1123
- const rateLimited = detectRateLimit(attempt.logText) || (attempt.error ? detectRateLimit(attempt.error) : false);
1124
- if (!isLast && rateLimited) {
1125
- const next = chain[i + 1];
1126
- const nextLabel = next.version ? `${next.agent}@${next.version}` : next.agent;
1127
- process.stderr.write(`[agents] routine ${config.name}: ${label} failed with credit/rate limit, trying ${nextLabel}\n`);
1128
- fs.appendFileSync(stdoutPath, `\n[agents] ${label} hit rate/usage limit — failover → ${nextLabel}\n`);
1129
- continue;
1130
- }
1131
- const authFailed = !rateLimited && (isAuthFailureFromLog(attempt.logText, effectiveAgent, { processFailed: true }) ||
1132
- (attempt.error ? detectAuthFailure(attempt.error) : false));
1133
- if (attempt.error) {
1134
- process.stderr.write(`[agents] routine ${config.name}: spawn failed for ${label}: ${attempt.error}\n`);
1135
- }
1136
- const authReason = authFailed
1137
- ? (authFailureReason(attempt.logText)
1138
- ?? (attempt.error ? authFailureReason(attempt.error) : null)
1139
- ?? 'authentication_failed')
1140
- : null;
1141
- const failureErrorMessage = authReason
1142
- ? `auth_failed: ${authReason}`
1143
- : (attempt.error ?? undefined);
1144
- if (authFailed)
1145
- recordRoutineAuthOutcome(attemptAgent, config.account, attemptVersion, { ok: false, verdict: 'revoked', detail: authReason ?? undefined });
1146
- finalizeRunMeta(meta, 'failed', attempt.exitCode ?? 1, failureErrorMessage ? { errorMessage: failureErrorMessage } : undefined);
1147
- writeRunMeta(meta);
1148
- timer.end({
1149
- status: 'failed',
1150
- exitCode: meta.exitCode ?? undefined,
1151
- runId,
1152
- ...(failureErrorMessage ? { error: failureErrorMessage } : {}),
1153
- });
1154
- const reportPath = authFailed ? null : extractAndSaveReport(stdoutPath, effectiveAgent, runDir);
1155
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1156
- return { meta, reportPath };
1157
- }
1158
- finalizeRunMeta(meta, 'failed', 1);
1159
- writeRunMeta(meta);
1160
- timer.end({ status: 'failed', exitCode: 1, runId });
1161
- return { meta, reportPath: null };
1162
- }
1163
- async function executeJobOnCloud(config, opts, attempt) {
1164
- if (config.workflow) {
1165
- throw new Error(`Routine '${config.name}' runs a workflow bundle, which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'workflow:'.`);
1166
- }
1167
- if (config.loop) {
1168
- throw new Error(`Routine '${config.name}' uses 'loop:', which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'loop:'.`);
1169
- }
1170
- if (config.command) {
1171
- throw new Error(`Routine '${config.name}' uses 'command:', which can't execute in the cloud yet — remove 'hostStrategy: cloud' or 'command:'.`);
1172
- }
1173
- if (!config.agent) {
1174
- throw new Error(`Routine '${config.name}' hostStrategy: cloud requires an agent`);
1175
- }
1176
- const { resolveProvider } = await import('../cloud/registry.js');
1177
- const { insertTask } = await import('../cloud/store.js');
1178
- const provider = resolveProvider(undefined, config.agent);
1179
- const timer = createTimer('agent.run', {
1180
- agent: config.agent,
1181
- jobName: config.name,
1182
- mode: config.mode,
1183
- placement: 'cloud',
1184
- ...redactPrompt(config.prompt),
1185
- schedule: config.schedule,
1186
- });
1187
- const runId = attempt.runId;
1188
- const runDir = getRunDir(config.name, runId);
1189
- fs.mkdirSync(runDir, { recursive: true });
1190
- const meta = {
1191
- jobName: config.name,
1192
- runId,
1193
- ...runProvenance(config),
1194
- ...attempt.stamp,
1195
- agent: config.agent,
1196
- pid: null,
1197
- spawnedAt: Date.now(),
1198
- status: 'running',
1199
- startedAt: new Date().toISOString(),
1200
- completedAt: null,
1201
- exitCode: null,
1202
- };
1203
- writeRunMeta(meta);
1204
- try {
1205
- const task = await provider.dispatch({
1206
- prompt: resolveJobPrompt(config),
1207
- agent: config.agent,
1208
- repo: config.repo,
1209
- timeout: config.timeout,
1210
- model: config.config?.model,
1211
- });
1212
- try {
1213
- insertTask(task);
1214
- }
1215
- catch { }
1216
- meta.cloudTaskId = task.id;
1217
- meta.cloudProvider = task.provider;
1218
- if (task.status === 'completed') {
1219
- finalizeRunMeta(meta, 'completed', 0);
1220
- }
1221
- else if (task.status === 'failed' || task.status === 'cancelled') {
1222
- finalizeRunMeta(meta, 'failed', 1, { errorMessage: task.summary ?? `cloud ${task.status}` });
1223
- }
1224
- writeRunMeta(meta);
1225
- timer.end({ status: meta.status, exitCode: meta.exitCode ?? undefined, runId });
1226
- return { meta, reportPath: null };
1227
- }
1228
- catch (err) {
1229
- finalizeRunMeta(meta, 'failed', 1, { errorMessage: err.message });
1230
- writeRunMeta(meta);
1231
- timer.end({ status: 'failed', exitCode: 1, runId, error: err.message });
1232
- throw err;
1233
- }
1234
- }
1235
- async function executeJobOnHost(config, opts, attempt) {
1236
- if (config.workflow) {
1237
- throw new Error(`Routine '${config.name}' runs a workflow bundle, which can't execute on a host yet — remove 'host:' or 'workflow:'.`);
1238
- }
1239
- if (config.loop) {
1240
- throw new Error(`Routine '${config.name}' uses 'loop:', which can't execute on a host yet — remove 'host:' or 'loop:'.`);
1241
- }
1242
- if (config.command) {
1243
- throw new Error(`Routine '${config.name}' uses 'command:', which can't execute on a host yet — remove 'host:' or 'command:'.`);
1244
- }
1245
- const { resolveHostRunTarget, dispatchPromptToHost } = await import('../hosts/run-target.js');
1246
- const host = await resolveHostRunTarget(config.host);
1247
- const { evaluateHostActivationReadiness } = await import('../routine-readiness.js');
1248
- const readiness = await evaluateHostActivationReadiness(config);
1249
- if (!readiness.ready)
1250
- throw new Error(`${readiness.readiness?.code ?? 'not_ready'}: ${readiness.readiness?.message ?? 'target is not ready'}`);
1251
- const remoteCwd = readiness.context.resolvedCwd;
1252
- const timer = createTimer('agent.run', {
1253
- agent: config.agent,
1254
- jobName: config.name,
1255
- mode: config.mode,
1256
- host: host.name,
1257
- ...redactPrompt(config.prompt),
1258
- schedule: config.schedule,
1259
- });
1260
- const runId = attempt.runId;
1261
- const runDir = getRunDir(config.name, runId);
1262
- fs.mkdirSync(runDir, { recursive: true });
1263
- const meta = {
1264
- jobName: config.name,
1265
- runId,
1266
- ...runProvenance(config),
1267
- ...attempt.stamp,
1268
- agent: config.agent,
1269
- pid: null,
1270
- spawnedAt: Date.now(),
1271
- status: 'running',
1272
- startedAt: new Date().toISOString(),
1273
- completedAt: null,
1274
- exitCode: null,
1275
- host: host.name,
1276
- };
1277
- writeRunMeta(meta);
1278
- const { task, exitCode } = await dispatchPromptToHost(host, buildHostDispatchOptions(config, { remoteCwd, runDir, detached: opts.detached }));
1279
- meta.hostTaskId = task.id;
1280
- if (!opts.detached && exitCode !== null && exitCode !== undefined && exitCode !== -1) {
1281
- finalizeRunMeta(meta, exitCode === 0 ? 'completed' : 'failed', exitCode);
1282
- }
1283
- writeRunMeta(meta);
1284
- timer.end({ status: meta.status, exitCode: meta.exitCode ?? undefined, runId });
1285
- return { meta, reportPath: null };
1286
- }
1287
- async function executeCommandJobForeground(config, attempt) {
1288
- const timer = createTimer('agent.run', {
1289
- jobName: config.name,
1290
- mode: config.mode,
1291
- schedule: config.schedule,
1292
- });
1293
- const runId = attempt.runId;
1294
- const runDir = getRunDir(config.name, runId);
1295
- fs.mkdirSync(runDir, { recursive: true });
1296
- const stdoutPath = path.join(runDir, 'stdout.log');
1297
- const stdoutFd = fs.openSync(stdoutPath, 'w', 0o600);
1298
- const meta = {
1299
- jobName: config.name,
1300
- runId,
1301
- ...runProvenance(config),
1302
- ...attempt.stamp,
1303
- command: config.command,
1304
- pid: null,
1305
- spawnedAt: Date.now(),
1306
- status: 'running',
1307
- startedAt: new Date().toISOString(),
1308
- completedAt: null,
1309
- exitCode: null,
1310
- };
1311
- writeRunMeta(meta);
1312
- const timeoutMs = parseTimeout(config.timeout) || 10 * 60 * 1000;
1313
- const cmd = buildShellCommand(wrapCommandRoutine(config.command));
1314
- const env = commandSpawnEnv(config);
1315
- process.stderr.write(`[agents] routine ${config.name}: running command\n`);
1316
- const result = await new Promise((resolve) => {
1317
- const child = spawn(cmd[0], cmd.slice(1), {
1318
- stdio: ['ignore', stdoutFd, stdoutFd],
1319
- ...backgroundSpawnOptions({ cwd: routineSpawnCwd(config), fdStdio: true }),
1320
- env,
1321
- });
1322
- meta.pid = child.pid || null;
1323
- writeRunMeta(meta);
1324
- let settled = false;
1325
- const finish = (r) => {
1326
- if (settled)
1327
- return;
1328
- settled = true;
1329
- try {
1330
- fs.closeSync(stdoutFd);
1331
- }
1332
- catch { }
1333
- resolve(r);
1334
- };
1335
- const timeoutTimer = setTimeout(() => {
1336
- try {
1337
- if (child.pid)
1338
- process.kill(-child.pid, 'SIGTERM');
1339
- }
1340
- catch { }
1341
- setTimeout(() => {
1342
- try {
1343
- if (child.pid)
1344
- process.kill(-child.pid, 'SIGKILL');
1345
- }
1346
- catch { }
1347
- }, 5000);
1348
- finish({ exitCode: null, status: 'timeout' });
1349
- }, timeoutMs);
1350
- child.on('exit', (code) => {
1351
- clearTimeout(timeoutTimer);
1352
- finish({ exitCode: code, status: code === 0 ? 'completed' : 'failed' });
1353
- });
1354
- child.on('error', (err) => {
1355
- clearTimeout(timeoutTimer);
1356
- finish({ exitCode: 1, status: 'failed', error: err.message });
1357
- });
1358
- });
1359
- finalizeRunMeta(meta, result.status, result.exitCode ?? (result.status === 'completed' ? 0 : 1), result.error ? { errorMessage: result.error } : undefined);
1360
- writeRunMeta(meta);
1361
- if (result.error) {
1362
- process.stderr.write(`[agents] routine ${config.name}: command spawn failed: ${result.error}\n`);
1363
- }
1364
- timer.end({
1365
- status: meta.status,
1366
- exitCode: meta.exitCode ?? undefined,
1367
- runId,
1368
- ...(result.error ? { error: result.error } : {}),
1369
- });
1370
- return { meta, reportPath: null };
1371
- }
1372
- function safeHook(fn) {
1373
- if (!fn)
1374
- return;
1375
- try {
1376
- fn();
1377
- }
1378
- catch { }
1379
- }
1380
- export async function executeJobDetached(config, hooks, trigger = { kind: 'manual' }) {
1381
- return runWithAttempt(config, trigger, (attempt) => executeJobDetachedClaimed(config, attempt, hooks), (meta) => meta);
1382
- }
1383
- async function executeJobDetachedClaimed(config, attempt, hooks) {
1384
- {
1385
- const { resolvePlacementTarget } = await import('../routines-placement.js');
1386
- const target = await resolvePlacementTarget(config);
1387
- if (target.mode === 'host' || target.mode === 'cloud') {
1388
- await assertRoutineAccountLocalForPlacement(config, target.mode);
1389
- }
1390
- if (target.mode === 'host') {
1391
- const { meta } = await executeJobOnHost({ ...config, host: target.host }, { detached: true }, attempt);
1392
- if (meta.status !== 'running')
1393
- emitRoutineEnd(meta);
1394
- return meta;
1395
- }
1396
- if (target.mode === 'cloud') {
1397
- const { meta } = await executeJobOnCloud(config, { detached: true }, attempt);
1398
- if (meta.status !== 'running')
1399
- emitRoutineEnd(meta);
1400
- return meta;
1401
- }
1402
- }
1403
- if (config.command) {
1404
- return executeCommandJobDetached(config, attempt, hooks);
1405
- }
1406
- const launch = await resolveRoutineLaunch(config);
1407
- const version = launch.chain[0]?.version ?? config.version;
1408
- const timer = createTimer('agent.run', {
1409
- agent: config.agent,
1410
- version,
1411
- jobName: config.name,
1412
- mode: config.mode,
1413
- ...redactPrompt(config.prompt),
1414
- schedule: config.schedule,
1415
- });
1416
- const resolvedPrompt = resolveJobPrompt(config);
1417
- let cmd = buildJobCommand(config, resolvedPrompt, launch.forwardAccount !== false);
1418
- if (!dispatchesViaAgentsRun(config) && version && config.agent) {
1419
- cmd = pinJobBinary(cmd, config.agent, version);
1420
- }
1421
- const useSandbox = config.sandbox !== false && !config.resume && !(config.agent && isCustomHarnessName(config.agent));
1422
- const overlayHome = useSandbox ? prepareJobHome(config, version) : undefined;
1423
- const runId = attempt.runId;
1424
- const runDir = getRunDir(config.name, runId);
1425
- fs.mkdirSync(runDir, { recursive: true });
1426
- const stdoutPath = path.join(runDir, 'stdout.log');
1427
- const stdoutFd = fs.openSync(stdoutPath, 'w', 0o600);
1428
- const baseEnv = injectRoutineActor(useSandbox
1429
- ? buildSpawnEnv(overlayHome, config.env)
1430
- : { ...process.env }, config);
1431
- mergeRoutineProviderEnv(baseEnv, config, config.agent);
1432
- const spawnEnv = dispatchesViaAgentsRun(config)
1433
- ? (() => {
1434
- const e = { ...baseEnv };
1435
- if (config.timezone)
1436
- e.TZ = config.timezone;
1437
- return e;
1438
- })()
1439
- : buildRoutineSpawnEnv(baseEnv, config.agent, version, config.timezone, overlayHome);
1440
- // RUSH-2860: if this host holds gh auth, the sandbox child MUST see it —
1441
- if (useSandbox)
1442
- assertSandboxForwardsHostGhAuth(spawnEnv);
1443
- const effectiveAgent = config.workflow
1444
- ? 'claude'
1445
- : isCustomHarnessName(config.agent)
1446
- ? readProfile(config.agent).host.agent
1447
- : config.agent;
1448
- const meta = {
1449
- jobName: config.name,
1450
- runId,
1451
- ...runProvenance(config),
1452
- ...attempt.stamp,
1453
- agent: effectiveAgent,
1454
- version,
1455
- ...(config.workflow ? { workflow: config.workflow } : {}),
1456
- pid: null,
1457
- spawnedAt: Date.now(),
1458
- timeoutMs: parseTimeout(config.timeout) || 10 * 60 * 1000,
1459
- status: 'running',
1460
- startedAt: new Date().toISOString(),
1461
- completedAt: null,
1462
- exitCode: null,
1463
- };
1464
- snapshotRoutineTranscriptBase(meta, runDir, overlayHome);
1465
- const preflightVersion = launch.chain[0]?.version;
1466
- const { fireTimeAuthReadiness } = await import('../routine-readiness.js');
1467
- const authBlocker = preflightVersion ? fireTimeAuthReadiness(effectiveAgent, preflightVersion) : null;
1468
- if (authBlocker) {
1469
- process.stderr.write(`[agents] routine ${config.name}: ${effectiveAgent}@${preflightVersion} ${authBlocker.code} — skipping run (${authBlocker.repair})\n`);
1470
- try {
1471
- fs.closeSync(stdoutFd);
1472
- }
1473
- catch { }
1474
- meta.readiness = authBlocker;
1475
- finalizeRunMeta(meta, 'blocked', null, { errorMessage: `blocked: ${authBlocker.code} — ${authBlocker.message}` });
1476
- writeRunMeta(meta);
1477
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1478
- timer.end({ status: 'blocked', runId, error: authBlocker.code });
1479
- return meta;
1480
- }
1481
- const child = spawn(cmd[0], cmd.slice(1), {
1482
- stdio: ['ignore', stdoutFd, stdoutFd],
1483
- ...backgroundSpawnOptions({ cwd: routineSpawnCwd(config), fdStdio: true }),
1484
- env: spawnEnv,
1485
- });
1486
- let settled = false;
1487
- let timeoutTimer;
1488
- const settle = (status, exitCode, errorMessage) => {
1489
- if (settled)
1490
- return;
1491
- settled = true;
1492
- if (timeoutTimer)
1493
- clearTimeout(timeoutTimer);
1494
- finalizeRunMeta(meta, status, exitCode, errorMessage ? { errorMessage } : undefined);
1495
- writeRunMeta(meta);
1496
- archiveRoutineTranscripts(meta, runDir, overlayHome);
1497
- const isAuthFailure = !!errorMessage && errorMessage.startsWith('auth_failed:');
1498
- if (status !== 'timeout' && !isAuthFailure)
1499
- extractAndSaveReport(stdoutPath, effectiveAgent, runDir);
1500
- timer.end({ status, exitCode: exitCode ?? undefined, runId, ...(errorMessage ? { error: errorMessage } : {}) });
1501
- safeHook(hooks?.onFinish ? () => hooks.onFinish(meta) : undefined);
1502
- };
1503
- timeoutTimer = setTimeout(() => {
1504
- terminateRoutineTree(child.pid ?? null);
1505
- settle('timeout', null, 'exceeded configured timeout');
1506
- }, meta.timeoutMs);
1507
- child.on('exit', (code) => {
1508
- let logText = '';
1509
- try {
1510
- logText = fs.readFileSync(stdoutPath, 'utf-8');
1511
- }
1512
- catch { }
1513
- if (isAuthFailureFromLog(logText, effectiveAgent, { processFailed: (code ?? 1) !== 0 })) {
1514
- const reason = authFailureReason(logText) ?? 'authentication_failed';
1515
- recordRoutineAuthOutcome(effectiveAgent, config.account, meta.version, { ok: false, verdict: 'revoked', detail: reason });
1516
- settle('failed', code ?? 1, `auth_failed: ${reason}`);
1517
- return;
1518
- }
1519
- const inferred = inferFinalStatusFromLog(stdoutPath, effectiveAgent);
1520
- const finalStatus = inferred ? inferred.status : (code === 0 ? 'completed' : 'failed');
1521
- if (finalStatus === 'completed')
1522
- recordRoutineAuthOutcome(effectiveAgent, config.account, meta.version, { ok: true });
1523
- if (inferred) {
1524
- settle(inferred.status, inferred.exitCode);
1525
- }
1526
- else {
1527
- settle(code === 0 ? 'completed' : 'failed', code ?? 1);
1528
- }
1529
- });
1530
- child.on('error', (err) => {
1531
- try {
1532
- fs.closeSync(stdoutFd);
1533
- }
1534
- catch { }
1535
- settle('failed', 1, err.message);
1536
- process.stderr.write(`[agents] daemon: spawn failed for job "${config.name}": ${err.message}\n`);
1537
- });
1538
- child.unref();
1539
- try {
1540
- fs.closeSync(stdoutFd);
1541
- }
1542
- catch { }
1543
- meta.pid = child.pid || null;
1544
- writeRunMeta(meta);
1545
- return { ...meta };
1546
- }
1547
- function executeCommandJobDetached(config, attempt, hooks) {
1548
- const timer = createTimer('agent.run', {
1549
- jobName: config.name,
1550
- mode: config.mode,
1551
- schedule: config.schedule,
1552
- });
1553
- const runId = attempt.runId;
1554
- const runDir = getRunDir(config.name, runId);
1555
- fs.mkdirSync(runDir, { recursive: true });
1556
- const stdoutPath = path.join(runDir, 'stdout.log');
1557
- const stdoutFd = fs.openSync(stdoutPath, 'w', 0o600);
1558
- const exitCodePath = path.join(runDir, 'exit-code');
1559
- const wrappedCommand = wrapCommandRoutine(config.command);
1560
- const cmd = process.platform === 'win32'
1561
- ? buildShellCommand(wrappedCommand)
1562
- : ['/bin/sh', '-c',
1563
- `(\n${wrappedCommand}\n)\n__ac_rc=$?; printf '%s' "$__ac_rc" > ${shSingleQuote(exitCodePath)} 2>/dev/null; exit $__ac_rc`];
1564
- const env = commandSpawnEnv(config);
1565
- const meta = {
1566
- jobName: config.name,
1567
- runId,
1568
- ...runProvenance(config),
1569
- ...attempt.stamp,
1570
- command: config.command,
1571
- pid: null,
1572
- spawnedAt: Date.now(),
1573
- timeoutMs: parseTimeout(config.timeout) || 10 * 60 * 1000,
1574
- status: 'running',
1575
- startedAt: new Date().toISOString(),
1576
- completedAt: null,
1577
- exitCode: null,
1578
- };
1579
- const child = spawn(cmd[0], cmd.slice(1), {
1580
- stdio: ['ignore', stdoutFd, stdoutFd],
1581
- ...backgroundSpawnOptions({ cwd: routineSpawnCwd(config), fdStdio: true }),
1582
- env,
1583
- });
1584
- let settled = false;
1585
- let timeoutTimer;
1586
- const settle = (status, exitCode, errorMessage) => {
1587
- if (settled)
1588
- return;
1589
- settled = true;
1590
- if (timeoutTimer)
1591
- clearTimeout(timeoutTimer);
1592
- finalizeRunMeta(meta, status, exitCode, errorMessage ? { errorMessage } : undefined);
1593
- writeRunMeta(meta);
1594
- timer.end({ status, exitCode: exitCode ?? undefined, runId, ...(errorMessage ? { error: errorMessage } : {}) });
1595
- safeHook(hooks?.onFinish ? () => hooks.onFinish(meta) : undefined);
1596
- };
1597
- timeoutTimer = setTimeout(() => {
1598
- terminateRoutineTree(child.pid ?? null);
1599
- settle('timeout', null, 'exceeded configured timeout');
1600
- }, meta.timeoutMs);
1601
- child.on('exit', (code) => settle(code === 0 ? 'completed' : 'failed', code ?? 1));
1602
- child.on('error', (err) => {
1603
- settle('failed', 1, err.message);
1604
- process.stderr.write(`[agents] daemon: command spawn failed for job "${config.name}": ${err.message}\n`);
1605
- });
1606
- child.unref();
1607
- try {
1608
- fs.closeSync(stdoutFd);
1609
- }
1610
- catch { }
1611
- meta.pid = child.pid || null;
1612
- writeRunMeta(meta);
1613
- return { ...meta };
1614
- }
1615
- function extractAndSaveReport(stdoutPath, agentType, runDir) {
1616
- try {
1617
- const report = extractReport(stdoutPath, agentType);
1618
- if (report) {
1619
- const reportPath = path.join(runDir, 'report.md');
1620
- fs.writeFileSync(reportPath, report, 'utf-8');
1621
- return reportPath;
1622
- }
1623
- }
1624
- catch (err) {
1625
- if (process.env.AGENTS_DEBUG) {
1626
- console.error(`[debug] Could not extract report: ${err.message}`);
1627
- }
1628
- }
1629
- return null;
1630
- }
1631
- export function extractReport(stdoutPath, agentType) {
1632
- if (!fs.existsSync(stdoutPath))
1633
- return null;
1634
- try {
1635
- const content = fs.readFileSync(stdoutPath, 'utf-8');
1636
- const lines = content.split('\n').filter((l) => l.trim());
1637
- let lastMessage = '';
1638
- for (const line of lines) {
1639
- try {
1640
- const parsed = JSON.parse(line);
1641
- if (agentType === 'claude' || agentType === 'cursor') {
1642
- if (parsed.type === 'assistant' && parsed.message?.content) {
1643
- for (const block of parsed.message.content) {
1644
- if (block.type === 'text' && block.text) {
1645
- lastMessage = block.text;
1646
- }
1647
- }
1648
- }
1649
- }
1650
- if (agentType === 'codex') {
1651
- if (parsed.type === 'message' && parsed.content) {
1652
- lastMessage = typeof parsed.content === 'string'
1653
- ? parsed.content
1654
- : JSON.stringify(parsed.content);
1655
- }
1656
- }
1657
- }
1658
- catch { }
1659
- }
1660
- return lastMessage || null;
1661
- }
1662
- catch {
1663
- return null;
1664
- }
1665
- }
1666
- export function inferFinalStatusFromLog(stdoutPath, agent) {
1667
- if (!fs.existsSync(stdoutPath))
1668
- return null;
1669
- try {
1670
- const content = fs.readFileSync(stdoutPath, 'utf-8');
1671
- const lines = content.split('\n').filter((l) => l.trim());
1672
- for (let i = lines.length - 1, scanned = 0; i >= 0 && scanned < 20; i--, scanned++) {
1673
- try {
1674
- const parsed = JSON.parse(lines[i]);
1675
- if ((agent === 'claude' || agent === 'cursor') && parsed.type === 'result') {
1676
- return parsed.is_error
1677
- ? { status: 'failed', exitCode: 1 }
1678
- : { status: 'completed', exitCode: 0 };
1679
- }
1680
- }
1681
- catch {
1682
- }
1683
- }
1684
- return null;
1685
- }
1686
- catch {
1687
- return null;
1688
- }
1689
- }
1690
- const MAX_WALL_CLOCK_MS = 24 * 60 * 60 * 1000;
1691
- const PS_IDENTITY_TIMEOUT_MS = 5_000;
1692
- function etimeIndicatesOurs(etime, spawnedAt) {
1693
- if (!etime)
1694
- return true;
1695
- const parts = etime.replace(/-/g, ':').split(':').reverse();
1696
- let uptimeSec = 0;
1697
- if (parts[0])
1698
- uptimeSec += parseInt(parts[0], 10);
1699
- if (parts[1])
1700
- uptimeSec += parseInt(parts[1], 10) * 60;
1701
- if (parts[2])
1702
- uptimeSec += parseInt(parts[2], 10) * 3600;
1703
- if (parts[3])
1704
- uptimeSec += parseInt(parts[3], 10) * 86400;
1705
- const processStartMs = Date.now() - uptimeSec * 1000;
1706
- return Math.abs(processStartMs - spawnedAt) < 30_000;
1707
- }
1708
- function isPidOurs(pid, spawnedAt) {
1709
- try {
1710
- process.kill(pid, 0);
1711
- }
1712
- catch {
1713
- return false;
1714
- }
1715
- if (spawnedAt === undefined)
1716
- return true;
1717
- if (process.platform === 'win32')
1718
- return true;
1719
- try {
1720
- const etime = execFileSync('ps', ['-p', String(pid), '-o', 'etime='], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: PS_IDENTITY_TIMEOUT_MS }).trim();
1721
- return etimeIndicatesOurs(etime, spawnedAt);
1722
- }
1723
- catch {
1724
- return true;
1725
- }
1726
- }
1727
- async function isPidOursAsync(pid, spawnedAt) {
1728
- if (!isAlive(pid))
1729
- return false;
1730
- if (spawnedAt === undefined)
1731
- return true;
1732
- if (process.platform === 'win32')
1733
- return true;
1734
- const res = await execFileBounded('ps', ['-p', String(pid), '-o', 'etime='], { timeoutMs: PS_IDENTITY_TIMEOUT_MS });
1735
- if (res.code !== 0)
1736
- return true;
1737
- return etimeIndicatesOurs(res.stdout.trim(), spawnedAt);
1738
- }
1739
- function applyHealedHostRun(meta, healed, emit = emitRoutineEnd) {
1740
- if (healed.status !== 'completed' && healed.status !== 'failed')
1741
- return;
1742
- finalizeRunMeta(meta, healed.status, healed.exitCode ?? (healed.status === 'completed' ? 0 : 1), { completedAt: healed.finishedAt ?? undefined });
1743
- writeRunMeta(meta);
1744
- emit(meta);
1745
- }
1746
- function finalizeHostRun(meta) {
1747
- try {
1748
- const task = loadHostTask(meta.hostTaskId);
1749
- if (!task)
1750
- return;
1751
- applyHealedHostRun(meta, reconcileHostTask(task));
1752
- }
1753
- catch { }
1754
- }
1755
- async function finalizeHostRunAsync(meta) {
1756
- try {
1757
- const task = loadHostTask(meta.hostTaskId);
1758
- if (!task)
1759
- return;
1760
- applyHealedHostRun(meta, await reconcileHostTaskAsync(task), (m) => { void emitRoutineEndAsync(m); });
1761
- }
1762
- catch { }
1763
- }
1764
- export function listLiveRoutineChildren() {
1765
- const runsDir = getRunsDir();
1766
- if (!fs.existsSync(runsDir))
1767
- return [];
1768
- const pids = [];
1769
- let jobDirs;
1770
- try {
1771
- jobDirs = fs.readdirSync(runsDir, { withFileTypes: true }).filter((e) => e.isDirectory());
1772
- }
1773
- catch {
1774
- return pids;
1775
- }
1776
- for (const jobDir of jobDirs) {
1777
- const jobRunsPath = path.join(runsDir, jobDir.name);
1778
- let runDirs;
1779
- try {
1780
- runDirs = fs.readdirSync(jobRunsPath, { withFileTypes: true }).filter((e) => e.isDirectory());
1781
- }
1782
- catch {
1783
- continue;
1784
- }
1785
- for (const runDirEntry of runDirs) {
1786
- const metaPath = path.join(jobRunsPath, runDirEntry.name, 'meta.json');
1787
- if (!fs.existsSync(metaPath))
1788
- continue;
1789
- try {
1790
- const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
1791
- if (meta.status !== 'running' || meta.hostTaskId || !meta.pid)
1792
- continue;
1793
- if (isPidOurs(meta.pid, meta.spawnedAt))
1794
- pids.push(meta.pid);
1795
- }
1796
- catch { }
1797
- }
1798
- }
1799
- return pids;
1800
- }
1801
- export function isRunGenuinelyInFlight(meta) {
1802
- if (meta.status !== 'running')
1803
- return false;
1804
- if (meta.hostTaskId)
1805
- return true;
1806
- if (!meta.pid)
1807
- return false;
1808
- return isPidOurs(meta.pid, meta.spawnedAt);
1809
- }
1810
- function reconcileRunningRecord(meta, jobRunsPath, runDirName, ours, emitEnd) {
1811
- const runDirPath = path.join(jobRunsPath, runDirName);
1812
- const stdoutPath = path.join(runDirPath, 'stdout.log');
1813
- const isCommandRun = Boolean(meta.command) || !meta.agent;
1814
- const wallClockMs = Date.now() - Date.parse(meta.startedAt);
1815
- const timeoutMs = meta.timeoutMs ?? MAX_WALL_CLOCK_MS;
1816
- if (Number.isFinite(wallClockMs) && wallClockMs > timeoutMs) {
1817
- if (meta.pid && ours)
1818
- terminateRoutineTree(meta.pid);
1819
- finalizeRunMeta(meta, 'timeout', null, { errorMessage: 'exceeded configured timeout' });
1820
- writeRunMeta(meta);
1821
- emitEnd(meta);
1822
- if (!isCommandRun) {
1823
- extractAndSaveReport(stdoutPath, meta.agent, runDirPath);
1824
- archiveRoutineTranscripts(meta, runDirPath);
1825
- }
1826
- return;
1827
- }
1828
- if (!meta.pid)
1829
- return;
1830
- if (!ours) {
1831
- if (isCommandRun) {
1832
- const ec = readCommandExitCode(runDirPath);
1833
- finalizeRunMeta(meta, ec === 0 ? 'completed' : 'failed', ec);
1834
- }
1835
- else {
1836
- const inferred = inferFinalStatusFromLog(stdoutPath, meta.agent);
1837
- if (inferred) {
1838
- finalizeRunMeta(meta, inferred.status, inferred.exitCode);
1839
- }
1840
- else {
1841
- finalizeRunMeta(meta, 'failed', null, { errorMessage: 'process exited before final status could be inferred' });
1842
- }
1843
- }
1844
- writeRunMeta(meta);
1845
- emitEnd(meta);
1846
- if (!isCommandRun) {
1847
- extractAndSaveReport(stdoutPath, meta.agent, runDirPath);
1848
- archiveRoutineTranscripts(meta, runDirPath);
1849
- }
1850
- }
1851
- }
1852
- export function monitorRunningJobs() {
1853
- const runsDir = getRunsDir();
1854
- if (!fs.existsSync(runsDir))
1855
- return;
1856
- const jobDirs = fs.readdirSync(runsDir, { withFileTypes: true })
1857
- .filter((e) => e.isDirectory());
1858
- for (const jobDir of jobDirs) {
1859
- const jobRunsPath = path.join(runsDir, jobDir.name);
1860
- let runDirs;
1861
- try {
1862
- runDirs = fs.readdirSync(jobRunsPath, { withFileTypes: true })
1863
- .filter((e) => e.isDirectory());
1864
- }
1865
- catch (err) {
1866
- if (err.code === 'ENOENT')
1867
- continue;
1868
- throw err;
1869
- }
1870
- for (const runDirEntry of runDirs) {
1871
- const metaPath = path.join(jobRunsPath, runDirEntry.name, 'meta.json');
1872
- if (!fs.existsSync(metaPath))
1873
- continue;
1874
- try {
1875
- const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
1876
- if (meta.status !== 'running')
1877
- continue;
1878
- if (meta.hostTaskId) {
1879
- finalizeHostRun(meta);
1880
- continue;
1881
- }
1882
- const ours = meta.pid ? isPidOurs(meta.pid, meta.spawnedAt) : false;
1883
- reconcileRunningRecord(meta, jobRunsPath, runDirEntry.name, ours, emitRoutineEnd);
1884
- }
1885
- catch { }
1886
- }
1887
- }
1888
- }
1889
- export async function reapExitedRunningJobs() {
1890
- const runsDir = getRunsDir();
1891
- let jobDirs;
1892
- try {
1893
- jobDirs = await fsp.readdir(runsDir, { withFileTypes: true });
1894
- }
1895
- catch {
1896
- return;
1897
- }
1898
- for (const jobDir of jobDirs) {
1899
- if (!jobDir.isDirectory())
1900
- continue;
1901
- const jobRunsPath = path.join(runsDir, jobDir.name);
1902
- let runDirs;
1903
- try {
1904
- runDirs = await fsp.readdir(jobRunsPath, { withFileTypes: true });
1905
- }
1906
- catch {
1907
- continue;
1908
- }
1909
- for (const runDirEntry of runDirs) {
1910
- if (!runDirEntry.isDirectory())
1911
- continue;
1912
- try {
1913
- const raw = await fsp.readFile(path.join(jobRunsPath, runDirEntry.name, 'meta.json'), 'utf-8');
1914
- const meta = JSON.parse(raw);
1915
- if (meta.status !== 'running')
1916
- continue;
1917
- if (meta.hostTaskId) {
1918
- await finalizeHostRunAsync(meta);
1919
- continue;
1920
- }
1921
- const ours = meta.pid ? await isPidOursAsync(meta.pid, meta.spawnedAt) : false;
1922
- reconcileRunningRecord(meta, jobRunsPath, runDirEntry.name, ours, (m) => { void emitRoutineEndAsync(m); });
1923
- }
1924
- catch { }
1925
- }
1926
- }
1927
- }