@phnx-labs/agents-cli 1.22.25 → 1.22.26

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 (82) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/README.md +17 -2
  3. package/dist/bin/agents +0 -0
  4. package/dist/browser.js +14 -4
  5. package/dist/commands/apply.js +52 -8
  6. package/dist/commands/browser.js +35 -0
  7. package/dist/commands/doctor.js +8 -0
  8. package/dist/commands/insights.d.ts +25 -19
  9. package/dist/commands/insights.js +107 -33
  10. package/dist/commands/reconnect.d.ts +46 -0
  11. package/dist/commands/reconnect.js +109 -0
  12. package/dist/commands/routines.js +2 -2
  13. package/dist/commands/secrets.d.ts +2 -8
  14. package/dist/commands/secrets.js +29 -105
  15. package/dist/commands/sessions.js +4 -0
  16. package/dist/commands/setup-secrets.d.ts +1 -0
  17. package/dist/commands/setup-secrets.js +1 -1
  18. package/dist/commands/setup.d.ts +26 -3
  19. package/dist/commands/setup.js +105 -46
  20. package/dist/commands/teams.d.ts +6 -0
  21. package/dist/commands/teams.js +43 -0
  22. package/dist/commands/trends.d.ts +8 -0
  23. package/dist/commands/trends.js +10 -156
  24. package/dist/index.js +1 -1
  25. package/dist/lib/agents.d.ts +11 -0
  26. package/dist/lib/agents.js +29 -2
  27. package/dist/lib/analytics/dashboard.d.ts +10 -6
  28. package/dist/lib/analytics/dashboard.js +6 -4
  29. package/dist/lib/analytics/mix-commands.d.ts +53 -0
  30. package/dist/lib/analytics/mix-commands.js +229 -0
  31. package/dist/lib/analytics/recipes.d.ts +19 -14
  32. package/dist/lib/analytics/recipes.js +4 -2
  33. package/dist/lib/browser/ipc.d.ts +26 -0
  34. package/dist/lib/browser/ipc.js +139 -24
  35. package/dist/lib/browser/profiles.d.ts +11 -0
  36. package/dist/lib/browser/profiles.js +1 -1
  37. package/dist/lib/browser/stream.d.ts +14 -0
  38. package/dist/lib/browser/stream.js +71 -0
  39. package/dist/lib/channels/owner-sink.d.ts +27 -0
  40. package/dist/lib/channels/owner-sink.js +93 -0
  41. package/dist/lib/devices/doctor-findings.d.ts +7 -1
  42. package/dist/lib/devices/doctor-findings.js +33 -1
  43. package/dist/lib/fleet/apply.d.ts +59 -3
  44. package/dist/lib/fleet/apply.js +183 -6
  45. package/dist/lib/fleet/types.d.ts +21 -2
  46. package/dist/lib/hooks/cache.js +15 -0
  47. package/dist/lib/hosts/passthrough.d.ts +23 -0
  48. package/dist/lib/hosts/passthrough.js +45 -0
  49. package/dist/lib/hosts/ready.d.ts +2 -0
  50. package/dist/lib/hosts/ready.js +10 -1
  51. package/dist/lib/hosts/reconnect.d.ts +14 -12
  52. package/dist/lib/hosts/reconnect.js +41 -40
  53. package/dist/lib/menubar/MenubarHelper.app/Contents/CodeResources +0 -0
  54. package/dist/lib/menubar/MenubarHelper.app/Contents/MacOS/MenubarHelper +0 -0
  55. package/dist/lib/routines.js +14 -2
  56. package/dist/lib/runner.d.ts +0 -3
  57. package/dist/lib/runner.js +1 -14
  58. package/dist/lib/secrets/Agents CLI.app/Contents/CodeResources +0 -0
  59. package/dist/lib/secrets/Agents CLI.app/Contents/MacOS/Agents CLI +0 -0
  60. package/dist/lib/secrets/push.d.ts +94 -0
  61. package/dist/lib/secrets/push.js +145 -0
  62. package/dist/lib/secrets/reaper.d.ts +15 -1
  63. package/dist/lib/secrets/reaper.js +30 -3
  64. package/dist/lib/session/db.d.ts +21 -3
  65. package/dist/lib/session/db.js +221 -13
  66. package/dist/lib/session/discover.d.ts +1 -0
  67. package/dist/lib/session/discover.js +115 -19
  68. package/dist/lib/session/insights.d.ts +18 -0
  69. package/dist/lib/session/insights.js +143 -1
  70. package/dist/lib/session/tool-index.js +133 -22
  71. package/dist/lib/session/tool-store.d.ts +26 -2
  72. package/dist/lib/session/tool-store.js +36 -17
  73. package/dist/lib/ssh-exec.js +8 -2
  74. package/dist/lib/startup/command-registry.d.ts +1 -0
  75. package/dist/lib/startup/command-registry.js +4 -0
  76. package/dist/lib/teams/agents.d.ts +13 -0
  77. package/dist/lib/teams/agents.js +75 -7
  78. package/dist/lib/teams/placement-probe.d.ts +21 -0
  79. package/dist/lib/teams/placement-probe.js +135 -0
  80. package/dist/lib/teams/scheduler.d.ts +74 -1
  81. package/dist/lib/teams/scheduler.js +187 -10
  82. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Live pool probing for the teams placement scheduler (RUSH-2002).
