@phnx-labs/agents-cli 1.23.43 → 1.23.44

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.44
4
+
5
+ - **Phoenix ID's default host is now `id.phoenix.so` (PHNX-4424).** `agents auth login`, `whoami` and `logout`, and a session-backup Worker set up from now on, talk to `https://id.phoenix.so` unless `PHOENIX_ID_BASE` says otherwise; a Worker set up earlier keeps checking `id.byphoenix.com`, which still serves. `id.byphoenix.com` keeps serving, and a session signed in through either host is valid at both, so existing sign-ins keep working. Source: `cli/src/lib/identity/client.ts`.
6
+
7
+ - **Far devices are no longer marked unreachable.** The device probe opened a new SSH connection every time, and a cold handshake to a peer 300 ms away takes 3.4–3.8 s, past its 2.5 s budget. `agents devices status`, AGI EXT's device list and `--device auto` therefore treated such boxes as unreachable and placed runs on the launching machine. The load probe now reuses the shared SSH connection other fleet commands keep open, which answers in 0.6–0.9 s, and a timed-out probe warms that connection in the background for the next one. The budgets are unchanged. Source: `cli/src/lib/devices/health.ts`, `cli/src/lib/devices/connect.ts`.
8
+
9
+ - **`agents projects prs list <project>` returns in about half the time on a repository with many open PRs.** GitHub works out each PR's merge state (`mergeStateStatus`) when asked, so the one paginated GraphQL list of 100 PRs a page spent about 3 s per page on that field alone, one page after another. The list now asks only for the open PR numbers, then reads the PRs 10 to a query, at most 12 queries at a time across every repository the process reads (each costs 1 GraphQL point). On `phnx-labs/agents` (115 open PRs) the command went from 5.9 s to 3.0 s (median of 5 runs each), and the JSON is byte-identical. Source: `cli/src/lib/github/project-prs.ts` (`listOpenPrs`).
10
+
3
11
  ## 1.23.43
4
12
 
5
13
  - **`agents cloud --provider rush` uses a Rush API key, not the deprecated `rush login` (PHNX-4381).** The provider and `agents cloud transcripts` now call the Rush developer API (`/o/{org}/sessions`: start, read, list, `…/events`, `…/messages`, `…/cancel`) with `RUSH_API_KEY` and `RUSH_ORG`, read from the secrets bundle named in `cloud.providers.rush.secretsBundle` or from the environment (`secrets exec getrush.ai -- agents cloud run …`). Nothing reads `~/.rush/user.yaml` any more. A run no longer needs `--repo`; it takes one repository (sent with `--branch` as a `tree/<branch>` resource), and two `--repo` flags are refused. `--skill` takes a public skill URL. `agents cloud run` loses `--mode`, `-b/--balanced` and `--strategy`, which only the old Rush path read: a key run uses the key creator's own model accounts, and `agents run --cloud --mode …` to Rush is refused. Source: `cli/src/lib/cloud/rush.ts`, `cli/src/commands/cloud-transcripts.ts`.
@@ -6,8 +6,13 @@ export declare class SessionStateService extends BasePeriodicService {
6
6
  readonly intervalMs = 15000;
7
7
  readonly deadlineMs = 30000;
8
8
  private stopReaderWatch;
9
+ private liveFiles;
10
+ private wakeTimer;
11
+ private lastWakeMs;
12
+ private lastChangeMs;
9
13
  constructor(wake: () => void);
10
- protected onStart(_ctx: DaemonContext): Promise<void>;
14
+ protected onStart(ctx: DaemonContext): Promise<void>;
11
15
  protected onStop(): Promise<void>;
12
16
  protected onTick(ctx: DaemonContext): Promise<void>;
17
+ private scheduleWake;
13
18
  }
@@ -1,26 +1,63 @@
1
1
  import { runActiveSessionsWarmTick } from '../daemon-ticks.js';
2
2
  import { watchActiveSessionsReaderPresence } from '../session/session-cache.js';
3
+ import { watchClaudeLiveSessionFiles } from '../session/discover.js';
3
4
  import { BasePeriodicService } from './service.js';
