@phnx-labs/agents-cli 1.22.0 → 1.22.3

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 (42) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +2 -0
  3. package/dist/bin/agents +0 -0
  4. package/dist/commands/cloud.js +1 -1
  5. package/dist/commands/doctor.js +34 -2
  6. package/dist/commands/exec.js +1 -1
  7. package/dist/commands/projects.js +128 -66
  8. package/dist/commands/secrets.js +9 -5
  9. package/dist/commands/teams.js +2 -2
  10. package/dist/commands/watchdog.js +64 -5
  11. package/dist/lib/app-bundle-install.d.ts +17 -0
  12. package/dist/lib/app-bundle-install.js +94 -0
  13. package/dist/lib/devices/doctor-findings.js +12 -4
  14. package/dist/lib/devices/doctor-overview-cache.d.ts +45 -0
  15. package/dist/lib/devices/doctor-overview-cache.js +168 -0
  16. package/dist/lib/devices/fleet.js +7 -2
  17. package/dist/lib/devices/self-host.d.ts +9 -0
  18. package/dist/lib/devices/self-host.js +61 -0
  19. package/dist/lib/hosts/passthrough.js +8 -6
  20. package/dist/lib/menubar/MenubarHelper.app/Contents/CodeResources +0 -0
  21. package/dist/lib/menubar/MenubarHelper.app/Contents/MacOS/MenubarHelper +0 -0
  22. package/dist/lib/menubar/install-menubar.js +27 -23
  23. package/dist/lib/project-status.d.ts +7 -0
  24. package/dist/lib/project-status.js +9 -0
  25. package/dist/lib/projects.d.ts +26 -2
  26. package/dist/lib/projects.js +69 -9
  27. package/dist/lib/rotate.d.ts +16 -1
  28. package/dist/lib/rotate.js +33 -7
  29. package/dist/lib/secrets/Agents CLI.app/Contents/CodeResources +0 -0
  30. package/dist/lib/secrets/Agents CLI.app/Contents/MacOS/Agents CLI +0 -0
  31. package/dist/lib/secrets/bundles.d.ts +20 -0
  32. package/dist/lib/secrets/bundles.js +50 -0
  33. package/dist/lib/secrets/install-helper.js +28 -31
  34. package/dist/lib/share/config.d.ts +14 -6
  35. package/dist/lib/share/config.js +23 -5
  36. package/dist/lib/types.d.ts +10 -0
  37. package/dist/lib/versions.js +69 -22
  38. package/dist/lib/watchdog/rotate.d.ts +218 -0
  39. package/dist/lib/watchdog/rotate.js +378 -0
  40. package/dist/lib/watchdog/runner.d.ts +33 -1
  41. package/dist/lib/watchdog/runner.js +303 -0
  42. package/package.json +1 -1
@@ -1267,34 +1267,23 @@ export function isVersionIsolated(agent, version) {
1267
1267
  return fs.existsSync(getIsolatedMarkerPath(agent, version));
1268
1268
  }
1269
1269
  /**
1270
- * Grok's official installer writes into ~/.grok/downloads, which (because we
1271
- * symlink ~/.grok to the active version home) resolves to the PREVIOUS default
1272
- * home during `agents add grok@<new>`. Move the freshly-downloaded binary and
1273
- * its generic platform copy into the target version's isolated home so
1274
- * `listInstalledVersions` and the shim resolve the right binary.
1270
+ * Move any `grok-<installedVersion>-...` binary (and its generic platform
1271
+ * copy) found directly under `sourceDownloads` into `targetDownloads`.
1272
+ * Returns true if the versioned binary was moved.
1275
1273
  */