3
+ *
4
+ * Gathers one {@link DevicePlacementSignal} per pool device so the pure pick in
5
+ * {@link ./scheduler} can filter unreachable / overloaded / not-installed
6
+ * devices and rank the rest. Two concerns, both best-effort:
7
+ *
8
+ * - reachability + headroom + load ← {@link probeFleetStats} (one parallel
9
+ * SSH fan-out over the pool; the local box is measured directly).
10
+ * - requested agent installed (+ signed in, locally) ← a one-shot readiness
11
+ * probe per remote device ({@link buildReadyProbeCommand} → `agents view`),
12
+ * the local box via {@link checkCliAvailable}/{@link checkCliSignedIn}.
13
+ *
14
+ * The result is cached briefly per (pool, agent) so a `teams start` wave that
15
+ * places N teammates probes the pool ONCE, not N times — the roster-count part
16
+ * of the rank stays live (the pure pick recounts the roster each call), only the
17
+ * SSH-measured load/harness snapshot is reused within the TTL.
18
+ *
19
+ * All SSH here is via `execFile` (async, bounded) so the whole pool is probed in
20
+ * parallel; a slow or wedged box degrades to "no signal" instead of blocking the
21
+ * launch. Remote sign-in is deliberately left unknown — sign-in detection is
22
+ * unreliable over SSH (see {@link checkCliSignedIn}); it ranks the local box
23
+ * only, and the install gate (not sign-in) is what drives the fail-loud.
24
+ */
25
+ import { execFile } from 'child_process';
26
+ import { probeFleetStats, headroom } from '../devices/health.js';
27
+ import { loadDevicesSync } from '../devices/registry.js';
28
+ import { buildSshInvocation, writeAskpassShim } from '../devices/connect.js';
29
+ import { buildReadyProbeCommand, parseReadyProbe, viewHasAgent } from '../hosts/ready.js';
30
+ import { localMachineId } from '../session/origin-machine.js';
31
+ import { normalizeHost } from '../machine-id.js';
32
+ import { checkCliAvailable, checkCliSignedIn } from './agents.js';
33
+ /** Per-remote readiness probe budget — matches the health probe's short window
34
+ * (`agents view` on a warm box is sub-second; a wedged one degrades to unknown). */
35
+ export const READY_PROBE_TIMEOUT_MS = 8_000;
36
+ /** How long a probed pool snapshot is reused within a `teams start` wave. Short
37
+ * enough that a device coming online / going overloaded is seen next wave, long
38
+ * enough that placing a wave of teammates does not re-fan-out per teammate. */
39
+ export const SIGNAL_TTL_MS = 15_000;
40
+ const cache = new Map();
41
+ function cacheKey(pool, agent) {
42
+ return `${agent}::${[...pool].map(normalizeHost).sort().join(',')}`;
43
+ }
44
+ /** Clear the probe cache — for tests and after a device-registry change. */
45
+ export function clearPlacementSignalCache() {
46
+ cache.clear();
47
+ }
48
+ /**
49
+ * Whether the requested agent is installed on a REMOTE device, via one SSH
50
+ * readiness probe. `undefined` when the probe could not answer (ssh/login
51
+ * failure) — reachability is then left to {@link probeFleetStats}; `false` when
52
+ * the box answered but agents-cli or the agent is absent (a genuine can't-run).
53
+ */
54
+ function probeRemoteInstalled(device, agent) {
55
+ let args;
56
+ let env;
57
+ try {
58
+ const shim = writeAskpassShim();
59
+ const cmd = buildReadyProbeCommand(device.shell === 'powershell' ? 'windows' : undefined);
60
+ // agentOnly: a read-only probe must never force a foreground Touch ID sheet
61
+ // on a password-auth device (mirrors probeDeviceStats in devices/health).
62
+ ({ args, env } = buildSshInvocation(device, [cmd], shim, {}, { agentOnly: true }));
63
+ }
64
+ catch {
65
+ return Promise.resolve(undefined);
66
+ }
67
+ return new Promise((resolve) => {
68
+ execFile('ssh', args, { encoding: 'utf-8', env: { ...process.env, ...env }, timeout: READY_PROBE_TIMEOUT_MS }, (err, stdout) => {
69
+ if (err || !stdout)
70
+ return resolve(undefined);
71
+ const probe = parseReadyProbe(stdout);
72
+ if (!probe.reachable)
73
+ return resolve(undefined); // ssh/login issue → unknown
74
+ if (!probe.version)
75
+ return resolve(false); // agents-cli missing → cannot run
76
+ resolve(viewHasAgent(probe.view, agent));
77
+ });
78
+ });
79
+ }
80
+ /**
81
+ * Probe every device in the team pool and return a name→signal map for the pure
82
+ * placement pick. Devices with no data at all are omitted (the pick then neither
83
+ * excludes nor prefers them). Never throws — a probe failure degrades to a
84
+ * missing/partial signal.
85
+ */
86
+ export async function probePoolSignals(pool, agent, opts = {}) {
87
+ const now = opts.now ?? Date.now();
88
+ const key = cacheKey(pool, agent);
89
+ const cached = cache.get(key);
90
+ if (!opts.force && cached && now - cached.at < SIGNAL_TTL_MS)
91
+ return cached.signals;
92
+ const reg = loadDevicesSync();
93
+ const self = normalizeHost(localMachineId());
94
+ const lookup = (name) => reg[name] ?? reg[normalizeHost(name)];
95
+ const profiles = [];
96
+ const seen = new Set();
97
+ for (const name of pool) {
98
+ const d = lookup(name);
99
+ if (d && !seen.has(d.name)) {
100
+ profiles.push(d);
101
+ seen.add(d.name);
102
+ }
103
+ }
104
+ const selfProfile = profiles.find((d) => normalizeHost(d.name) === self);
105
+ const stats = await probeFleetStats(profiles, { selfName: selfProfile?.name });
106
+ const installed = new Map(await Promise.all(profiles.map(async (d) => {
107
+ const isSelf = normalizeHost(d.name) === self;
108
+ if (isSelf) {
109
+ const inst = checkCliAvailable(agent)[0];
110
+ const signedIn = inst ? await checkCliSignedIn(agent) : undefined;
111
+ return [d.name, { installed: inst, signedIn }];
112
+ }
113
+ // Remote sign-in stays unknown (see the module docblock); the install
114
+ // gate is what drives the fail-loud.
115
+ return [d.name, { installed: await probeRemoteInstalled(d, agent), signedIn: undefined }];
116
+ })));
117
+ const signals = new Map();
118
+ for (const name of pool) {
119
+ const d = lookup(name);
120
+ const s = d ? stats.get(d.name) : undefined;
121
+ const inst = d ? installed.get(d.name) : undefined;
122
+ if (!s && !inst)
123
+ continue; // fully unknown device — leave it out of the map
124
+ signals.set(name, {
125
+ reachable: s?.reachable,
126
+ headroom: s ? headroom(s) : undefined,
127
+ loadPercent: s?.loadPercent,
128
+ memPercent: s?.memPercent,
129
+ installed: inst?.installed,
130
+ signedIn: inst?.signedIn,
131
+ });
132
+ }
133
+ cache.set(key, { at: now, signals });
134
+ return signals;
135
+ }
@@ -1,3 +1,26 @@
1
+ import type { Headroom } from '../devices/health.js';
2
+ /**
3
+ * Live signal for one pool device, gathered by the caller (SSH probes) and
4
+ * passed into the pure pick. Every field is optional/best-effort: a device with
5
+ * no signal is neither excluded nor preferred — it degrades to the roster-count
6
+ * path. `reachable === false` and `installed === false` are the only two
7
+ * exclusion signals here; `headroom` drives the overload exclusion + the load
8
+ * tier of the rank. See {@link DeviceStats}/{@link headroom} in devices/health.
9
+ */
10
+ export interface DevicePlacementSignal {
11
+ /** SSH probe answered. `false` → excluded (unreachable). undefined → unknown. */
12
+ reachable?: boolean;
13
+ /** Headroom bucket from load+memory. `'loaded'` → excluded (overloaded). */
14
+ headroom?: Headroom;
15
+ /** Normalized CPU load percent (finer rank tiebreak within a headroom tier). */
16
+ loadPercent?: number;
17
+ /** Memory pressure percent (used with loadPercent for the load cost). */
18
+ memPercent?: number;
19
+ /** Requested agent installed on the device. `false` → excluded (can't run). */
20
+ installed?: boolean;
21
+ /** Requested agent signed in (best-effort). Ranks a signed-in device first. */
22
+ signedIn?: boolean;
23
+ }
1
24
  /** Team fields the placement cascade reads (a subset of TeamMeta). */