4
5
  const SESSION_STATE_TICK_MS = 15_000;
5
6
  const SESSION_STATE_DEADLINE_MS = 30_000;
7
+ const LIVE_CHANGE_SETTLE_MS = 150;
8
+ const LIVE_CHANGE_MIN_GAP_MS = 1_000;
6
9
  export class SessionStateService extends BasePeriodicService {
7
10
  wake;
8
11
  id = 'session-state';
9
12
  intervalMs = SESSION_STATE_TICK_MS;
10
13
  deadlineMs = SESSION_STATE_DEADLINE_MS;
11
14
  stopReaderWatch = null;
15
+ liveFiles = null;
16
+ wakeTimer;
17
+ lastWakeMs = 0;
18
+ lastChangeMs = 0;
12
19
  constructor(wake) {
13
20
  super();
14
21
  this.wake = wake;
15
22
  }
16
- async onStart(_ctx) {
23
+ async onStart(ctx) {
17
24
  this.stopReaderWatch = watchActiveSessionsReaderPresence(this.wake);
25
+ const warned = new Set();
26
+ this.liveFiles = watchClaudeLiveSessionFiles(() => {
27
+ this.lastChangeMs = Date.now();
28
+ this.scheduleWake();
29
+ }, (dir, err) => {
30
+ if (warned.has(dir))
31
+ return;
32
+ warned.add(dir);
33
+ ctx.log('WARN', `session-state: cannot watch ${dir} (${err.message}); renames there wait for the 15 s tick`, { event: 'sessions.live-watch.failed', dir, error: err.message });
34
+ });
18
35
  }
19
36
  async onStop() {
20
37
  this.stopReaderWatch?.();
21
38
  this.stopReaderWatch = null;
39
+ this.liveFiles?.close();
40
+ this.liveFiles = null;
41
+ clearTimeout(this.wakeTimer);
42
+ this.wakeTimer = undefined;
22
43
  }
23
44
  async onTick(ctx) {
45
+ const startedMs = Date.now();
24
46
  await runActiveSessionsWarmTick({ log: ctx.log });
47
+ this.liveFiles?.refresh();
48
+ const changedDuringTick = this.lastChangeMs >= startedMs;
49
+ if (changedDuringTick)
50
+ this.scheduleWake();
51
+ }
52
+ scheduleWake() {
53
+ if (this.wakeTimer || !this.liveFiles)
54
+ return;
55
+ const delay = Math.max(LIVE_CHANGE_SETTLE_MS, this.lastWakeMs + LIVE_CHANGE_MIN_GAP_MS - Date.now());
56
+ this.wakeTimer = setTimeout(() => {
57
+ this.wakeTimer = undefined;
58
+ this.lastWakeMs = Date.now();
59
+ this.wake();
60
+ }, delay);
61
+ this.wakeTimer.unref?.();
25
62
  }
26
63
  }
@@ -29,6 +29,7 @@ export declare function buildSshInvocation(device: DeviceProfile, cmd: string[],
29
29
  agentOnly?: boolean;
30
30
  interactiveCwd?: string;
31
31
  argv?: boolean;
32
+ multiplex?: boolean;
32
33
  }): {
33
34
  args: string[];
34
35
  env: Record<string, string>;
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { assertValidSshTarget, shellQuote } from '../ssh-exec.js';
3
+ import { assertValidSshTarget, controlOpts, shellQuote } from '../ssh-exec.js';
4
4
  import { resolveActor, actorEnv } from '../actor.js';
5
5
  import { getCliLaunch } from '../cli-entry.js';
6
6
  import { encodePwshBase64, pwshLiteral, pwshNativeExecStatements } from '../pwsh.js';
@@ -170,6 +170,8 @@ export function buildSshInvocation(device, cmd, askpassShimPath, hostKey = {}, o
170
170
  args.push('-o', 'BatchMode=yes');
171
171
  args.push(...deviceIdentityArgs(device));
172
172
  }
173
+ if (opts.multiplex && !interactive)
174
+ args.push(...controlOpts());
173
175
  if (interactive)
174
176
  args.push('-tt');
175
177
  args.push(target);
@@ -1,3 +1,4 @@
1
+ import { type ChildProcess } from 'child_process';
1
2
  import type { DeviceProfile } from './registry.js';
2
3
  export declare const PROBE_TIMEOUT_MS = 2500;
3
4
  export declare const RELAYED_PROBE_TIMEOUT_MS = 8000;
@@ -69,6 +70,8 @@ export declare function probeDeviceStats(device: DeviceProfile, opts?: {
69
70
  timeoutMs?: number;
70
71
  now?: number;
71
72
  }): Promise<DeviceStats>;
73
+ export declare const WARM_SSH_LIFETIME_MS = 15000;
74
+ export declare function warmSshConnection(args: string[], env: Record<string, string>): ChildProcess;
72
75
  export declare function probeLocalStats(host: string, opts?: {
73
76
  timeoutMs?: number;
74
77
  now?: number;
@@ -1,4 +1,4 @@
1
- import { execFile } from 'child_process';
1
+ import { execFile, spawn } from 'child_process';
2
2
  import { buildSshInvocation, writeAskpassShim } from './connect.js';
3
3
  import { resolveDeviceProfile } from './resolve-profile.js';
4
4
  export const PROBE_TIMEOUT_MS = 2_500;
@@ -189,7 +189,7 @@ export function headroom(stats) {
189
189
  export function buildProbeInvocation(device, askpassShimPath) {
190
190
  const resolved = resolveDeviceProfile(device);
191
191
  const isWin = resolved.shell === 'powershell';
192
- const { args, env } = buildSshInvocation(resolved, [isWin ? WIN_PROBE_SNIPPET : PROBE_SNIPPET], askpassShimPath, {}, { agentOnly: true });
192
+ const { args, env } = buildSshInvocation(resolved, [isWin ? WIN_PROBE_SNIPPET : PROBE_SNIPPET], askpassShimPath, {}, { agentOnly: true, multiplex: true });
193
193
  return { args, env, isWin, budgetMs: probeBudgetMs(resolved) };
194
194
  }
195
195
  // Stats probes are agentOnly so listing devices never opens credential UI; a timeout means slow, not conclusively unreachable.
@@ -214,12 +214,24 @@ export function probeDeviceStats(device, opts = {}) {
214
214
  }, (err, stdout) => {
215
215
  if (err || !stdout) {
216
216
  const timedOut = Boolean(err && err.killed);
217
+ if (timedOut)
218
+ warmSshConnection(args, env);
217
219
  return resolve(timedOut ? { host, reachable: false, timedOut, fetchedAt } : { host, reachable: false, fetchedAt });
218
220
  }
219
221
  resolve(isWin ? parseWinProbeOutput(host, stdout, fetchedAt) : parseProbeOutput(host, stdout, fetchedAt));
220
222
  });
221
223
  });
222
224
  }
