@phnx-labs/agents-cli 1.23.38 → 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 +8 -0
- package/dist/commands/exec.d.ts +4 -0
- package/dist/commands/exec.js +14 -1
- package/dist/lib/accounting/account-pool-collect.d.ts +1 -0
- package/dist/lib/accounting/account-pool-collect.js +13 -7
- package/dist/lib/accounting/account-pool.d.ts +1 -0
- package/dist/lib/accounting/account-pool.js +4 -3
- package/dist/lib/daemon/device-probe-service.js +8 -0
- package/dist/lib/daemon-services.js +1 -1
- package/dist/lib/devices/stats-cache.d.ts +24 -1
- package/dist/lib/devices/stats-cache.js +52 -18
- package/dist/lib/devices/worker-pick.d.ts +1 -1
- package/dist/lib/devices/worker-pick.js +8 -1
- package/dist/lib/hosts/ready.d.ts +3 -0
- package/dist/lib/hosts/ready.js +41 -1
- package/dist/lib/session/active.js +11 -3
- package/dist/lib/smart-launch.d.ts +5 -1
- package/dist/lib/smart-launch.js +41 -20
- package/dist/lib/teams/placement-probe.d.ts +5 -2
- package/dist/lib/teams/placement-probe.js +119 -57
- package/dist/lib/teams/scheduler.d.ts +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
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
|
+
|
|
3
11
|
## 1.23.38
|
|
4
12
|
|
|
5
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
|
package/dist/commands/exec.d.ts
CHANGED
|
@@ -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: {
|
package/dist/commands/exec.js
CHANGED
|
@@ -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
|
|
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 {
|
|
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
|
-
|
|
9
|
-
.filter((a) =>
|
|
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
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
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
|
|
38
|
+
return parsed;
|
|
37
39
|
}
|
|
38
40
|
catch {
|
|
39
41
|
}
|
|
40
|
-
return {};
|
|
42
|
+
return { version: 1, entries: {} };
|
|
41
43
|
}
|
|
42
|
-
|
|
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
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
|
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;
|
package/dist/lib/hosts/ready.js
CHANGED
|
@@ -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 =
|
|
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). ` +
|
|
@@ -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
|
-
|
|
844
|
-
|
|
845
|
-
|
|
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
|
|
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 {};
|
package/dist/lib/smart-launch.js
CHANGED
|
@@ -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
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
-
|
|
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
|
|
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 {
|
|
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
|
-
|
|
14
|
-
const
|
|
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
|
-
|
|
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
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (!
|
|
98
|
-
return
|
|
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
|
|
113
|
-
const
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
140
|
-
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phnx-labs/agents-cli",
|
|
3
|
-
"version": "1.23.
|
|
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",
|