@phnx-labs/agents-cli 1.23.37 → 1.23.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.39
4
+
5
+ - **`agents run --device auto` places from a snapshot instead of probing the fleet on every launch.** Each placement probe's load stats and readiness answer are now kept in `~/.agents/.cache/.fleet-stats.json`, and the daemon's `device-probe` tick refreshes them every 3 minutes while placement was used in the last day. A launch uses a device's entry when it is at most 5 minutes old and probes live only the devices whose entry is missing or older (stats and readiness now in parallel). The picked device is confirmed with one `ssh … true` that the dispatch then reuses, and `ensureHostReady` reads the same fresh entry instead of its own `agents view` round trip. On yosemite-s1 a headless `--device auto` launch reached its dispatch ssh in 0.6 to 0.9 s instead of 6.1 s. A pick that no longer answers is marked and the next best is taken; when only the snapshot says no device is ready, placement probes live before refusing. Source: cli/src/lib/teams/placement-probe.ts, cli/src/lib/devices/stats-cache.ts, cli/src/lib/hosts/ready.ts, cli/src/lib/smart-launch.ts, cli/src/lib/daemon/device-probe-service.ts
6
+ - **Picking an account no longer checks every stored credential one at a time.** The run checked whether each registry account's secret was present with one synchronous `secrets` process per account, about 70 ms each on Linux and far more through the macOS keychain. It now checks only the accounts that can serve the harness, all at once. Account selection for `agents run claude --local` went from 1.5 s to 0.2 s on yosemite-s1. The banner for a pick without a recent usage reading now says `usage unverified — no recent usage reading`; nothing was being refreshed. Source: cli/src/lib/accounting/account-pool-collect.ts, cli/src/commands/exec.ts
7
+ - **`agents run` names each slow step as it starts.** On a terminal, stderr shows one dim line before placement (`Placing on the fleet…`), account selection (`Picking an account…`), the harness check (`Starting claude@2.1.261…`) and a remote start (`Starting on yosemite-m5…`). Nothing is printed with `--json`, `--quiet`, or when stderr is not a terminal. Source: cli/src/commands/exec.ts
8
+
9
+ - **The daemon no longer floods a busy Mac with `ps`.** Scans that asked for the process table while a read was still running each started their own `ps -A`. On a loaded machine a `ps -A` takes seconds, so they piled up: zion had 74 running at once from one daemon, with a load average near 40, and every editor, panel and terminal on it slowed down. Callers now share the read in flight, so there is at most one `ps -A` at a time. Source: cli/src/lib/session/active.ts
10
+
11
+ ## 1.23.38
12
+
13
+ - **The Lead can say what moved today (PHNX-4432).** Its tools now print dates. `agents lead tool linear tasks` lists the most recently updated tickets first, each with its age, cut to `--limit` and with a count of older ones (`linear tasks --json` sorts by priority and returns every match, so a done list started with tickets from August). `prs list` and the roster add when each PR was updated, and when each session started and was last active. The brief now keeps the merged and closed PRs among the 40 most recently updated, with their age, under "Merged or closed lately". Before this, "what happened in the last 24 hours" got "none of my tools show history". Source: cli/src/lib/lead/tools.ts, cli/src/lib/lead/brief.ts, cli/src/lib/lead/roster.ts
14
+
3
15
  ## 1.23.37
4
16
 
5
17
  - **A headless run an agent starts no longer takes over that agent's tab.** When a Claude session in an editor tab ran `claude -p` through its shell, the SessionStart hook walked up to the tab agent's `~/.agents/.cache/terminals/by-pid/<pid>.json` and rewrote its session id, so `agents ps`, the feed and the editor showed the tab as the one-second headless run (observed on yosemite-s0 for a zion tab, 2026-10-19). A by-pid entry now yields to the session its own process recorded at SessionStart (`state/sessions/<pid>.json`), which only that process writes, so the tab, its launch id and `agents message` resolve to the real session again, including for entries an older hook already rewrote. Source: cli/src/lib/session/pid-registry.ts, cli/src/lib/session/hook-sessions.ts
@@ -129,6 +129,10 @@ export declare function runAutoDefaultsToAffinity(options: {
129
129
  local?: boolean;
130
130
  }, env?: NodeJS.ProcessEnv): boolean;
131
131
  export declare function hostInteractiveNeedsCorrelationId(runAgent: string, hostSessionId: string | undefined, resumeId: string | undefined): boolean;
132
+ export declare function runStageLine(text: string, opts: {
133
+ json?: boolean;
134
+ quiet?: boolean;
135
+ }, stderrIsTty?: boolean): string | null;
132
136
  export declare function isInsideGitWorkTree(cwd: string): boolean;
133
137
  export declare function gitToplevel(cwd: string): string | null;