1276
- function relocateGrokBinaryToVersionHome(installedVersion) {
1277
- const hostGrokLink = path.join(getHomeDir(), agentConfigDirName('grok'));
1278
- let sourceDownloads;
1279
- try {
1280
- sourceDownloads = path.join(fs.readlinkSync(hostGrokLink), 'downloads');
1281
- }
1282
- catch {
1283
- sourceDownloads = path.join(hostGrokLink, 'downloads');
1284
- }
1285
- const targetDownloads = path.join(getVersionHomePath('grok', installedVersion), agentConfigDirName('grok'), 'downloads');
1274
+ function tryMoveGrokDownloads(sourceDownloads, targetDownloads, installedVersion) {
1286
1275
  if (!fs.existsSync(sourceDownloads))
1287
- return;
1276
+ return false;
1288
1277
  if (path.resolve(sourceDownloads) === path.resolve(targetDownloads))
1289
- return;
1278
+ return false;
1290
1279
  const entries = fs.readdirSync(sourceDownloads).filter((e) => e.startsWith('grok-'));
1291
1280
  if (entries.length === 0)
1292
- return;
1293
- fs.mkdirSync(targetDownloads, { recursive: true });
1281
+ return false;
1294
1282
  const escapedVersion = installedVersion.replace(/\./g, '\\.');
1295
1283
  const versionedPattern = new RegExp(`^grok-${escapedVersion}-`);
1296
1284
  const movedPaths = [];
1297
- // Move the versioned binary first.
1285
+ // Move the versioned binary first — only create the target dir once we
1286
+ // know there is something to move into it.
1298
1287
  for (const entry of entries) {
1299
1288
  if (!versionedPattern.test(entry))
1300
1289
  continue;
@@ -1303,6 +1292,7 @@ function relocateGrokBinaryToVersionHome(installedVersion) {
1303
1292
  if (fs.existsSync(dst))
1304
1293
  continue;
1305
1294
  try {
1295
+ fs.mkdirSync(targetDownloads, { recursive: true });
1306
1296
  fs.renameSync(src, dst);
1307
1297
  movedPaths.push(dst);
1308
1298
  }
@@ -1311,7 +1301,7 @@ function relocateGrokBinaryToVersionHome(installedVersion) {
1311
1301
  }
1312
1302
  }
1313
1303
  if (movedPaths.length === 0)
1314
- return;
1304
+ return false;
1315
1305
  // The installer also creates a generic platform binary (e.g. grok-macos-aarch64)
1316
1306
  // that is a copy of the versioned binary. Move it too if its size matches.
1317
1307
  const movedSize = fs.statSync(movedPaths[0]).size;
@@ -1331,6 +1321,42 @@ function relocateGrokBinaryToVersionHome(installedVersion) {
1331
1321
  /* ignore per-file failures */
1332
1322
  }
1333
1323
  }
1324
+ return true;
1325
+ }
1326
+ /**
1327
+ * Grok's official installer writes into ~/.grok/downloads, which (because we
1328
+ * symlink ~/.grok to the active version home) resolves to the PREVIOUS default
1329
+ * home during `agents add grok@<new>`. Move the freshly-downloaded binary and
1330
+ * its generic platform copy into the target version's isolated home so
1331
+ * `listInstalledVersions` and the shim resolve the right binary.
1332
+ *
1333
+ * Self-healing: if `~/.grok`'s current target has nothing matching (e.g. a
1334
+ * PAST install mislabeled `installedVersion` as the literal string 'latest',
1335
+ * whose regex never matched the real filename, stranding the binary in
1336
+ * whatever version was default at the time), sweep every other installed
1337
+ * grok version home for the missing file before giving up.
1338
+ */
1339
+ function relocateGrokBinaryToVersionHome(installedVersion) {
1340
+ const hostGrokLink = path.join(getHomeDir(), agentConfigDirName('grok'));
1341
+ let sourceDownloads;
1342
+ try {
1343
+ sourceDownloads = path.join(fs.readlinkSync(hostGrokLink), 'downloads');
1344
+ }
1345
+ catch {
1346
+ sourceDownloads = path.join(hostGrokLink, 'downloads');
1347
+ }
1348
+ const targetDownloads = path.join(getVersionHomePath('grok', installedVersion), agentConfigDirName('grok'), 'downloads');
1349
+ if (tryMoveGrokDownloads(sourceDownloads, targetDownloads, installedVersion))
1350
+ return;
1351
+ for (const version of listInstalledVersions('grok')) {
1352
+ if (version === installedVersion)
1353
+ continue;
1354
+ const candidate = path.join(getVersionHomePath('grok', version), agentConfigDirName('grok'), 'downloads');
1355
+ if (path.resolve(candidate) === path.resolve(sourceDownloads))
1356
+ continue; // already tried
1357
+ if (tryMoveGrokDownloads(candidate, targetDownloads, installedVersion))
1358
+ return;
1359
+ }
1334
1360
  }
1335
1361
  /**
1336
1362
  * Install a specific version of an agent.
@@ -1376,7 +1402,28 @@ export async function installVersion(agent, version, onProgress, opts) {
1376
1402
  await execAsync(script, { timeout: 120000 });
1377
1403
  }
1378
1404
  if (version === 'latest') {
1379
- installedVersion = await getCliVersionFromPath(agent) || version;
1405
+ // A freshly-installed self-updating binary (grok, …) can take a
1406
+ // moment to become resolvable on PATH right after the installer
1407
+ // exits — retry briefly rather than silently falling back to the
1408
+ // literal string 'latest'. That fallback used to corrupt version
1409
+ // bookkeeping downstream: it creates a bogus `versions/<agent>/latest/`
1410
+ // dir, and for grok specifically defeats relocateGrokBinaryToVersionHome
1411
+ // (its exact-filename regex can never match `grok-latest-...`), which
1412
+ // permanently strands the real downloaded binary in the PREVIOUS
1413
+ // default's downloads dir.
1414
+ let probed = await getCliVersionFromPath(agent);
1415
+ for (let attempt = 0; !probed && attempt < 2; attempt++) {
1416
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1417
+ probed = await getCliVersionFromPath(agent);
1418
+ }
1419
+ if (!probed) {
1420
+ return {
1421
+ success: false,
1422
+ installedVersion: version,
1423
+ error: `${agentConfig.name} installed but its version could not be determined after several attempts.`,
1424
+ };
1425
+ }
1426
+ installedVersion = probed;
1380
1427
  // Fold any stale literal `latest` dir from an earlier probe-failed
1381
1428
  // install into the real version so it stops shadowing `agents view`.
1382
1429
  await reconcileStaleLatestDir(agent, installedVersion);
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Watchdog rotate — in-place rotation of a rate-limited session onto a healthy
3
+ * account/harness, inside the SAME terminal tab (one-watchdog; follow-up to
4
+ * RUSH-2132 / PR #1875).
5
+ *
6
+ * When a stalled session's transcript tail shows a hard limit ("You've hit your
7
+ * weekly limit · resets …"), the daemon watchdog rotates it instead of nudging:
8
+ *
9
+ * 1. DETECT — classifyTailForRotate() matches the tail against the limit
10
+ * patterns (ported from apps/factory/src/core/autoRotate.ts) and parses the
11
+ * `resets <time>` clause when present.
12
+ * 2. GATE — defaultRotateGate() runs the SAME first-party selection
13
+ * `agents run auto` would (collectHarnessCandidates + pickHarnessWeighted,
14
+ * ../rotate.ts). Zero healthy → ONE `rotate` skip event per cooldown window
15
+ * and the terminal is left untouched. No `agents view` subprocess anywhere.
16
+ * 3. RELAUNCH — the per-harness exit sequence (ported from apps/factory
17
+ * prewarm.ts PREWARM_CONFIGS) is injected, then
18
+ * `agents run auto --interactive --session-id <uuid>`.
19
+ * 4. REPLAY — when the new session's TUI is live (bounded wait, default
20
+ * 60s), the resume replay is injected. On timeout the session is flagged
21
+ * and the machine stops — never blind-type into a dead shell.
22
+ *
23
+ * The machine spans ticks (the exit sequence kills the old session, so it drops
24
+ * out of the active-session list before the new TUI is live): state persists at
25
+ * <watchdog-state>/rotate/<sessionId>.json as
26
+ * exiting → launching → awaiting-tui → replaying → done | failed.
27
+ *
28
+ * Config: `watchdog.rotate: on|off` in agents.yaml (default on), read per tick.
29
+ */
30
+ import type { InjectTarget } from '../terminal/inject.js';
31
+ import type { ActiveSession } from '../session/active.js';
32
+ /**
33
+ * Agent-reported hard-limit texts, matched against a session transcript tail.
34
+ * Ported verbatim from apps/factory/src/core/autoRotate.ts RATE_LIMIT_PATTERNS —
35
+ * kept specific on purpose: a transcript carries prose, so a loose "rate limit"
36
+ * match would rotate terminals whose agent merely DISCUSSED limits. The first
37
+ * two patterns cover the weekly/session variants, including claude's
38
+ * "You've hit your weekly limit · resets <time>" form.
39
+ */
40
+ export declare const ROTATE_LIMIT_PATTERNS: RegExp[];
41
+ export type RotateTailVerdict = {
42
+ kind: 'none';
43
+ } | {
44
+ kind: 'rate_limited';
45
+ resetsAtMs?: number;
46
+ };
47
+ /**
48
+ * Classify a transcript tail for the rotate decision: does it show a hard
49
+ * account limit (rotate this session) or not (leave it to the nudge path)?
50
+ * Unlike the retired extension path there is NO `no healthy` tail parsing here —
51
+ * the health gate is a first-party function call (defaultRotateGate), not a
52
+ * cross-package string contract.
53
+ */
54
+ export declare function classifyTailForRotate(tailLines: string[], nowMs: number): RotateTailVerdict;
55
+ /**
56
+ * Parse the `resets <time>` clause of a limit line into an epoch-ms horizon.
57
+ * Ported from apps/factory/src/core/autoRotate.ts parseResetTimeMs (behavior
58
+ * verbatim): the ISO form (milliseconds + Z) is matched EXPLICITLY and first —
59
+ * a generic capture stops at the milliseconds dot and drops the Z, which makes
60
+ * Date.parse read LOCAL time (the suppression would end hours off). Time-of-day
61
+ * forms like `7am` / `7:30pm` with an optional `(Area/City)` IANA zone cover
62
+ * claude's own limit text. Returns undefined when no usable reset is present or
63
+ * the parsed time is already past (caller falls back to its default cooldown).
64
+ */
65
+ export declare function parseRotateResetMs(text: string, nowMs: number): number | undefined;
66
+ /**
67
+ * Clean-exit key sequences per harness, ported verbatim from apps/factory
68
+ * prewarm.ts PREWARM_CONFIGS. Injected as RAW BYTES with no trailing Enter — a
69
+ * literal \x03 written to the pty IS Ctrl+C (SIGINT), \x1b IS Esc. claude's Ink
70
+ * TUI needs the Esc first to leave any open mode before the interrupt pair.
71
+ */
72
+ export declare const ROTATE_EXIT_SEQUENCES: Record<string, string[]>;
73
+ /** Unknown harnesses get the common denominator: Ctrl+C twice. */
74
+ export declare const DEFAULT_ROTATE_EXIT_SEQUENCE: string[];
75
+ export declare function exitSequenceFor(agent: string): string[];
76
+ /**
77
+ * The rotate relaunch, typed into the same tab: full auto — the CLI resolves
78
+ * host (affinity) → harness (cross-harness headroom) → account (balanced) and
79
+ * exits nonzero when every layer is exhausted. Ported from apps/factory
80
+ * autoRotate.ts buildAutoRotateLaunchCommand. A terminal on a REMOTE device
81
+ * rotates ON that device (`--host`); a local terminal omits it. `--session-id`
82
+ * is honored only when the CLI picks claude (existing claude-only semantics)
83
+ * and ignored otherwise — passing it unconditionally keeps the terminal's
84
+ * AGENT_SESSION_ID aligned with the session Claude actually creates.
85
+ */
86
+ export declare function buildRotateLaunchCommand(opts: {
87
+ host?: string;
88
+ sessionId: string;
89
+ }): string;
90
+ /**
91
+ * The harness-agnostic replay injected once the new TUI is live: load the OLD
92
+ * session's transcript, assess, continue. This is the same instruction shape
93
+ * the CLI's own `continue` flow uses.
94
+ */
95
+ export declare function buildRotateReplayText(oldSessionId: string): string;
96
+ export type RotatePhase = 'exiting' | 'launching' | 'awaiting-tui' | 'replaying' | 'done' | 'failed';
97
+ /** Persisted at <watchdog-state>/rotate/<sessionId>.json — keyed by the OLD session id. */
98
+ export interface RotateState {
99
+ /** The OLD (rate-limited) session id — the file key and the replay target. */
100
+ sessionId: string;
101
+ /** The id passed to `--session-id` on the relaunch. */
102
+ newSessionId: string;
103
+ /** The harness that was rate-limited (drives the exit-sequence table). */
104
+ agent: string;
105
+ phase: RotatePhase;
106
+ /** The resolved inject target — serializable, so the sweep can replay without re-resolving. */
107
+ target: InjectTarget;
108
+ /** Remote device the terminal lives on, when provenance says ssh. */
109
+ host?: string;
110
+ /**
111
+ * The old session's cwd — correlates the readiness fallback: a fresh active
112
+ * session only counts as the relaunched TUI when it runs in the SAME project.
113
+ */
114
+ cwd?: string;
115
+ /**
116
+ * The machine the old session runs on (provenance host = os.hostname()) —
117
+ * the second half of the readiness-fallback correlation, so a fresh session
118
+ * on ANOTHER box never satisfies it.
119
+ */
120
+ machineHost?: string;
121
+ startedAtMs: number;
122
+ updatedAtMs: number;
123
+ /** awaiting-tui deadline: startedAtMs + readiness budget. */
124
+ deadlineMs: number;
125
+ error?: string;
126
+ /**
127
+ * Set on the transition to `failed`: the tick will not re-begin a rotate for
128
+ * this session until then (default +15m). Without it a session whose old TUI
129
+ * ignored the exit sequence re-enters begin → deadline → failed every tick.
130
+ */
131
+ suppressUntilMs?: number;
132
+ }
133
+ /** Bounded wait for the relaunched TUI to come live (readiness). */
134
+ export declare const DEFAULT_ROTATE_READINESS_MS = 60000;
135
+ /** Zero-healthy skip cooldown when neither the gate nor the tail carries a reset. */
136
+ export declare const DEFAULT_ROTATE_SKIP_COOLDOWN_MS: number;
137
+ /** Retry cooldown after a FAILED rotate — honored at begin via the state file. */
138
+ export declare const DEFAULT_ROTATE_FAILED_COOLDOWN_MS: number;
139
+ export declare function rotateStatePath(dir: string, sessionId: string): string;
140
+ export declare function readRotateState(dir: string, sessionId: string): RotateState | null;
141
+ export declare function writeRotateState(dir: string, state: RotateState): void;
142
+ export declare function clearRotateState(dir: string, sessionId: string): void;
143
+ /** A phase the machine still has work to do in (done/failed are terminal). */
144
+ export declare function isInflightPhase(phase: RotatePhase): boolean;
145
+ /** Every persisted rotate state (any phase) — for `watchdog status`. */
146
+ export declare function listRotateStates(dir: string): RotateState[];
147
+ /** In-flight rotates only — the set a tick's sweep must advance. */
148
+ export declare function listInflightRotates(dir: string): RotateState[];
149
+ /**
150
+ * One `rotate` skip event per cooldown window, tracked as
151
+ * <watchdog-state>/rotate-skips.json: { [sessionId]: suppressUntilMs }. A skip
152
+ * inside the window logs nothing and touches nothing.
153
+ */
154
+ export declare function readRotateSkipLedger(dir: string): Record<string, number>;
155
+ /** True when a skip for this session is OUTSIDE its suppression window (log it). */
156
+ export declare function shouldLogRotateSkip(dir: string, sessionId: string, nowMs: number): boolean;
157
+ /** Suppress further skip events for this session until suppressUntilMs. */
158
+ export declare function recordRotateSkip(dir: string, sessionId: string, suppressUntilMs: number): void;
159
+ /**
160
+ * `watchdog.rotate` in agents.yaml (default ON — it is safe now: the health gate
161
+ * is first-party and the readiness wait is bounded). Read fresh per tick so a
162
+ * flip mid-run is honored on the next pass.
163
+ */
164
+ export declare function isWatchdogRotateEnabled(): boolean;
165
+ /**
166
+ * Persist `watchdog.rotate: on|off`. Called by the `agents watchdog rotate
167
+ * on|off` subcommand (commands/watchdog.ts) — the rotate-only switch the
168
+ * Factory migration uses so a user who opted out of autoRotate keeps nudging
169
+ * (rather than `agents watchdog disable`, which kills the whole watchdog).
170
+ */
171
+ export declare function setWatchdogRotateEnabled(on: boolean): void;
172
+ export interface RotateGateResult {
173
+ /** True when at least one harness has a healthy account to rotate INTO. */
174
+ healthy: boolean;
175
+ /** Earliest future window reset across all candidates, when any snapshot carries one. */
176
+ resetsAtMs?: number;
177
+ /** Human detail for the skip event (the zero-healthy error text). */
178
+ detail: string;
179
+ }
180
+ /**
181
+ * The first-party health gate: run the SAME selection `agents run auto` would —
182
+ * collectHarnessCandidates over every installed harness, pickHarnessWeighted.
183
+ * Zero healthy → the caller suppresses rotation until earliestResetAcross (or
184
+ * the parsed tail reset, or the default cooldown) and leaves the terminal alone.
185
+ * No `agents view` subprocess, no Keychain probe: collection is cache-only
186
+ * (collectRunCandidates reads daemon-written snapshots, readOnly).
187
+ */
188
+ export declare function defaultRotateGate(): Promise<RotateGateResult>;
189
+ /**
190
+ * Default TUI-liveness probe for the relaunched session: the new session's
191
+ * transcript resolves under any known harness layout. `--session-id` is honored
192
+ * on a claude pick; for other harnesses the runner's readiness check ALSO
193
+ * accepts a fresh active session (started after the rotate began), so a codex
194
+ * pick with an unknown id is still detected.
195
+ */
196
+ export declare function defaultRotateTranscriptLive(newSessionId: string): boolean;
197
+ /**
198
+ * The readiness FALLBACK correlation. A fresh active session counts as the
199
+ * relaunched TUI only when ALL of these hold:
200
+ * - it is not the old session and started at/after the rotate began;
201
+ * - it runs in the SAME cwd (trailing-slash normalized); and
202
+ * - it runs on the SAME machine (provenance host = os.hostname(), the same
203
+ * field provenance.ts populates).
204
+ * An unrelated fresh session — another project, another host, a remote
205
+ * teammate — must NEVER satisfy readiness: on a busy fleet box an
206
+ * uncorrelated "any new session" match fires on the first sweep regardless of
207
+ * whether the relaunch came up, and when `agents run auto` failed loud after
208
+ * the gate that types the replay into a bare shell. When the state lacks cwd
209
+ * or host the fallback cannot correlate and only the transcript probe counts.
210
+ */
211
+ export declare function isCorrelatedRelaunch(state: RotateState, s: ActiveSession): boolean;
212
+ /**
213
+ * The default TUI-liveness probe. The new-session-id transcript is PRIMARY (a
214
+ * claude pick honors `--session-id`); the correlated fresh-session fallback
215
+ * (isCorrelatedRelaunch) covers non-claude picks whose id we can't know a
216
+ * priori.
217
+ */
218
+ export declare function defaultTuiLiveFor(state: RotateState, sessions: ActiveSession[]): boolean;