2
25
  export interface PlacementTeam {
3
26
  devices?: string[];
@@ -14,7 +37,37 @@ export interface PlacementTeam {
14
37
  */
15
38
  export interface PlacementOptions {
16
39
  maxConcurrent?: Record<string, number>;
40
+ /**
41
+ * Live per-device signals (RUSH-2002). When present, the many-device pick
42
+ * filters unreachable/overloaded/not-installed devices and ranks the rest by
43
+ * health + harness + load. Absent → the pick stays a pure roster count.
44
+ */
45
+ signals?: Map<string, DevicePlacementSignal>;
46
+ /** Human label of the requested agent (e.g. `claude@2.1.112`) for the
47
+ * fail-loud message. */
48
+ agentLabel?: string;
49
+ }
50
+ /** Why a device was excluded from the viable set, for the fail-loud message. */
51
+ export type ExclusionReason = 'unreachable' | 'overloaded' | 'capped' | 'not-installed';
52
+ /** A pool device dropped from the auto-pick, with the reason + live detail. */
53
+ export interface ExcludedDevice {
54
+ device: string;
55
+ reason: ExclusionReason;
56
+ /** Present for `capped`: `running/cap`. */
57
+ detail?: string;
17
58
  }
59
+ /**
60
+ * No device in the pool can host the teammate. Carries the per-device reasons so
61
+ * the caller can print exactly why the pool is unusable instead of silently
62
+ * degrading to a local run the user did not ask for.
63
+ */
64
+ export declare class NoViableDeviceError extends Error {
65
+ readonly excluded: ExcludedDevice[];
66
+ readonly agentLabel?: string;
67
+ constructor(excluded: ExcludedDevice[], agentLabel?: string);
68
+ }
69
+ /** Build the user-facing fail-loud message from the per-device reasons. */
70
+ export declare function formatNoViableMessage(excluded: ExcludedDevice[], agentLabel?: string): string;
18
71
  /**
19
72
  * A roster entry the load counter reads — the shape any teammate satisfies
20
73
  * (AgentProcess included). `status` is compared against `'running'` (the
@@ -45,11 +98,31 @@ export declare function cappedDevices(devices: string[], roster: RosterEntry[],
45
98
  * teammate silently landing on a machine its operator capped.
46
99
  */
47
100
  export declare function pickLeastLoaded(devices: string[], roster: RosterEntry[], maxConcurrent?: Record<string, number>): string;
101
+ /**
102
+ * Split the pool into the viable set and the excluded set (with reasons), from
103
+ * the caps + live signals. Pure — the caller decides what to do with an empty
104
+ * viable set. Reasons are checked in a stable order (unreachable → not-installed
105
+ * → overloaded → capped) so a device reports its most fundamental blocker first.
106
+ */
107
+ export declare function classifyExclusions(devices: string[], roster: RosterEntry[], opts?: PlacementOptions): {
108
+ eligible: string[];
109
+ excluded: ExcludedDevice[];
110
+ };
111
+ /**
112
+ * Health-, harness-, and load-aware pick over a pool (RUSH-2002). Filters
113
+ * unreachable / overloaded / capped / not-installed devices, then ranks the
114
+ * survivors by: (a) agent signed in, (b) lower load (headroom tier, then raw
115
+ * load cost), (c) fewer running teammates, ties broken by pool order. Throws
116
+ * {@link NoViableDeviceError} when nothing survives — never returns a local
117
+ * fallback. Pure: all I/O is pre-resolved into `opts.signals`.
118
+ */
119
+ export declare function pickBestDevice(devices: string[], roster: RosterEntry[], opts?: PlacementOptions): string;
48
120
  /**
49
121
  * Resolve where a teammate runs. Returns `{ device: null }` for a local run
50
122
  * (no pin, no pool, or the chosen device is the local machine) and
51
123
  * `{ device: <name> }` for a remote placement. See the cascade in the module
52
- * header.
124
+ * header. Throws {@link NoViableDeviceError} when a required pool has no viable
125
+ * host — the caller surfaces it at `teams start` rather than falling back local.
53
126
  */
54
127
  export declare function resolvePlacement(team: PlacementTeam, explicitDevice: string | null, roster: RosterEntry[], opts?: PlacementOptions): {
55
128
  device: string | null;
@@ -8,19 +8,68 @@
8
8
  *
9
9
  * 1. teammate has an explicit `--device` pin → that device
10
10
  * 2. else the team pool has exactly one device → that device (whole team)
11
- * 3. else the team pool has many devices → least-loaded pick
11
+ * 3. else the team pool has many devices → best-viable pick
12
12
  * 4. else (no pin, no pool) → null == run local
13
13
  *
14
- * Step 3 is cap-aware: a device at its `agents.max-concurrent` cap (from the
15
- * device doc, passed in via PlacementOptions) is excluded from the auto-pick,
16
- * and an all-capped pool fails loud. Pins and pools of one are the user's own
17
- * choice and are never second-guessed.
14
+ * Step 3 is cap-, health-, and harness-aware (RUSH-2002). When the caller
15
+ * supplies live {@link DevicePlacementSignal}s (probed reachability, headroom,
16
+ * load/mem, and whether the requested agent is installed + signed in), the pick:
17
+ * - EXCLUDES an unreachable device, an overloaded one (headroom `loaded`), a
18
+ * device at its `agents.max-concurrent` cap, and one the requested agent is
19
+ * not installed on;
20
+ * - RANKS the survivors by (a) agent installed + signed in, (b) lower load /
21
+ * memory (by headroom tier, then raw), (c) fewer running teammates, ties
22
+ * broken by pool order.
23
+ * With no signals it degrades to the original cap-aware least-loaded pick, so
24
+ * the pure roster-count path (and its tests) are unchanged.
25
+ *
26
+ * When every pool device is excluded, the pick FAILS LOUD ({@link
27
+ * NoViableDeviceError}) naming each device's reason — never a silent fall back
28
+ * to local, since the user asked for a remote pool. Pins are the user's own
29
+ * choice and are never second-guessed; a pool of one is respected for
30
+ * load/cap/reachability but still fails loud when the agent is provably not
31
+ * installed there (running it would be futile).
18
32
  *
19
33
  * A device whose name equals the local machine id is treated as "local" — it
20
34
  * resolves to a null placement so the existing local spawn path runs unchanged,
21
35
  * letting the local machine participate in a pool as just another member.
22
36
  */
23
37
  import { machineId } from '../session/sync/config.js';
38
+ /**
39
+ * No device in the pool can host the teammate. Carries the per-device reasons so
40
+ * the caller can print exactly why the pool is unusable instead of silently
41
+ * degrading to a local run the user did not ask for.
42
+ */
43
+ export class NoViableDeviceError extends Error {
44
+ excluded;
45
+ agentLabel;
46
+ constructor(excluded, agentLabel) {
47
+ super(formatNoViableMessage(excluded, agentLabel));
48
+ this.name = 'NoViableDeviceError';
49
+ this.excluded = excluded;
50
+ this.agentLabel = agentLabel;
51
+ }
52
+ }
53
+ /** Build the user-facing fail-loud message from the per-device reasons. */
54
+ export function formatNoViableMessage(excluded, agentLabel) {
55
+ const anyNotInstalled = excluded.some((e) => e.reason === 'not-installed');
56
+ const agent = agentLabel ?? 'the requested agent';
57
+ const perDevice = excluded
58
+ .map((e) => (e.detail ? `${e.device} (${e.reason} ${e.detail})` : `${e.device} (${e.reason})`))
59
+ .join(', ');
60
+ // When the whole pool lacks the agent, lead with the harness message the
61
+ // ticket specifies; otherwise summarize the mixed reasons.
62
+ const head = anyNotInstalled
63
+ ? `No device in the team pool can run ${agent}.`
64
+ : `No viable device in the team pool for ${agent}.`;
65
+ const anyUnreachable = excluded.some((e) => e.reason === 'unreachable');
66
+ const hint = anyNotInstalled
67
+ ? " Run 'agents devices ping' to see which devices have the agent installed + signed in, or add the agent to a pool device."
68
+ : anyUnreachable
69
+ ? " Add a device to the pool, raise a cap, or wait for the pool to free up / come back online ('agents devices ping')."
70
+ : ' Add a device to the pool, raise a cap, or bring an overloaded box under load.';
71
+ return `${head} ${perDevice}.${hint}`;
72
+ }
24
73
  /** True when `device` names the local machine (case-insensitive). */
25
74
  function isLocalDevice(device) {
26
75
  return device.toLowerCase() === machineId();
@@ -97,14 +146,134 @@ export function pickLeastLoaded(devices, roster, maxConcurrent) {
97
146
  }
98
147
  return best;
99
148
  }
149
+ /** Load cost for a signal: worst of load% and mem%, or undefined when neither
150
+ * was probed. The "how full is this box" number the finer rank tiebreak reads. */
151
+ function loadCost(s) {
152
+ if (!s)
153
+ return undefined;
154
+ const vals = [s.loadPercent, s.memPercent].filter((v) => typeof v === 'number');
155
+ return vals.length ? Math.max(...vals) : undefined;
156
+ }
157
+ /** Rank a headroom bucket into a load TIER (lower is less loaded). An unprobed
158
+ * device sits between `light` and `busy` — preferred over a known-busy box but
159
+ * not over a known-idle one. `loaded` is excluded before ranking, so it never
160
+ * reaches here. */
161
+ function headroomTier(h) {
162
+ switch (h) {
163
+ case 'idle': return 0;
164
+ case 'light': return 1;
165
+ case 'busy': return 3;
166
+ default: return 2; // 'unknown' / undefined
167
+ }
168
+ }
169
+ /**
170
+ * Split the pool into the viable set and the excluded set (with reasons), from
171
+ * the caps + live signals. Pure — the caller decides what to do with an empty
172
+ * viable set. Reasons are checked in a stable order (unreachable → not-installed
173
+ * → overloaded → capped) so a device reports its most fundamental blocker first.
174
+ */
175
+ export function classifyExclusions(devices, roster, opts) {
176
+ const load = loadByDevice(devices, roster);
177
+ const caps = opts?.maxConcurrent ?? {};
178
+ const signals = opts?.signals;
179
+ const eligible = [];
180
+ const excluded = [];
181
+ for (const d of devices) {
182
+ const s = signals?.get(d);
183
+ if (s?.reachable === false) {
184
+ excluded.push({ device: d, reason: 'unreachable' });
185
+ continue;
186
+ }
187
+ if (s?.installed === false) {
188
+ excluded.push({ device: d, reason: 'not-installed' });
189
+ continue;
190
+ }
191
+ if (s?.headroom === 'loaded') {
192
+ excluded.push({ device: d, reason: 'overloaded' });
193
+ continue;
194
+ }
195
+ const cap = caps[d];
196
+ if (cap !== undefined && (load.get(d) ?? 0) >= cap) {
197
+ excluded.push({ device: d, reason: 'capped', detail: `${load.get(d) ?? 0}/${cap}` });
198
+ continue;
199
+ }
200
+ eligible.push(d);
201
+ }
202
+ return { eligible, excluded };
203
+ }
204
+ /**
205
+ * Health-, harness-, and load-aware pick over a pool (RUSH-2002). Filters
206
+ * unreachable / overloaded / capped / not-installed devices, then ranks the
207
+ * survivors by: (a) agent signed in, (b) lower load (headroom tier, then raw
208
+ * load cost), (c) fewer running teammates, ties broken by pool order. Throws
209
+ * {@link NoViableDeviceError} when nothing survives — never returns a local
210
+ * fallback. Pure: all I/O is pre-resolved into `opts.signals`.
211
+ */
212
+ export function pickBestDevice(devices, roster, opts) {
213
+ if (devices.length === 0) {
214
+ throw new Error('pickBestDevice called with an empty device pool');
215
+ }
216
+ const load = loadByDevice(devices, roster);
217
+ const { eligible, excluded } = classifyExclusions(devices, roster, opts);
218
+ if (eligible.length === 0) {
219
+ // A pool excluded ONLY for unreachability is a probe MISS / transient infra
220
+ // blip (a worker went briefly unresponsive during `teams start`), not proof
221
+ // the agent can't RUN there. Per the fail-loud contract — fire only on
222
+ // positive evidence (not-installed / saturated), never on a bare
223
+ // reachability miss — degrade to a best-effort roster-count pick so the wave
224
+ // retries and the real error surfaces at SSH dispatch, instead of a hard
225
+ // exit-1 that strands an all-remote pool on a transient blip.
226
+ const onlyUnreachable = excluded.every((e) => e.reason === 'unreachable');
227
+ if (!onlyUnreachable) {
228
+ throw new NoViableDeviceError(excluded, opts?.agentLabel);
229
+ }
230
+ let fallback = devices[0];
231
+ let fallbackLoad = load.get(fallback) ?? 0;
232
+ for (const d of devices) {
233
+ const l = load.get(d) ?? 0;
234
+ if (l < fallbackLoad) {
235
+ fallback = d;
236
+ fallbackLoad = l;
237
+ }
238
+ }
239
+ return fallback;
240
+ }
241
+ const signals = opts?.signals;
242
+ const order = new Map(devices.map((d, i) => [d, i]));
243
+ // Ascending composite sort — the first element is the best placement.
244
+ return [...eligible].sort((a, b) => {
245
+ const sa = signals?.get(a);
246
+ const sb = signals?.get(b);
247
+ // (a) signed-in agent first.
248
+ const signedIn = (sa?.signedIn === true ? 0 : 1) - (sb?.signedIn === true ? 0 : 1);
249
+ if (signedIn !== 0)
250
+ return signedIn;
251
+ // (b) lower load — coarse headroom tier, then raw load cost.
252
+ const tier = headroomTier(sa?.headroom) - headroomTier(sb?.headroom);
253
+ if (tier !== 0)
254
+ return tier;
255
+ // (c) fewer running teammates.
256
+ const teammates = (load.get(a) ?? 0) - (load.get(b) ?? 0);
257
+ if (teammates !== 0)
258
+ return teammates;
259
+ // finer load tiebreak: a known-lower load wins; unknown sits mid (50).
260
+ const cost = (loadCost(sa) ?? 50) - (loadCost(sb) ?? 50);
261
+ if (cost !== 0)
262
+ return cost;
263
+ // stable: first declared in the pool wins.
264
+ return (order.get(a) ?? 0) - (order.get(b) ?? 0);
265
+ })[0];
266
+ }
100
267
  /**
101
268
  * Resolve where a teammate runs. Returns `{ device: null }` for a local run
102
269
  * (no pin, no pool, or the chosen device is the local machine) and
103
270
  * `{ device: <name> }` for a remote placement. See the cascade in the module
104
- * header.
271
+ * header. Throws {@link NoViableDeviceError} when a required pool has no viable
272
+ * host — the caller surfaces it at `teams start` rather than falling back local.
105
273
  */
106
274
  export function resolvePlacement(team, explicitDevice, roster, opts) {
107
- // 1. Explicit pin wins — even without a pool.
275
+ // 1. Explicit pin wins — even without a pool — and is never second-guessed
276
+ // (the remote `agents run` surfaces any install/health issue there).
108
277
  if (explicitDevice) {
109
278
  return { device: isLocalDevice(explicitDevice) ? null : explicitDevice };
110
279
  }
@@ -112,11 +281,19 @@ export function resolvePlacement(team, explicitDevice, roster, opts) {
112
281
  // 4. No pool → local, exactly like today.
113
282
  if (pool.length === 0)
114
283
  return { device: null };
115
- // 2. Pool of one → the whole team runs there.
284
+ // 2. Pool of one → the whole team runs there. Respect the choice for
285
+ // load/cap/reachability, but still fail loud when the agent is provably
286
+ // NOT installed there — running it would be futile.
116
287
  if (pool.length === 1) {
288
+ if (opts?.signals?.get(pool[0])?.installed === false) {
289
+ throw new NoViableDeviceError([{ device: pool[0], reason: 'not-installed' }], opts.agentLabel);
290
+ }
117
291
  return { device: isLocalDevice(pool[0]) ? null : pool[0] };
118
292
  }
119
- // 3. Many → least-loaded across the pool (cap-aware when caps are provided).
120
- const picked = pickLeastLoaded(pool, roster, opts?.maxConcurrent);
293
+ // 3. Many → best viable pick. With live signals, this is health-, harness-,
294
+ // and load-aware; without them it degrades to the cap-aware roster count.
295
+ const picked = opts?.signals
296
+ ? pickBestDevice(pool, roster, opts)
297
+ : pickLeastLoaded(pool, roster, opts?.maxConcurrent);
121
298
  return { device: isLocalDevice(picked) ? null : picked };
122
299
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.22.25",
3
+ "version": "1.22.26",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",