225
+ export const WARM_SSH_LIFETIME_MS = 15_000;
226
+ export function warmSshConnection(args, env) {
227
+ const child = spawn('ssh', [...args.slice(0, -1), 'true'], { detached: true, stdio: 'ignore', env: { ...process.env, ...env } });
228
+ child.on('error', () => { });
229
+ const timer = setTimeout(() => child.kill('SIGKILL'), WARM_SSH_LIFETIME_MS);
230
+ timer.unref();
231
+ child.on('exit', () => clearTimeout(timer));
232
+ child.unref();
233
+ return child;
234
+ }
223
235
  export function probeLocalStats(host, opts = {}) {
224
236
  const fetchedAt = opts.now ?? Date.now();
225
237
  const isWin = process.platform === 'win32';
@@ -95,6 +95,7 @@ export interface ProjectPrsOptions {
95
95
  }
96
96
  export declare function rowToProjectPr(row: Record<string, unknown>): ProjectPr;
97
97
  export declare const PR_NODE_FIELDS = "\n number title url isDraft state createdAt updatedAt body\n author { __typename login avatarUrl }\n repository { nameWithOwner }\n headRefName baseRefName headRefOid mergeable mergeStateStatus\n autoMergeRequest { enabledBy { login } mergeMethod }\n commits(last: 1) { nodes { commit { statusCheckRollup { state contexts(first: 100) { pageInfo { hasNextPage } nodes {\n __typename\n ... on CheckRun { name status conclusion detailsUrl }\n ... on StatusContext { context state targetUrl }\n } } } } } }";
98
+ export declare const OPEN_PRS_PER_QUERY = 10;
98
99
  export declare function prFromNode(node: Record<string, unknown>): {
99
100
  slug: string;
100
101
  pr: ProjectPr;
@@ -61,14 +61,21 @@ export const PR_NODE_FIELDS = `
61
61
  ... on CheckRun { name status conclusion detailsUrl }
62
62
  ... on StatusContext { context state targetUrl }
63
63
  } } } } } }`;
64
- const OPEN_PRS_QUERY = `query($owner: String!, $name: String!, $endCursor: String) {
64
+ const OPEN_PR_NUMBERS_QUERY = `query($owner: String!, $name: String!, $endCursor: String) {
65
65
  repository(owner: $owner, name: $name) {
66
66
  pullRequests(states: OPEN, first: 100, after: $endCursor, orderBy: {field: CREATED_AT, direction: DESC}) {
67
67
  pageInfo { hasNextPage endCursor }
68
- nodes { ${PR_NODE_FIELDS} }
68
+ nodes { number }
69
69
  }
70
70
  }
71
71
  }`;
72
+ const prsByNumberQuery = (numbers) => `query($owner: String!, $name: String!) {
73
+ repository(owner: $owner, name: $name) {
74
+ ${numbers.map((n) => `pr${n}: pullRequest(number: ${n}) { ${PR_NODE_FIELDS} }`).join('\n ')}
75
+ }
76
+ }`;
77
+ export const OPEN_PRS_PER_QUERY = 10;
78
+ const OPEN_PR_QUERIES_IN_FLIGHT = 12;
72
79
  const MERGEABLE = { MERGEABLE: true, CONFLICTING: false };
73
80
  function rollupFromContexts(contexts) {
74
81
  const byName = new Map();
@@ -111,14 +118,43 @@ export function prFromNode(node) {
111
118
  ci.ciState = rollup.state;
112
119
  return { slug: String(rec(node.repository).nameWithOwner ?? ''), pr: { ...pr, ...ci } };
113
120
  }
121
+ let openPrQueriesRunning = 0;
122
+ const openPrQueryWaiters = [];
123
+ async function withOpenPrQuerySlot(fn) {
124
+ if (openPrQueriesRunning < OPEN_PR_QUERIES_IN_FLIGHT)
125
+ openPrQueriesRunning++;
126
+ else
127
+ await new Promise((handOver) => openPrQueryWaiters.push(handOver));
128
+ try {
129
+ return await fn();
130
+ }
131
+ finally {
132
+ const nextInLine = openPrQueryWaiters.shift();
133
+ if (nextInLine)
134
+ nextInLine();
135
+ else
136
+ openPrQueriesRunning--;
137
+ }
138
+ }
114
139
  export async function listOpenPrs(repo, gh = ghExec) {
115
140
  const [owner, name] = repo.split('/');
116
- const out = await gh([
117
- 'api', 'graphql', '--paginate',
118
- '-f', `owner=${owner}`, '-f', `name=${name}`, '-f', `query=${OPEN_PRS_QUERY}`,
119
- '--jq', '.data.repository.pullRequests.nodes[]',
120
- ]);
121
- return parseNdjson(out).map((node) => prFromNode(node).pr);
141
+ const repoFields = ['-f', `owner=${owner}`, '-f', `name=${name}`];
142
+ const numbers = (await gh([
143
+ 'api', 'graphql', '--paginate', ...repoFields, '-f', `query=${OPEN_PR_NUMBERS_QUERY}`,
144
+ '--jq', '.data.repository.pullRequests.nodes[].number',
145
+ ])).split('\n').map((l) => l.trim()).filter(Boolean).map(Number);
146
+ const batches = [];
147
+ for (let i = 0; i < numbers.length; i += OPEN_PRS_PER_QUERY)
148
+ batches.push(numbers.slice(i, i + OPEN_PRS_PER_QUERY));
149
+ const nodes = (await Promise.all(batches.map((batch) => withOpenPrQuerySlot(async () => parseNdjson(await gh([
150
+ 'api', 'graphql', ...repoFields, '-f', `query=${prsByNumberQuery(batch)}`,
151
+ '--jq', '.data.repository[] | select(. != null)',
152
+ ])))))).flat();
153
+ const byNumber = new Map(nodes.filter((node) => node.state === 'OPEN').map((node) => [Number(node.number), node]));
154
+ return numbers.flatMap((n) => {
155
+ const node = byNumber.get(n);
156
+ return node ? [prFromNode(node).pr] : [];
157
+ });
122
158
  }
123
159
  export async function fetchOnePr(repo, number, gh = ghExec, cache) {
124
160
  const out = await gh(['api', `repos/${repo}/pulls/${number}`, ...(cache ? ['--cache', cache] : []), '--jq', PR_JQ]);
@@ -1,4 +1,4 @@
1
- export declare const DEFAULT_PHOENIX_ID_BASE = "https://id.byphoenix.com";
1
+ export declare const DEFAULT_PHOENIX_ID_BASE = "https://id.phoenix.so";
2
2
  export declare const PHOENIX_ID_BASE: string;
3
3
  export declare function sessionFilePath(): string;
4
4
  export interface PhoenixSession {
@@ -2,7 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { atomicWriteFileSync } from '../fs-atomic.js';
4
4
  import { getRuntimeStateDir } from '../state.js';
5
- export const DEFAULT_PHOENIX_ID_BASE = 'https://id.byphoenix.com';
5
+ export const DEFAULT_PHOENIX_ID_BASE = 'https://id.phoenix.so';
6
6
  export const PHOENIX_ID_BASE = process.env.PHOENIX_ID_BASE ?? DEFAULT_PHOENIX_ID_BASE;
7
7
  export function sessionFilePath() {
8
8
  return path.join(getRuntimeStateDir(), 'phoenix-session.json');
@@ -159,6 +159,10 @@ export declare function getSessionRoots(): SessionRoots[];
159
159
  export declare function readClaudeLiveNames(): Map<string, LiveSessionName & {
160
160
  sessionId: string;
161
161
  }>;
162
+ export declare function watchClaudeLiveSessionFiles(onChange: () => void, onWatchError?: (dir: string, err: Error) => void): {
163
+ refresh: () => void;
164
+ close: () => void;
165
+ };
162
166
  export declare function decodeJwtEmail(idToken: string): string | undefined;
163
167
  export declare function __codexAccountResolveCountForTest(): number;
164
168
  export declare function __resetCodexAccountCacheForTest(): void;
@@ -645,9 +645,11 @@ function recentlyLive(sessionIds, now) {
645
645
  }
646
646
  return hot;
647
647
  }
648
+ let lastClaudeLiveDirs = [];
648
649
  export function readClaudeLiveNames() {
649
650
  const newest = new Map();
650
- for (const dir of getAgentSessionDirs('claude', 'sessions')) {
651
+ lastClaudeLiveDirs = getAgentSessionDirs('claude', 'sessions');
652
+ for (const dir of lastClaudeLiveDirs) {
651
653
  let files;
652
654
  try {
653
655
  files = fs.readdirSync(dir).filter(f => f.endsWith('.json'));
@@ -681,6 +683,42 @@ export function readClaudeLiveNames() {
681
683
  }
682
684
  return new Map([...newest].map(([id, { entry }]) => [id, entry]));
683
685
  }
686
+ export function watchClaudeLiveSessionFiles(onChange, onWatchError = () => { }) {
687
+ const watchers = new Map();
688
+ const drop = (dir) => { watchers.get(dir)?.close(); watchers.delete(dir); };
689
+ const refresh = () => {
690
+ const listed = new Set(lastClaudeLiveDirs);
691
+ for (const dir of [...watchers.keys()])
692
+ if (!listed.has(dir))
693
+ drop(dir);
694
+ for (const dir of listed) {
695
+ if (watchers.has(dir))
696
+ continue;
697
+ try {
698
+ const watcher = fs.watch(dir, { persistent: false }, (_event, name) => {
699
+ const deletedSelf = name !== null && String(name) === path.basename(dir);
700
+ if (deletedSelf) {
701
+ drop(dir);
702
+ return;
703
+ }
704
+ if (!name || String(name).endsWith('.json'))
705
+ onChange();
706
+ });
707
+ watcher.on('error', () => drop(dir));
708
+ watchers.set(dir, watcher);
709
+ }
710
+ catch (err) {
711
+ if (err.code !== 'ENOENT')
712
+ onWatchError(dir, err);
713
+ }
714
+ }
715
+ };
716
+ return {
717
+ refresh,
718
+ close: () => { for (const dir of [...watchers.keys()])
719
+ drop(dir); },
720
+ };
721
+ }
684
722
  async function scanClaudeIncremental(onProgress) {
685
723
  claudeAccountIndex(true);
686
724
  const liveNames = readClaudeLiveNames();
@@ -12,6 +12,8 @@ export declare class RemoteUtf8Accumulator {
12
12
  current(): string;
13
13
  }
14
14
  export declare const SSH_CONTROL_PERSIST_SECONDS: number;
15
+ export declare const MAX_CONTROL_PATH_BYTES = 86;
16
+ export declare function controlPathBytes(dir: string): number;
15
17
  export declare function controlOpts(): string[];
16
18
  export declare function sshConnectOpts(mux: string[], hostKeyOpts?: string[]): string[];
17
19
  interface SshExecOptions {
@@ -16,12 +16,15 @@ export function shellQuote(s) {
16
16
  return s;
17
17
  return "'" + s.replace(/'/g, "'\\''") + "'";
18
18
  }
19
+ const SSH_KEEPALIVE_OPTS = [
20
+ '-o', 'ServerAliveInterval=15',
21
+ '-o', 'ServerAliveCountMax=3',
22
+ ];
19
23
  export const SSH_OPTS = [
20
24
  '-o', 'StrictHostKeyChecking=accept-new',
21
25
  '-o', 'BatchMode=yes',
22
26
  '-o', 'ConnectTimeout=10',
23
- '-o', 'ServerAliveInterval=15',
24
- '-o', 'ServerAliveCountMax=3',
27
+ ...SSH_KEEPALIVE_OPTS,
25
28
  ];
26
29
  export const REMOTE_STDOUT_MAX_BYTES = 16 * 1024 * 1024;
27
30
  export class RemoteUtf8Accumulator {
@@ -40,10 +43,16 @@ export class RemoteUtf8Accumulator {
40
43
  }
41
44
  export const SSH_CONTROL_PERSIST_SECONDS = 10 * 60;
42
45
  let controlDirEnsured = false;
46
+ export const MAX_CONTROL_PATH_BYTES = 86;
47
+ export function controlPathBytes(dir) {
48
+ return Buffer.byteLength(path.join(dir, 'cm-'.padEnd(43, '0')));
49
+ }
43
50
  export function controlOpts() {
44
51
  if (process.platform === 'win32')
45
52
  return [];
46
53
  const dir = path.join(getCacheDir(), 'ssh');
54
+ if (controlPathBytes(dir) > MAX_CONTROL_PATH_BYTES)
55
+ return [];
47
56
  if (!controlDirEnsured) {
48
57
  try {
49
58
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -56,6 +65,7 @@ export function controlOpts() {
56
65
  '-o', 'ControlMaster=auto',
57
66
  '-o', `ControlPath=${path.join(dir, 'cm-%C')}`,
58
67
  '-o', `ControlPersist=${SSH_CONTROL_PERSIST_SECONDS}s`,
68
+ ...SSH_KEEPALIVE_OPTS,
59
69
  ];
60
70
  }
61
71
  export function sshConnectOpts(mux, hostKeyOpts) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.43",
3
+ "version": "1.23.44",
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",