134
138
  export declare function computeNetMode(opts: {
@@ -122,11 +122,19 @@ export function hostInteractiveNeedsCorrelationId(runAgent, hostSessionId, resum
122
122
  return true;
123
123
  return !hostSessionId && isSessionTrackedAgent(runAgent);
124
124
  }
125
+ export function runStageLine(text, opts, stderrIsTty = Boolean(process.stderr.isTTY)) {
126
+ return stderrIsTty && !opts.json && !opts.quiet ? chalk.dim(`${text}\n`) : null;
127
+ }
128
+ function writeRunStage(text, opts) {
129
+ const line = runStageLine(text, opts);
130
+ if (line)
131
+ process.stderr.write(line);
132
+ }
125
133
  function formatRotationBanner(result, verb = 'balanced') {
126
134
  const { picked, healthy, excluded } = result;
127
135
  const label = picked.email ? `${picked.email} · ${picked.agent}@${picked.version}` : `${picked.agent}@${picked.version}`;
128
136
  const ratio = `${healthy.length} of ${healthy.length + excluded.length} healthy`;
129
- const caveat = result.usageUnverified ? ', usage unverified — no account could be refreshed' : '';
137
+ const caveat = result.usageUnverified ? ', usage unverified — no recent usage reading' : '';
130
138
  return `[agents] ${verb} picked ${label} (${ratio}${caveat})`;
131
139
  }
132
140
  export function isInsideGitWorkTree(cwd) {
@@ -944,6 +952,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
944
952
  const { applyDeviceAutoToOptions } = await import('../lib/smart-launch.js');
945
953
  const result = await applyDeviceAutoToOptions(options, {
946
954
  accountPickerRequested,
955
+ onPlacing: () => writeRunStage('Placing on the fleet…', options),
947
956
  agent: normalizedAgentSpec.split('#')[0].split('@')[0] === RUN_AUTO_KEYWORD
948
957
  ? undefined
949
958
  : (resolveAgentName(normalizedAgentSpec.split('#')[0].split('@')[0]) ?? undefined),
@@ -1350,6 +1359,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
1350
1359
  process.stderr.write(chalk.gray(started));
1351
1360
  }
1352
1361
  }
1362
+ writeRunStage(`Starting on ${host.name}…`, options);
1353
1363
  const exitCode = await runInteractiveOnHost(host, {
1354
1364
  agent: runAgent,
1355
1365
  version: resumeId ? undefined : runVersion,
@@ -1432,6 +1442,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
1432
1442
  if (process.env.AGENTS_DISPATCH_DEBUG || options.verbose) {
1433
1443
  process.stderr.write(chalk.gray(`[hosts] dispatch headless ${runAgent}${runVersion ? `@${runVersion}` : ''} -> ${host.name}\n`));
1434
1444
  }
1445
+ writeRunStage(`Starting on ${host.name}…`, options);
1435
1446
  const { task, exitCode } = await dispatchPromptToHost(host, {
1436
1447
  agent: runAgent,
1437
1448
  version: resumeId ? undefined : runVersion,
@@ -2041,6 +2052,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
2041
2052
  else {
2042
2053
  try {
2043
2054
  const { collectRunCandidatesForRun } = await import('../lib/accounting/account-pool-collect.js');
2055
+ writeRunStage('Picking an account…', options);
2044
2056
  bootMark('resolve-version:start');
2045
2057
  const routingModel = options.model ?? resolvedResumeSource?.model ?? workflowModel
2046
2058
  ?? (options.fallback ? undefined : resolveRunDefaults(agent, resolveVersion(agent, cwd), cwd).model);
@@ -2158,6 +2170,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
2158
2170
  {
2159
2171
  const launchTarget = version ?? resolveVersion(agent, cwd) ?? undefined;
2160
2172
  if (launchTarget) {
2173
+ writeRunStage(`Starting ${agent}@${launchTarget}…`, options);
2161
2174
  const healed = await ensureAgentRunnable(agent, launchTarget, options.quiet ? undefined : (m) => process.stderr.write(chalk.yellow(`[agents] ${m}\n`)));
2162
2175
  if (healed === null) {
2163
2176
  const { isVersionIsolated } = await import('../lib/installations/versions.js');
@@ -1,6 +1,7 @@
1
1
  import type { AgentId } from '../types.js';
2
2
  import { type RotateCandidate } from './rotate.js';
3
3
  import { type RegistryAccountRecord } from './account-pool.js';
4
+ export declare function localRegistryRecords(agent: AgentId, includeKeyed?: boolean): Promise<RegistryAccountRecord[]>;
4
5
  export interface RunCandidateInputs {
5
6
  native: RotateCandidate[];
6
7
  records: RegistryAccountRecord[];
@@ -1,12 +1,15 @@
1
1
  import { readAccountRegistry } from '../account-registry.js';
2
- import { hasKeychainTokenSync, isSecretsTransportError } from '../secrets-client.js';
2
+ import { hasKeychainToken, isSecretsTransportError } from '../secrets-client.js';
3
3
  import { getGlobalDefault, listInstalledVersions } from '../installations/versions.js';
4
4
  import { collectRunCandidates } from './rotate.js';
5
- import { registryPoolCandidates } from './account-pool.js';
6
- function localRegistryRecords() {
5
+ import { registryAccountServesHarness, registryPoolCandidates } from './account-pool.js';
6
+ export async function localRegistryRecords(agent, includeKeyed = false) {
7
7
  try {
8
- return Object.values(readAccountRegistry().accounts)
9
- .filter((a) => hasKeychainTokenSync(a.secretRef))
8
+ const accounts = Object.values(readAccountRegistry().accounts)
9
+ .filter((a) => registryAccountServesHarness(a, agent, includeKeyed));
10
+ const present = await Promise.all(accounts.map((a) => hasKeychainToken(a.secretRef)));
11
+ return accounts
12
+ .filter((_, i) => present[i])
10
13
  .map((a) => ({ id: a.id, name: a.name, provider: a.provider, auth: a.auth, secretPresent: true }));
11
14
  }
12
15
  catch (err) {
@@ -43,7 +46,10 @@ export function foldRegistryCandidates(agent, inputs, includeKeyed = false) {
43
46
  return [...native, ...extra];
44
47
  }
45
48
  export async function collectRunCandidatesForRun(agent, includeKeyed = false) {
46
- const native = await collectRunCandidates(agent);
47
49
  const runVersion = getGlobalDefault(agent) ?? listInstalledVersions(agent)[0];
48
- return foldRegistryCandidates(agent, { native, records: localRegistryRecords(), runVersion }, includeKeyed);
50
+ const [native, records] = await Promise.all([
51
+ collectRunCandidates(agent),
52
+ runVersion ? localRegistryRecords(agent, includeKeyed) : Promise.resolve([]),
53
+ ]);
54
+ return foldRegistryCandidates(agent, { native, records, runVersion }, includeKeyed);
49
55
  }
@@ -16,5 +16,6 @@ interface RegistryAccountInput {
16
16
  auth: AccountAuthKind;
17
17
  secretPresent: boolean;
18
18
  }
19
+ export declare function registryAccountServesHarness(record: Pick<RegistryAccountRecord, 'provider' | 'auth'>, agent: AgentId, includeKeyed?: boolean): boolean;
19
20
  export declare function registryPoolCandidates(records: RegistryAccountRecord[], agent: AgentId, includeKeyed?: boolean): RegistryAccountInput[];
20
21
  export {};
@@ -1,10 +1,11 @@
1
1
  import { providerAuthenticatesHarness } from '../account-provider-registry.js';
2
+ export function registryAccountServesHarness(record, agent, includeKeyed = false) {
3
+ return (record.auth === 'setup-token' || includeKeyed) && providerAuthenticatesHarness(record.provider, record.auth, agent);
4
+ }
2
5
  export function registryPoolCandidates(records, agent, includeKeyed = false) {
3
6
  const out = [];
4
7
  for (const r of records) {
5
- if (r.auth !== 'setup-token' && !includeKeyed)
6
- continue;
7
- if (!providerAuthenticatesHarness(r.provider, r.auth, agent))
8
+ if (!registryAccountServesHarness(r, agent, includeKeyed))
8
9
  continue;
9
10
  out.push({
10
11
  id: r.id,
@@ -10,6 +10,14 @@ export class DeviceProbeService extends BasePeriodicService {
10
10
  async onStop() {
11
11
  }
12
12
  async onTick(ctx) {
13
+ const { listOnlineDeviceNames } = await import('../smart-launch.js');
14
+ const { refreshPlacementSnapshot } = await import('../teams/placement-probe.js');
15
+ const refreshed = await refreshPlacementSnapshot(listOnlineDeviceNames()).catch((err) => {
16
+ ctx.log('WARN', `placement snapshot refresh failed: ${err.message}`);
17
+ return null;
18
+ });
19
+ if (refreshed !== null)
20
+ ctx.log('DEBUG', `placement snapshot: probed ${refreshed} device(s)`);
13
21
  const { runDeviceSync } = await import('../devices/sync.js');
14
22
  const { reconcilePendingSentinels, pruneDismissedPendingSentinels } = await import('../devices/pending.js');
15
23
  const dev = await runDeviceSync({ soft: true, mode: 'refresh' });
@@ -33,7 +33,7 @@ export const DAEMON_SERVICES = [
33
33
  {
34
34
  id: 'device-probe',
35
35
  title: 'Device probe',
36
- description: 'Discovers Tailscale devices and surfaces pending ones for registration.',
36
+ description: 'Discovers Tailscale devices and surfaces pending ones for registration, and keeps the placement snapshot `--device auto` reads current while placement was used in the last day.',
37
37
  },
38
38
  {
39
39
  id: 'state-dir-check',
@@ -3,10 +3,33 @@ import type { DeviceProfile } from './registry.js';
3
3
  export declare const STATS_STALE_MS: number;
4
4
  export declare function isFreshDeviceStats(stats: DeviceStats, now?: number): boolean;
5
5
  export declare function retainHardwareFacts(probed: DeviceStats, prior: DeviceStats | undefined): DeviceStats;
6
+ export declare const PLACEMENT_SNAPSHOT_MAX_AGE_MS: number;
7
+ export declare const PLACEMENT_DEMAND_WINDOW_MS: number;
8
+ export interface ReadyProbeEntry {
9
+ answered: boolean;
10
+ timedOut?: boolean;
11
+ version: string | null;
12
+ view: string;
13
+ fetchedAt: number;
14
+ }
15
+ export interface PlacementSnapshot {
16
+ stats: Record<string, DeviceStats>;
17
+ readiness: Record<string, ReadyProbeEntry>;
18
+ demandAt?: number;
19
+ }
6
20
  export declare function readStatsCache(): Record<string, DeviceStats>;
7
21
  export declare function writeStatsCache(entries: Record<string, DeviceStats>): void;
22
+ export declare function readPlacementSnapshot(): PlacementSnapshot;
23
+ export declare function writePlacementSnapshot(update: {
24
+ stats?: Record<string, DeviceStats>;
25
+ readiness?: Record<string, ReadyProbeEntry>;
26
+ demandAt?: number;
27
+ }): void;
28
+ export declare function freshReadyProbe(snapshot: PlacementSnapshot, name: string, now?: number): ReadyProbeEntry | undefined;
29
+ export declare function freshSnapshotStats(snapshot: PlacementSnapshot, name: string, now?: number): DeviceStats | undefined;
30
+ export declare function placementDemandIsRecent(snapshot: PlacementSnapshot, now?: number): boolean;
8
31
  export declare function removeStatsCacheEntry(name: string): void;
9
- export declare function pruneStatsCache(entries: Record<string, DeviceStats>, name: string): Record<string, DeviceStats>;
32
+ export declare function pruneStatsCache<T>(entries: Record<string, T>, name: string): Record<string, T>;
10
33
  interface FleetStatsResult {
11
34
  stats: Map<string, DeviceStats>;
12
35
  oldestFetchedAt: number | null;
@@ -26,43 +26,77 @@ export function retainHardwareFacts(probed, prior) {
26
26
  specsFetchedAt: prior.specsFetchedAt ?? prior.fetchedAt,
27
27
  };
28
28
  }
29
+ export const PLACEMENT_SNAPSHOT_MAX_AGE_MS = 5 * 60_000;
30
+ export const PLACEMENT_DEMAND_WINDOW_MS = 24 * 60 * 60_000;
29
31
  function cacheFilePath() {
30
32
  return path.join(getCacheDir(), CACHE_FILE);
31
33
  }
32
- export function readStatsCache() {
34
+ function readCacheFile() {
33
35
  try {
34
36
  const parsed = JSON.parse(fs.readFileSync(cacheFilePath(), 'utf-8'));
35
37
  if (parsed && parsed.entries && typeof parsed.entries === 'object')
36
- return parsed.entries;
38
+ return parsed;
37
39
  }
38
40
  catch {
39
41
  }
40
- return {};
42
+ return { version: 1, entries: {} };
41
43
  }
42
- export function writeStatsCache(entries) {
44
+ function updateCacheFile(update) {
43
45
  try {
44
46
  const dir = getCacheDir();
45
47
  if (!fs.existsSync(dir))
46
48
  fs.mkdirSync(dir, { recursive: true });
47
- const merged = {
48
- version: 1,
49
- entries: { ...readStatsCache(), ...entries },
50
- };
51
- fs.writeFileSync(cacheFilePath(), JSON.stringify(merged, null, 2));
49
+ const file = cacheFilePath();
50
+ const tmp = `${file}.${process.pid}.tmp`;
51
+ try {
52
+ fs.writeFileSync(tmp, JSON.stringify(update(readCacheFile()), null, 2));
53
+ fs.renameSync(tmp, file);
54
+ }
55
+ finally {
56
+ fs.rmSync(tmp, { force: true });
57
+ }
52
58
  }
53
59
  catch {
54
60
  }
55
61
  }
62
+ export function readStatsCache() {
63
+ return readCacheFile().entries;
64
+ }
65
+ export function writeStatsCache(entries) {
66
+ updateCacheFile((current) => ({ ...current, entries: { ...current.entries, ...entries } }));
67
+ }
68
+ export function readPlacementSnapshot() {
69
+ const file = readCacheFile();
70
+ return { stats: file.entries, readiness: file.readiness ?? {}, demandAt: file.placementDemandAt };
71
+ }
72
+ export function writePlacementSnapshot(update) {
73
+ updateCacheFile((current) => ({
74
+ ...current,
75
+ entries: { ...current.entries, ...update.stats },
76
+ readiness: { ...current.readiness, ...update.readiness },
77
+ placementDemandAt: update.demandAt ?? current.placementDemandAt,
78
+ }));
79
+ }
80
+ export function freshReadyProbe(snapshot, name, now = Date.now()) {
81
+ const entry = snapshot.readiness[name];
82
+ return entry && now - entry.fetchedAt <= PLACEMENT_SNAPSHOT_MAX_AGE_MS ? entry : undefined;
83
+ }
84
+ export function freshSnapshotStats(snapshot, name, now = Date.now()) {
85
+ const stats = snapshot.stats[name];
86
+ return stats && now - stats.fetchedAt <= PLACEMENT_SNAPSHOT_MAX_AGE_MS ? stats : undefined;
87
+ }
88
+ export function placementDemandIsRecent(snapshot, now = Date.now()) {
89
+ return snapshot.demandAt !== undefined && now - snapshot.demandAt <= PLACEMENT_DEMAND_WINDOW_MS;
90
+ }
56
91
  export function removeStatsCacheEntry(name) {
57
- try {
58
- const current = readStatsCache();
59
- if (!(name in current))
60
- return;
61
- const entries = pruneStatsCache(current, name);
62
- fs.writeFileSync(cacheFilePath(), JSON.stringify({ version: 1, entries }, null, 2));
63
- }
64
- catch {
65
- }
92
+ const current = readCacheFile();
93
+ if (!(name in current.entries) && !(current.readiness && name in current.readiness))
94
+ return;
95
+ updateCacheFile((file) => ({
96
+ ...file,
97
+ entries: pruneStatsCache(file.entries, name),
98
+ readiness: file.readiness ? pruneStatsCache(file.readiness, name) : undefined,
99
+ }));
66
100
  }
67
101
  export function pruneStatsCache(entries, name) {
68
102
  const { [name]: _removed, ...remaining } = entries;
@@ -17,7 +17,7 @@ interface WorkerPickOptions {
17
17
  platforms?: string[];
18
18
  eligibleHosts?: string[];
19
19
  localMachine?: string;
20
- probe?: (pool: string[]) => Promise<Map<string, DevicePlacementSignal>>;
20
+ probe?: (pool: string[], force?: boolean) => Promise<Map<string, DevicePlacementSignal>>;
21
21
  preferred?: ReadonlySet<string>;
22
22
  }
23
23
  export declare function resolveWorkerDevice(opts?: WorkerPickOptions): Promise<WorkerPickPlan>;
@@ -32,7 +32,11 @@ export async function resolveWorkerDevice(opts = {}) {
32
32
  });
33
33
  if (onPlatform.length === 0)
34
34
  throw new Error(formatNoWorkerError(excluded, wanted));
35
- const signals = await (opts.probe ?? ((p) => probePoolSignals(p)))(onPlatform);
35
+ const probe = opts.probe ?? ((p, force) => probePoolSignals(p, undefined, { force }));
36
+ let signals = await probe(onPlatform);
37
+ if (!onPlatform.some((device) => isWorkerEligible(signals.get(device))) && [...signals.values()].some((s) => s.fromSnapshot)) {
38
+ signals = await probe(onPlatform, true);
39
+ }
36
40
  const eligible = onPlatform.filter((device) => {
37
41
  const signal = signals.get(device);
38
42
  if (signal?.reachable !== true) {
@@ -60,6 +64,9 @@ export async function resolveWorkerDevice(opts = {}) {
60
64
  excluded,
61
65
  };
62
66
  }
67
+ function isWorkerEligible(signal) {
68
+ return signal?.reachable === true && !blocksPlacement(signal.headroom);
69
+ }
63
70
  export function formatNoWorkerError(excluded, platforms) {
64
71
  const detail = excluded.length
65
72
  ? excluded.map((e) => `${e.device} (${e.reason})`).join(', ')
@@ -17,6 +17,9 @@ export declare function buildReadyProbeCommand(os?: string, opts?: {
17
17
  ingestUsage?: boolean;
18
18
  }): string;
19
19
  export declare function readyProbe(target: string, os?: string, extraSshArgs?: string[]): ReadyProbe;
20
+ export declare const HOST_CONFIRM_TIMEOUT_MS = 5000;
21
+ export declare function hostAnswers(host: Host, timeoutMs?: number): boolean;
22
+ export declare function compactReadyView(view: string): string;
20
23
  export declare function parseReadyProbe(stdout: string): ReadyProbe;
21
24
  export declare function viewHasAgent(view: string, agent: string): boolean;
22
25
  export declare function isConcreteVersionPin(version?: string | null): boolean;
@@ -7,6 +7,7 @@ import { remoteShellFor, buildWindowsAgentsCommand, encodePowershell, powershell
7
7
  import { resolveRemoteOsSync } from './remote-os.js';
8
8
  import { AUTH_PROBE_MAX_AGE_MS, isDeadVerdict } from '../auth-health.js';
9
9
  import { USAGE_STALE_REFUSAL_MAX_AGE_MS } from '../accounting/rotate.js';
10
+ import { freshReadyProbe, readPlacementSnapshot } from '../devices/stats-cache.js';
10
11
  export function localCliVersion() {
11
12
  let dir = path.dirname(fileURLToPath(import.meta.url));
12
13
  for (let i = 0; i < 8; i++) {
@@ -79,6 +80,38 @@ export function readyProbe(target, os, extraSshArgs) {
79
80
  return { reachable: false, version: null, view: '', timedOut: true };
80
81
  return parseReadyProbe(r.stdout);
81
82
  }
83
+ export const HOST_CONFIRM_TIMEOUT_MS = 5_000;
84
+ export function hostAnswers(host, timeoutMs = HOST_CONFIRM_TIMEOUT_MS) {
85
+ return sshExec(sshTargetFor(host), 'true', { timeoutMs, extraSshArgs: hostIdentityArgs(host) }).code === 0;
86
+ }
87
+ export function compactReadyView(view) {
88
+ let rows;
89
+ try {
90
+ rows = JSON.parse(view);
91
+ }
92
+ catch {
93
+ return view;
94
+ }
95
+ if (!Array.isArray(rows))
96
+ return view;
97
+ return JSON.stringify(rows.map((row) => ({
98
+ agent: row?.agent,
99
+ runReady: row?.runReady && {
100
+ ready: row.runReady.ready,
101
+ reason: row.runReady.reason,
102
+ accounts: (row.runReady.accounts ?? []).map((a) => ({ ready: a.ready, reason: a.reason })),
103
+ },
104
+ versions: (row?.versions ?? []).map((v) => ({
105
+ version: v.version,
106
+ signedIn: v.signedIn,
107
+ launchable: v.launchable,
108
+ authVerdict: v.authVerdict,
109
+ authCheckedAt: v.authCheckedAt,
110
+ usageStatus: v.usageStatus,
111
+ usageCapturedAt: v.usageCapturedAt,
112
+ })),
113
+ })));
114
+ }
82
115
  export function parseReadyProbe(stdout) {
83
116
  const idx = stdout.indexOf(READY_MARKER);
84
117
  if (idx === -1)
@@ -232,9 +265,16 @@ export function evaluateHostAgentInstall(view, opts, hostName) {
232
265
  }
233
266
  return { warnings };
234
267
  }
268
+ function snapshotReadyProbe(host) {
269
+ const entry = freshReadyProbe(readPlacementSnapshot(), host.name);
270
+ if (!entry?.answered || !entry.version || !hostAnswers(host))
271
+ return undefined;
272
+ return { reachable: true, version: entry.version, view: entry.view };
273
+ }
235
274
  export function ensureHostReady(host, opts) {
236
275
  const target = sshTargetFor(host);
237
- const probe = readyProbe(target, host.os ?? resolveRemoteOsSync(host.name), hostIdentityArgs(host));
276
+ const probe = snapshotReadyProbe(host)
277
+ ?? readyProbe(target, host.os ?? resolveRemoteOsSync(host.name), hostIdentityArgs(host));
238
278
  if (probe.timedOut) {
239
279
  throw new Error(`Host "${host.name}" (${target}) did not respond in time — the SSH probe timed out after 20 seconds. ` +
240
280
  `The host may be slow to start a login shell (nvm/sdkman init, cold node startup). ` +
@@ -13,6 +13,9 @@ export interface BriefPr {
13
13
  url: string;
14
14
  draft: boolean;
15
15
  open: boolean;
16
+ updatedAt?: string;
17
+ mergedAt?: string;
18
+ closedAt?: string;
16
19
  }
17
20
  export interface BriefInputs {
18
21
  project: string;
@@ -36,7 +39,7 @@ export declare function fetchRecentPrs(repo: string | undefined, cwd: string | u
36
39
  export declare function linearTeamKey(home: string): string | undefined;
37
40
  export declare function quoteNotes(memory: string): string;
38
41
  export declare function projectRepo(def: ProjectDef): string | undefined;
39
- export declare function buildBrief(inputs: BriefInputs): string;
42
+ export declare function buildBrief(inputs: BriefInputs, nowMs?: number): string;
40
43
  export declare function briefSummary(inputs: BriefInputs): string[];
41
44
  export declare function fleetLine(rows: Array<{
42
45
  status: string;
@@ -2,16 +2,16 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { execFile } from 'node:child_process';
4
4
  import { createHash } from 'node:crypto';
5
- import { formatRosterRow } from './roster.js';
5
+ import { ago, formatRosterRow } from './roster.js';
6
6
  export const BRIEF_FETCH_TIMEOUT_MS = 8_000;
7
7
  const DIGEST_MAX_CHARS = 2_500;
8
8
  export const LEAD_RULES = [
9
9
  'You are the Lead for this project: one long-lived agent the owner talks or types to. You dispatch and manage coding agents; you never edit files.',
10
10
  'Your only tools are these shell commands, each run on its own (no pipes, ;, &&, redirects or $(...); those are denied):',
11
- ' `agents lead tool roster [--project <name>]` lists live sessions from the live feed. It is the only way to see sessions.',
11
+ ' `agents lead tool roster [--project <name>]` lists live sessions from the live feed, each with when it started and was last active. It is the only way to see sessions.',
12
12
  ' `agents lead tool attention` lists every open ask across the fleet (question, choices, its key). It is the only way to see what agents are asking.',
13
- ' `agents lead tool prs list [--repo <owner/repo>]` lists this project\'s open PRs.',
14
- ' `agents lead tool linear tasks [--status open|todo|progress|backlog|done]`, `agents lead tool linear view <ID>`, `agents lead tool linear create --title <title> [--description <text>]`.',
13
+ ' `agents lead tool prs list [--repo <owner/repo>]` lists this project\'s open PRs, each with when it was last updated.',
14
+ ' `agents lead tool linear tasks [--status open|todo|progress|backlog|done] [--limit 1-50]` (most recently updated first, each with its age), `agents lead tool linear view <ID>`, `agents lead tool linear create --title <title> [--description <text>]`.',
15
15
  'These queue one action for the owner\'s Confirm and never act themselves:',
16
16
  ' `agents lead tool answer --key <key> (--choice <id> | --text <answer>)` answers an open ask from the attention tool.',
17
17
  ' `agents lead tool send --session <id> -- <text>` types a message into a running session of this project (no slash commands).',
@@ -89,7 +89,12 @@ export async function fetchRecentPrs(repo, cwd) {
89
89
  if (!repo)
90
90
  throw new Error('project has no GitHub repo');
91
91
  const raw = JSON.parse(await run('gh', ['api', `repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=40`], cwd));
92
- return raw.map((p) => ({ number: p.number, title: p.title, url: p.html_url, draft: p.draft === true, open: p.state === 'open' }));
92
+ return raw.map((p) => ({
93
+ number: p.number, title: p.title, url: p.html_url, draft: p.draft === true, open: p.state === 'open',
94
+ ...(p.updated_at ? { updatedAt: p.updated_at } : {}),
95
+ ...(p.merged_at ? { mergedAt: p.merged_at } : {}),
96
+ ...(p.closed_at ? { closedAt: p.closed_at } : {}),
97
+ }));
93
98
  }
94
99
  export function linearTeamKey(home) {
95
100
  let raw;
@@ -113,7 +118,7 @@ export function quoteNotes(memory) {
113
118
  export function projectRepo(def) {
114
119
  return def.repo ?? def.repos?.[0]?.slug;
115
120
  }
116
- export function buildBrief(inputs) {
121
+ export function buildBrief(inputs, nowMs = Date.now()) {
117
122
  const { def } = inputs;
118
123
  const out = [];
119
124
  out.push(`# Lead brief: ${inputs.project}`);
@@ -128,7 +133,7 @@ export function buildBrief(inputs) {
128
133
  if (inputs.agentsDigest)
129
134
  out.push('', '## AGENTS.md digest', inputs.agentsDigest);
130
135
  const rows = Object.values(inputs.roster);
131
- out.push('', `## Live sessions (${rows.length})`, ...(rows.length ? rows.map(formatRosterRow) : ['None.']), inputs.fleet);
136
+ out.push('', `## Live sessions (${rows.length})`, ...(rows.length ? rows.map((r) => formatRosterRow(r, nowMs)) : ['None.']), inputs.fleet);
132
137
  out.push('', '## Open tickets');
133
138
  if ('error' in inputs.tickets)
134
139
  out.push(`Unavailable: ${inputs.tickets.error}`);
@@ -143,7 +148,12 @@ export function buildBrief(inputs) {
143
148
  else if (open.length === 0)
144
149
  out.push('None.');
145
150
  else
146
- out.push(...open.map((p) => `- #${p.number} ${p.title}${p.draft ? ' (draft)' : ''}`));
151
+ out.push(...open.map((p) => `- #${p.number} ${p.title}${p.draft ? ' (draft)' : ''}${p.updatedAt ? ` · updated ${ago(p.updatedAt, nowMs)}` : ''}`));
152
+ const ended = 'error' in inputs.prs ? [] : inputs.prs.filter((p) => !p.open);
153
+ if (ended.length) {
154
+ out.push('', `## Merged or closed lately (as of ${new Date(nowMs).toISOString()})`);
155
+ out.push(...ended.map((p) => `- #${p.number} ${p.title} · ${p.mergedAt ? `merged ${ago(p.mergedAt, nowMs)}` : `closed without merging ${p.closedAt ? ago(p.closedAt, nowMs) : ''}`.trimEnd()}`));
156
+ }
147
157
  out.push('', '## Memory', quoteNotes(inputs.memory));
148
158
  return out.join('\n');
149
159
  }
@@ -307,7 +307,7 @@ export class LeadHost {
307
307
  if (!this.roster.ready)
308
308
  throw new Error('The live feed is not connected yet; try again in a few seconds.');
309
309
  const rows = Object.values(this.projectRoster(project));
310
- const lines = rows.length ? rows.map(formatRosterRow) : [`No live sessions for ${project}.`];
310
+ const lines = rows.length ? rows.map((r) => formatRosterRow(r, Date.now())) : [`No live sessions for ${project}.`];
311
311
  return { type: 'roster', text: [`Live sessions for ${project} (${rows.length}):`, ...lines, this.fleetSummary()].join('\n') };
312
312
  }
313
313
  resolveReply(session) {
@@ -6,6 +6,8 @@ export interface RosterRow {
6
6
  project?: string;
7
7
  cwd?: string;
8
8
  ticket?: string;
9
+ startedAtMs?: number;
10
+ lastActivityMs?: number;
9
11
  }
10
12
  export type RosterSnapshot = Record<string, RosterRow>;
11
13
  export interface LeadAttention {
@@ -38,7 +40,8 @@ export declare class FeedRoster {
38
40
  private scopeRows;
39
41
  }
40
42
  export declare function filterProject(snapshot: RosterSnapshot, project: string, projectForCwd: (cwd: string | undefined) => string | undefined, exclude?: ReadonlySet<string>): RosterSnapshot;
41
- export declare function formatRosterRow(row: RosterRow): string;
42
- export declare function rosterDelta(prev: RosterSnapshot | null, cur: RosterSnapshot): string[];
43
+ export declare function formatRosterRow(row: RosterRow, nowMs: number): string;
44
+ export declare function rosterDelta(prev: RosterSnapshot | null, cur: RosterSnapshot, nowMs?: number): string[];
45
+ export declare function ago(at: string | number, nowMs: number): string;
43
46
  export declare function formatAttention(ask: LeadAttention, row: RosterRow | undefined, nowMs?: number): string;
44
47
  export {};
@@ -2,6 +2,9 @@ import { sessionHeadline } from '../session/title.js';
2
2
  function str(v) {
3
3
  return typeof v === 'string' && v.length > 0 ? v : undefined;
4
4
  }
5
+ function num(v) {
6
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined;
7
+ }
5
8
  export function rosterRowFromFeed(scope, agent) {
6
9
  const id = str(agent.sessionId);
7
10
  if (!id || agent.previous === true)
@@ -16,6 +19,8 @@ export function rosterRowFromFeed(scope, agent) {
16
19
  project: str(agent.confirmedProject),
17
20
  cwd: str(agent.cwd),
18
21
  ticket: str(agent.ticketId),
22
+ startedAtMs: num(agent.startedAtMs),
23
+ lastActivityMs: num(agent.lastActivityMs),
19
24
  };
20
25
  }
21
26
  export function attentionFromFeed(item) {
@@ -148,14 +153,16 @@ export function filterProject(snapshot, project, projectForCwd, exclude = new Se
148
153
  }
149
154
  return out;
150
155
  }
151
- export function formatRosterRow(row) {
156
+ export function formatRosterRow(row, nowMs) {
152
157
  const ticket = row.ticket ? ` ${row.ticket}` : '';
153
- return `- ${row.id.slice(0, 8)} “${row.title}” ${row.status} on ${row.host}${ticket}`;
158
+ const started = row.startedAtMs ? ` · started ${ago(row.startedAtMs, nowMs)}` : '';
159
+ const active = row.lastActivityMs ? ` · last active ${ago(row.lastActivityMs, nowMs)}` : '';
160
+ return `- ${row.id.slice(0, 8)} “${row.title}” ${row.status} on ${row.host}${ticket}${started}${active}`;
154
161
  }
155
- export function rosterDelta(prev, cur) {
162
+ export function rosterDelta(prev, cur, nowMs = Date.now()) {
156
163
  if (!prev) {
157
164
  const rows = Object.values(cur);
158
- return rows.length === 0 ? ['No live sessions for this project.'] : rows.map(formatRosterRow);
165
+ return rows.length === 0 ? ['No live sessions for this project.'] : rows.map((r) => formatRosterRow(r, nowMs));
159
166
  }
160
167
  const lines = [];
161
168
  for (const row of Object.values(cur)) {
@@ -174,8 +181,8 @@ export function rosterDelta(prev, cur) {
174
181
  return lines;
175
182
  }
176
183
  const MAX_QUESTION_CHARS = 240;
177
- function age(openedAt, nowMs) {
178
- const ms = nowMs - Date.parse(openedAt);
184
+ export function ago(at, nowMs) {
185
+ const ms = nowMs - (typeof at === 'number' ? at : Date.parse(at));
179
186
  if (!Number.isFinite(ms) || ms < 0)
180
187
  return 'just now';
181
188
  const mins = Math.floor(ms / 60_000);
@@ -192,5 +199,5 @@ export function formatAttention(ask, row, nowMs = Date.now()) {
192
199
  const title = row?.title ?? ask.sessionId.slice(0, 8);
193
200
  const project = ask.project ?? row?.project;
194
201
  const choices = ask.choices.length ? ` Choices: ${ask.choices.map((c) => `${c.id}=${c.label}`).join(', ')}` : ' Free-text answer.';
195
- return `- ${ask.key} “${title}” on ${ask.host}${project ? ` · ${project}` : ''} · ${age(ask.openedAt, nowMs)}: ${trimmed}${choices}`;
202
+ return `- ${ask.key} “${title}” on ${ask.host}${project ? ` · ${project}` : ''} · ${ago(ask.openedAt, nowMs)}: ${trimmed}${choices}`;
196
203
  }
@@ -10,6 +10,16 @@ export interface LeadToolContext {
10
10
  export declare function leadToolContext(env?: NodeJS.ProcessEnv): LeadToolContext;
11
11
  export declare function toolRoster(ctx: LeadToolContext, project?: string): Promise<string>;
12
12
  export declare function toolAttention(ctx: LeadToolContext): Promise<string>;
13
+ interface LinearIssue {
14
+ identifier: string;
15
+ title: string;
16
+ state?: {
17
+ name?: string;
18
+ };
19
+ url?: string;
20
+ description?: string;
21
+ updatedAt?: string;
22
+ }
13
23
  export declare function toolDispatch(ctx: LeadToolContext, ticket: string, agent: string): Promise<string>;
14
24
  export declare function toolStart(ctx: LeadToolContext, agent: string, task: string): Promise<string>;
15
25
  export declare function toolSend(ctx: LeadToolContext, session: string, text: string): Promise<string>;
@@ -24,6 +34,7 @@ export declare function toolPrAct(ctx: LeadToolContext, verb: PrVerb, opts: {
24
34
  runId?: string;
25
35
  }): Promise<string>;
26
36
  export declare function toolLinearTasks(ctx: LeadToolContext, status: string, limit: number): Promise<string>;
37
+ export declare function formatLinearTasks(issues: LinearIssue[], status: string, limit: number, nowMs: number): string;
27
38
  export declare function toolLinearView(id: string): Promise<string>;
28
39
  export declare function toolLinearCreate(ctx: LeadToolContext, title: string, description?: string): Promise<string>;
29
40
  export declare function toolRemember(ctx: LeadToolContext, note: string): string;
@@ -2,6 +2,7 @@ import { loadProjectDef } from '../projects.js';
2
2
  import { atomicWriteFileSync } from '../fs-atomic.js';
3
3
  import { connectHost, sendRequest } from './client.js';
4
4
  import { runAgents, runLinear } from './act.js';
5
+ import { ago } from './roster.js';
5
6
  import { LeadToolError, answerArgv, appendNote, assertAgent, assertPrNumber, assertRepo, assertSessionId, assertTask, assertTicketId, dispatchPrompt, linearCreateArgv, linearPickupArgv, linearTasksArgv, linearViewArgv, prArgv, prFailureArgv, prReadArgv, prsListArgv, runArgv, sendArgv, } from './shapes.js';
6
7
  import { ensureLeadDir } from './paths.js';
7
8
  import { readMemory } from './store.js';
@@ -94,7 +95,7 @@ export async function toolPrsList(ctx, repo) {
94
95
  continue;
95
96
  }
96
97
  for (const pr of r.pullRequests)
97
- lines.push(`${r.slug}#${pr.number}${pr.isDraft ? ' [draft]' : ''} ${pr.title}`);
98
+ lines.push(`${r.slug}#${pr.number}${pr.isDraft ? ' [draft]' : ''} ${pr.title}${pr.updatedAt ? ` · updated ${ago(pr.updatedAt, Date.now())}` : ''}`);
98
99
  }
99
100
  return lines.length ? lines.join('\n') : `No open PRs for ${ctx.project}.`;
100
101
  }
@@ -147,10 +148,17 @@ export async function toolPrAct(ctx, verb, opts) {
147
148
  }
148
149
  export async function toolLinearTasks(ctx, status, limit) {
149
150
  const raw = JSON.parse(await runLinear(linearTasksArgv(ctx.def, status, limit)));
150
- const issues = raw.issues ?? [];
151
+ return formatLinearTasks(raw.issues ?? [], status, limit, Date.now());
152
+ }
153
+ export function formatLinearTasks(issues, status, limit, nowMs) {
151
154
  if (issues.length === 0)
152
155
  return `No ${status} tickets.`;
153
- return issues.map((i) => `${i.identifier} ${i.title}${i.state?.name ? ` (${i.state.name})` : ''}`).join('\n');
156
+ const when = (i) => (i.updatedAt ? Date.parse(i.updatedAt) || 0 : 0);
157
+ const shown = [...issues].sort((a, b) => when(b) - when(a)).slice(0, limit);
158
+ const lines = shown.map((i) => `${i.identifier} ${i.title}${i.state?.name ? ` (${i.state.name})` : ''}${i.updatedAt ? ` · updated ${ago(i.updatedAt, nowMs)}` : ''}`);
159
+ if (issues.length > shown.length)
160
+ lines.push(`(${issues.length - shown.length} older ${status} tickets not shown)`);
161
+ return lines.join('\n');
154
162
  }
155
163
  export async function toolLinearView(id) {
156
164
  const i = JSON.parse(await runLinear(linearViewArgv(id)));
@@ -53,11 +53,13 @@ export function setActiveScanClockForTest(fn) {
53
53
  activeScanNow = fn ?? (() => Date.now());
54
54
  }
55
55
  let processTableCache;
56
+ let processTableReading;
56
57
  let processTableLiveReads = 0;
57
58
  let unattributedCache;
58
59
  let unattributedFullRescans = 0;
59
60
  export function clearActiveScanCachesForTest() {
60
61
  processTableCache = undefined;
62
+ processTableReading = undefined;
61
63
  processTableLiveReads = 0;
62
64
  unattributedCache = undefined;
63
65
  unattributedFullRescans = 0;
@@ -840,9 +842,15 @@ async function readProcessTable() {
840
842
  if (processTableCache && now - processTableCache.at < PROCESS_TABLE_FRESH_MS) {
841
843
  return processTableCache.rows;
842
844
  }
843
- const rows = await readProcessTableLive();
844
- processTableCache = { at: now, rows };
845
- return rows;
845
+ if (processTableReading)
846
+ return processTableReading;
847
+ const reading = readProcessTableLive()
848
+ .then((rows) => { if (processTableReading === reading)
849
+ processTableCache = { at: now, rows }; return rows; })
850
+ .finally(() => { if (processTableReading === reading)
851
+ processTableReading = undefined; });
852
+ processTableReading = reading;
853
+ return reading;
846
854
  }
847
855
  async function readProcessTableLive() {
848
856
  processTableLiveReads += 1;
@@ -39,7 +39,10 @@ export declare function resolveDeviceAuto(agent?: string, opts?: {
39
39
  eligibleHosts?: string[];
40
40
  localMachine?: string;
41
41
  accountPicker?: boolean;
42
- probe?: (pool: string[], agent?: AgentType) => Promise<Map<string, DevicePlacementSignal>>;
42
+ probe?: (pool: string[], agent?: AgentType, opts?: {
43
+ force?: boolean;
44
+ }) => Promise<Map<string, DevicePlacementSignal>>;
45
+ confirm?: (key: string) => Promise<boolean>;
43
46
  preferred?: ReadonlySet<string>;
44
47
  }): Promise<DeviceAutoPlan>;
45
48
  export declare function resolveDeviceAffinity(opts?: DeviceAffinityOptions): DeviceAffinityPlan;
@@ -64,5 +67,6 @@ export declare function applyDeviceAutoToOptions(options: DeviceAutoHostOptions,
64
67
  resolve?: (accountPicker: boolean) => DeviceAutoPlan | Promise<DeviceAutoPlan>;
65
68
  agent?: string;
66
69
  accountPickerRequested?: boolean;
70
+ onPlacing?: () => void;
67
71
  }): Promise<DeviceAutoApplyResult>;
68
72
  export {};
@@ -4,7 +4,8 @@ import { loadDevicesSync } from './devices/registry.js';
4
4
  import { blocksPlacement } from './devices/health.js';
5
5
  import { autoLaunchPreferredSet, describeAutoPool, filterAutoPool, isAutoPoolMember } from './devices/pool.js';
6
6
  import { normalizeHost } from './machine-id.js';
7
- import { probePoolSignals } from './teams/placement-probe.js';
7
+ import { confirmPlacementTarget, probePoolSignals } from './teams/placement-probe.js';
8
+ import { writePlacementSnapshot } from './devices/stats-cache.js';
8
9
  import { pickBestDevice } from './teams/scheduler.js';
9
10
  const DEFAULT_AFFINITY_ALPHA = 1.3;
10
11
  export function affinityWeights(rows, alpha = DEFAULT_AFFINITY_ALPHA) {
@@ -102,25 +103,28 @@ export async function resolveDeviceAuto(agent, opts = {}) {
102
103
  pool.push(local);
103
104
  if (pool.length === 0)
104
105
  throw new Error(formatEmptyAutoPoolError());
105
- const signals = await (opts.probe ?? probePoolSignals)(pool, agent);
106
- if (!agent && !opts.probe) {
107
- const { collectFleetHarnesses } = await import('./devices/harness-inventory.js');
108
- const { isInteractiveTerminal } = await import('./format.js');
109
- const { default: ora } = await import('ora');
110
- const inventory = await collectFleetHarnesses({
111
- devices: pool,
112
- spinner: isInteractiveTerminal() ? (text) => ora(text).start() : undefined,
113
- });
114
- const byHost = new Map(inventory.map((result) => [normalizeHost(result.host), result]));
115
- for (const key of pool) {
116
- const result = byHost.get(key);
117
- const accountEligible = !!result && !result.error && !result.skipped && result.rows.some((row) => row.ready);
118
- const current = signals.get(key);
119
- if (current)
120
- signals.set(key, { ...current, installed: accountEligible, signedIn: accountEligible });
106
+ const collectSignals = async (force) => {
107
+ const signals = await (opts.probe ?? probePoolSignals)(pool, agent, { force });
108
+ if (!agent && !opts.probe) {
109
+ const { collectFleetHarnesses } = await import('./devices/harness-inventory.js');
110
+ const { isInteractiveTerminal } = await import('./format.js');
111
+ const { default: ora } = await import('ora');
112
+ const inventory = await collectFleetHarnesses({
113
+ devices: pool,
114
+ spinner: isInteractiveTerminal() ? (text) => ora(text).start() : undefined,
115
+ });
116
+ const byHost = new Map(inventory.map((result) => [normalizeHost(result.host), result]));
117
+ for (const key of pool) {
118
+ const result = byHost.get(key);
119
+ const accountEligible = !!result && !result.error && !result.skipped && result.rows.some((row) => row.ready);
120
+ const current = signals.get(key);
121
+ if (current)
122
+ signals.set(key, { ...current, installed: accountEligible, signedIn: accountEligible });
123
+ }
121
124
  }
122
- }
123
- const eligiblePool = pool.filter((key) => {
125
+ return signals;
126
+ };
127
+ const eligibleIn = (signals) => pool.filter((key) => {
124
128
  const signal = signals.get(key);
125
129
  if (signal?.reachable !== true || blocksPlacement(signal.headroom))
126
130
  return false;
@@ -130,11 +134,27 @@ export async function resolveDeviceAuto(agent, opts = {}) {
130
134
  ? signal.pickerEligible === true
131
135
  : signal.signedIn === true);
132
136
  });
137
+ if (!opts.probe)
138
+ writePlacementSnapshot({ demandAt: Date.now() });
139
+ let signals = await collectSignals(false);
140
+ let eligiblePool = eligibleIn(signals);
141
+ if (eligiblePool.length === 0 && [...signals.values()].some((signal) => signal.fromSnapshot)) {
142
+ signals = await collectSignals(true);
143
+ eligiblePool = eligibleIn(signals);
144
+ }
133
145
  if (eligiblePool.length === 0) {
134
146
  throw new Error(formatNoHealthyDeviceError(pool, signals, agent));
135
147
  }
136
148
  const preferred = opts.preferred ?? autoLaunchPreferredSet(pool, { roster: pool });
137
- const picked = pickBestDevice(eligiblePool, [], { signals, agentLabel: agent, preferred });
149
+ const confirm = opts.confirm ?? confirmPlacementTarget;
150
+ let picked = pickBestDevice(eligiblePool, [], { signals, agentLabel: agent, preferred });
151
+ while (picked !== local && signals.get(picked)?.fromSnapshot && !(await confirm(picked))) {
152
+ signals.set(picked, { ...signals.get(picked), reachable: false, fromSnapshot: false });
153
+ eligiblePool = eligiblePool.filter((key) => key !== picked);
154
+ if (eligiblePool.length === 0)
155
+ throw new Error(formatNoHealthyDeviceError(pool, signals, agent));
156
+ picked = pickBestDevice(eligiblePool, [], { signals, agentLabel: agent, preferred });
157
+ }
138
158
  return {
139
159
  host: picked === local ? null : picked,
140
160
  pickedDeviceKey: picked,
@@ -203,6 +223,7 @@ export async function applyDeviceAutoToOptions(options, deps = {}) {
203
223
  if (!hasAuto) {
204
224
  return { attempted: false };
205
225
  }
226
+ deps.onPlacing?.();
206
227
  const accountPickerRequested = deps.accountPickerRequested ?? false;
207
228
  const resolve = deps.resolve ?? ((accountPicker) => resolveDeviceAuto(deps.agent, { accountPicker }));
208
229
  const plan = await resolve(accountPickerRequested);
@@ -1,9 +1,8 @@
1
1
  import { type DeviceStats } from '../devices/health.js';
2
+ import { type PlacementSnapshot, type ReadyProbeEntry } from '../devices/stats-cache.js';
2
3
  import { type AgentType } from './agents.js';
3
4
  import type { DevicePlacementSignal } from './scheduler.js';
4
5
  export declare const READY_PROBE_TIMEOUT_MS = 8000;
5
- export declare const SIGNAL_TTL_MS = 15000;
6
- export declare function clearPlacementSignalCache(): void;
7
6
  interface ReadinessInfo {
8
7
  answered: boolean;
9
8
  installed: boolean | undefined;
@@ -12,9 +11,13 @@ interface ReadinessInfo {
12
11
  reason?: string;
13
12
  timedOut?: boolean;
14
13
  }
14
+ export declare function readinessFromProbe(entry: ReadyProbeEntry, agent: string): ReadinessInfo;
15
15
  export declare function mergePlacementSignal(stats: DeviceStats | undefined, readiness: ReadinessInfo | undefined): DevicePlacementSignal;
16
+ export declare function snapshotSignal(snapshot: PlacementSnapshot, name: string, agent: string | undefined, now: number): DevicePlacementSignal | undefined;
16
17
  export declare function probePoolSignals(pool: string[], agent?: AgentType, opts?: {
17
18
  force?: boolean;
18
19
  now?: number;
19
20
  }): Promise<Map<string, DevicePlacementSignal>>;
21
+ export declare function refreshPlacementSnapshot(pool: string[], now?: number): Promise<number | null>;
22
+ export declare function confirmPlacementTarget(name: string): Promise<boolean>;
20
23
  export {};
@@ -4,22 +4,16 @@ import { probeFleetStats, headroom } from '../devices/health.js';
4
4
  import { loadDevicesSync } from '../devices/registry.js';
5
5
  import { buildSshInvocation, writeAskpassShim } from '../devices/connect.js';
6
6
  import { resolveDeviceProfile } from '../devices/resolve-profile.js';
7
- import { buildReadyProbeCommand, parseReadyProbe, viewAgentAccountEligibility, viewHasAgent, } from '../hosts/ready.js';
7
+ import { freshReadyProbe, freshSnapshotStats, placementDemandIsRecent, readPlacementSnapshot, retainHardwareFacts, writePlacementSnapshot, } from '../devices/stats-cache.js';
8
+ import { buildReadyProbeCommand, compactReadyView, hostAnswers, parseReadyProbe, viewAgentAccountEligibility, viewHasAgent, } from '../hosts/ready.js';
9
+ import { resolveHost } from '../hosts/registry.js';
8
10
  import { collectRunCandidates, isSignInRecoverable, readinessFromCandidate, } from '../accounting/rotate.js';
9
11
  import { localMachineId } from '../origin-machine.js';
10
12
  import { normalizeHost } from '../machine-id.js';
11
13
  import { checkCliAvailable } from './agents.js';
12
14
  export const READY_PROBE_TIMEOUT_MS = 8_000;
13
- export const SIGNAL_TTL_MS = 15_000;
14
- const cache = new Map();
15
- function cacheKey(pool, agent) {
16
- return `${agent ?? 'any-agent'}::${[...pool].map(normalizeHost).sort().join(',')}`;
17
- }
18
- export function clearPlacementSignalCache() {
19
- cache.clear();
20
- }
21
- function probeRemoteReadiness(device, agent, usagePayload) {
22
- const unknown = { answered: false, installed: undefined, signedIn: undefined, pickerEligible: undefined };
15
+ function probeRemoteReady(device, usagePayload) {
16
+ const unknown = () => ({ answered: false, version: null, view: '', fetchedAt: Date.now() });
23
17
  let args;
24
18
  let env;
25
19
  try {
@@ -28,7 +22,7 @@ function probeRemoteReadiness(device, agent, usagePayload) {
28
22
  ({ args, env } = buildSshInvocation(device, [cmd], shim, {}, { agentOnly: true }));
29
23
  }
30
24
  catch {
31
- return Promise.resolve(unknown);
25
+ return Promise.resolve(unknown());
32
26
  }
33
27
  return new Promise((resolve) => {
34
28
  const child = spawn('ssh', args, {
@@ -54,27 +48,33 @@ function probeRemoteReadiness(device, agent, usagePayload) {
54
48
  child.stdout.setEncoding('utf-8');
55
49
  child.stdout.on('data', (chunk) => { stdout += chunk; });
56
50
  child.stderr.resume();
57
- child.on('error', () => finish(unknown));
51
+ child.on('error', () => finish(unknown()));
58
52
  child.on('close', (code) => {
59
53
  if (timedOut)
60
- return finish({ ...unknown, timedOut: true });
54
+ return finish({ ...unknown(), timedOut: true });
61
55
  if (code !== 0 || !stdout)
62
- return finish(unknown);
56
+ return finish(unknown());
63
57
  const probe = parseReadyProbe(stdout);
64
58
  if (!probe.reachable)
65
- return finish(unknown);
66
- if (!probe.version)
67
- return finish({ answered: true, installed: false, signedIn: false, pickerEligible: false });
68
- const installed = viewHasAgent(probe.view, agent);
69
- const eligibility = installed
70
- ? viewAgentAccountEligibility(probe.view, agent)
71
- : { signedIn: false, pickerEligible: false };
72
- finish({ answered: true, installed, ...eligibility });
59
+ return finish(unknown());
60
+ finish({ answered: true, version: probe.version, view: compactReadyView(probe.view), fetchedAt: Date.now() });
73
61
  });
74
62
  child.stdin.on('error', () => { });
75
63
  child.stdin.end(usagePayload);
76
64
  });
77
65
  }
66
+ export function readinessFromProbe(entry, agent) {
67
+ if (!entry.answered) {
68
+ return { answered: false, installed: undefined, signedIn: undefined, pickerEligible: undefined, timedOut: entry.timedOut };
69
+ }
70
+ if (!entry.version)
71
+ return { answered: true, installed: false, signedIn: false, pickerEligible: false };
72
+ const installed = viewHasAgent(entry.view, agent);
73
+ const eligibility = installed
74
+ ? viewAgentAccountEligibility(entry.view, agent)
75
+ : { signedIn: false, pickerEligible: false };
76
+ return { answered: true, installed, ...eligibility };
77
+ }
78
78
  export function mergePlacementSignal(stats, readiness) {
79
79
  const reachable = readiness?.answered === true ? true : stats?.reachable;
80
80
  return {
@@ -90,14 +90,55 @@ export function mergePlacementSignal(stats, readiness) {
90
90
  reason: readiness?.reason,
91
91
  };
92
92
  }
93
- export async function probePoolSignals(pool, agent, opts = {}) {
94
- const now = opts.now ?? Date.now();
95
- const key = cacheKey(pool, agent);
96
- const cached = cache.get(key);
97
- if (!opts.force && cached && now - cached.at < SIGNAL_TTL_MS)
98
- return cached.signals;
93
+ export function snapshotSignal(snapshot, name, agent, now) {
94
+ const stats = freshSnapshotStats(snapshot, name, now);
95
+ if (!stats)
96
+ return undefined;
97
+ if (!agent)
98
+ return { ...mergePlacementSignal(stats, undefined), fromSnapshot: true };
99
+ const probe = freshReadyProbe(snapshot, name, now);
100
+ if (!probe)
101
+ return undefined;
102
+ return { ...mergePlacementSignal(stats, readinessFromProbe(probe, agent)), fromSnapshot: true };
103
+ }
104
+ async function localReadiness(agent) {
105
+ if (!checkCliAvailable(agent)[0])
106
+ return { answered: true, installed: false, signedIn: false, pickerEligible: false };
107
+ const candidates = await collectRunCandidates(agent).catch(() => null);
108
+ if (!candidates)
109
+ return { answered: true, installed: true, signedIn: undefined, pickerEligible: undefined };
110
+ const readiness = candidates.map((candidate) => readinessFromCandidate(candidate));
111
+ return {
112
+ answered: true,
113
+ installed: true,
114
+ signedIn: readiness.some((candidate) => candidate.ready),
115
+ pickerEligible: readiness.some((candidate) => candidate.ready || isSignInRecoverable(candidate)),
116
+ };
117
+ }
118
+ async function probeLive(profiles, selfName, withReadiness) {
119
+ const remote = profiles.filter((d) => d.name !== selfName);
120
+ const usagePayload = withReadiness && remote.length > 0
121
+ ? JSON.stringify(buildFleetStatePayload({ usageOnly: true }))
122
+ : '';
123
+ const [stats, probed] = await Promise.all([
124
+ profiles.length > 0 ? probeFleetStats(profiles, { selfName }) : Promise.resolve(new Map()),
125
+ withReadiness
126
+ ? Promise.all(remote.map(async (d) => [d.name, await probeRemoteReady(d, usagePayload)]))
127
+ : Promise.resolve([]),
128
+ ]);
129
+ const prior = readPlacementSnapshot().stats;
130
+ const rows = {};
131
+ for (const [name, row] of stats) {
132
+ const kept = retainHardwareFacts(row, prior[name]);
133
+ stats.set(name, kept);
134
+ rows[name] = kept;
135
+ }
136
+ const probes = new Map(probed);
137
+ writePlacementSnapshot({ stats: rows, readiness: Object.fromEntries(probes) });
138
+ return { stats, probes };
139
+ }
140
+ function resolvePoolProfiles(pool) {
99
141
  const reg = loadDevicesSync();
100
- const self = normalizeHost(localMachineId());
101
142
  const lookup = (name) => reg[name] ?? reg[normalizeHost(name)];
102
143
  const profiles = [];
103
144
  const seen = new Set();
@@ -108,40 +149,61 @@ export async function probePoolSignals(pool, agent, opts = {}) {
108
149
  seen.add(d.name);
109
150
  }
110
151
  }
152
+ return { lookup, profiles };
153
+ }
154
+ export async function probePoolSignals(pool, agent, opts = {}) {
155
+ const now = opts.now ?? Date.now();
156
+ const self = normalizeHost(localMachineId());
157
+ const { lookup, profiles } = resolvePoolProfiles(pool);
111
158
  const selfProfile = profiles.find((d) => normalizeHost(d.name) === self);
112
- const stats = await probeFleetStats(profiles, { selfName: selfProfile?.name });
113
- const usagePayload = JSON.stringify(buildFleetStatePayload({ usageOnly: true }));
114
- const installed = new Map(agent
115
- ? await Promise.all(profiles.map(async (d) => {
116
- const isSelf = normalizeHost(d.name) === self;
117
- if (isSelf) {
118
- const inst = checkCliAvailable(agent)[0];
119
- if (!inst)
120
- return [d.name, { answered: true, installed: false, signedIn: false, pickerEligible: false }];
121
- const candidates = await collectRunCandidates(agent).catch(() => null);
122
- if (!candidates) {
123
- return [d.name, { answered: true, installed: true, signedIn: undefined, pickerEligible: undefined }];
124
- }
125
- const readiness = candidates.map((candidate) => readinessFromCandidate(candidate));
126
- return [d.name, {
127
- answered: true,
128
- installed: true,
129
- signedIn: readiness.some((candidate) => candidate.ready),
130
- pickerEligible: readiness.some((candidate) => candidate.ready || isSignInRecoverable(candidate)),
131
- }];
132
- }
133
- return [d.name, await probeRemoteReadiness(d, agent, usagePayload)];
134
- }))
135
- : []);
159
+ const snapshot = readPlacementSnapshot();
160
+ const cached = new Map();
161
+ const live = [];
162
+ for (const d of profiles) {
163
+ const signal = d === selfProfile || opts.force ? undefined : snapshotSignal(snapshot, d.name, agent, now);
164
+ if (signal)
165
+ cached.set(d.name, signal);
166
+ else
167
+ live.push(d);
168
+ }
169
+ const [{ stats, probes }, selfReadiness] = await Promise.all([
170
+ probeLive(live, selfProfile?.name, agent !== undefined),
171
+ agent && selfProfile ? localReadiness(agent) : Promise.resolve(undefined),
172
+ ]);
136
173
  const signals = new Map();
137
174
  for (const name of pool) {
138
175
  const d = lookup(name);
139
- const s = d ? stats.get(d.name) : undefined;
140
- const inst = d ? installed.get(d.name) : undefined;
176
+ if (!d)
177
+ continue;
178
+ const fromSnapshot = cached.get(d.name);
179
+ if (fromSnapshot) {
180
+ signals.set(name, fromSnapshot);
181
+ continue;
182
+ }
183
+ const s = stats.get(d.name);
184
+ const probe = probes.get(d.name);
185
+ const inst = d === selfProfile ? selfReadiness : probe && agent ? readinessFromProbe(probe, agent) : undefined;
141
186
  if (!s && !inst)
142
187
  continue;
143
188
  signals.set(name, mergePlacementSignal(s, inst));
144
189
  }
145
- cache.set(key, { at: now, signals });
146
190
  return signals;
147
191
  }
192
+ export async function refreshPlacementSnapshot(pool, now = Date.now()) {
193
+ if (!placementDemandIsRecent(readPlacementSnapshot(), now))
194
+ return null;
195
+ const self = normalizeHost(localMachineId());
196
+ const remote = resolvePoolProfiles(pool).profiles.filter((d) => normalizeHost(d.name) !== self);
197
+ const { probes } = await probeLive(remote, undefined, true);
198
+ return probes.size;
199
+ }
200
+ export async function confirmPlacementTarget(name) {
201
+ const host = await resolveHost(name);
202
+ if (host && hostAnswers(host))
203
+ return true;
204
+ const deviceName = resolvePoolProfiles([name]).profiles[0]?.name ?? name;
205
+ writePlacementSnapshot({
206
+ readiness: { [deviceName]: { answered: false, timedOut: true, version: null, view: '', fetchedAt: Date.now() } },
207
+ });
208
+ return false;
209
+ }
@@ -10,6 +10,7 @@ export interface DevicePlacementSignal {
10
10
  signedIn?: boolean;
11
11
  pickerEligible?: boolean;
12
12
  reason?: string;
13
+ fromSnapshot?: boolean;
13
14
  }
14
15
  interface PlacementTeam {
15
16
  devices?: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.37",
3
+ "version": "1.23.39",
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",