@phnx-labs/agents-cli 1.23.42 → 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 +14 -0
- package/README.md +1 -1
- package/dist/commands/cloud-transcripts.js +31 -12
- package/dist/commands/cloud.js +6 -17
- package/dist/commands/exec.js +2 -1
- package/dist/lib/agent-modes.js +1 -0
- package/dist/lib/agent-spec/agents.js +1 -1
- package/dist/lib/cloud/dispatch.d.ts +1 -1
- package/dist/lib/cloud/dispatch.js +3 -10
- package/dist/lib/cloud/registry.d.ts +2 -0
- package/dist/lib/cloud/registry.js +7 -1
- package/dist/lib/cloud/rush.d.ts +10 -33
- package/dist/lib/cloud/rush.js +151 -300
- package/dist/lib/cloud/stream.js +8 -6
- package/dist/lib/cloud/types.d.ts +4 -6
- package/dist/lib/cloud/types.js +4 -1
- package/dist/lib/daemon/session-state-service.d.ts +6 -1
- package/dist/lib/daemon/session-state-service.js +38 -1
- package/dist/lib/devices/connect.d.ts +1 -0
- package/dist/lib/devices/connect.js +3 -1
- package/dist/lib/devices/health.d.ts +3 -0
- package/dist/lib/devices/health.js +14 -2
- package/dist/lib/exec.d.ts +1 -1
- package/dist/lib/exec.js +2 -1
- package/dist/lib/github/project-prs.d.ts +1 -0
- package/dist/lib/github/project-prs.js +44 -8
- package/dist/lib/identity/client.d.ts +1 -1
- package/dist/lib/identity/client.js +1 -1
- package/dist/lib/session/discover.d.ts +4 -0
- package/dist/lib/session/discover.js +39 -1
- package/dist/lib/session/presentation.d.ts +3 -0
- package/dist/lib/session/presentation.js +4 -1
- package/dist/lib/ssh-exec.d.ts +2 -0
- package/dist/lib/ssh-exec.js +12 -2
- package/package.json +1 -1
- package/dist/lib/rush-session.d.ts +0 -1
- package/dist/lib/rush-session.js +0 -5
- package/dist/lib/session/cloud.d.ts +0 -5
- package/dist/lib/session/cloud.js +0 -89
|
@@ -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(
|
|
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
|
}
|
|
@@ -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';
|
package/dist/lib/exec.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare function resolveMode(agent: AgentId, requested: Mode): Mode;
|
|
|
19
19
|
* because plan is broken in a headless `--prompt`/`-p` run — kimi refuses
|
|
20
20
|
* `--prompt` + `--plan`, and grok's `--permission-mode plan` silently stalls at
|
|
21
21
|
* its ExitPlanMode gate. For those agents, a headless plan request degrades to
|
|
22
|
-
* `auto` (kimi -p auto-runs; grok
|
|
22
|
+
* `auto` (kimi -p auto-runs; grok runs `--permission-mode auto`) with a visible
|
|
23
23
|
* one-line stderr warning, mirroring the graceful plan→edit degrade antigravity
|
|
24
24
|
* get for having no plan flag at all. Interactive runs are never
|
|
25
25
|
* downgraded. This is the single source of truth shared by buildExecCommand
|
package/dist/lib/exec.js
CHANGED
|
@@ -103,7 +103,7 @@ export function resolveMode(agent, requested) {
|
|
|
103
103
|
* because plan is broken in a headless `--prompt`/`-p` run — kimi refuses
|
|
104
104
|
* `--prompt` + `--plan`, and grok's `--permission-mode plan` silently stalls at
|
|
105
105
|
* its ExitPlanMode gate. For those agents, a headless plan request degrades to
|
|
106
|
-
* `auto` (kimi -p auto-runs; grok
|
|
106
|
+
* `auto` (kimi -p auto-runs; grok runs `--permission-mode auto`) with a visible
|
|
107
107
|
* one-line stderr warning, mirroring the graceful plan→edit degrade antigravity
|
|
108
108
|
* get for having no plan flag at all. Interactive runs are never
|
|
109
109
|
* downgraded. This is the single source of truth shared by buildExecCommand
|
|
@@ -441,6 +441,7 @@ export const AGENT_COMMANDS = {
|
|
|
441
441
|
modeFlags: {
|
|
442
442
|
plan: ['--permission-mode', 'plan'],
|
|
443
443
|
edit: [],
|
|
444
|
+
auto: ['--permission-mode', 'auto'],
|
|
444
445
|
skip: ['--always-approve'],
|
|
445
446
|
},
|
|
446
447
|
jsonFlags: ['--output-format', 'streaming-json'],
|
|
@@ -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
|
|
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 {
|
|
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
|
|
117
|
-
|
|
118
|
-
'
|
|
119
|
-
'--jq', '.data.repository.pullRequests.nodes[]',
|
|
120
|
-
]);
|
|
121
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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();
|
|
@@ -19,6 +19,9 @@ export declare function renderSessionLogJson(session: SessionMeta): Promise<void
|
|
|
19
19
|
export declare function renderSession(session: SessionMeta, mode: ViewMode, filters: FilterOptions, options?: {
|
|
20
20
|
redact?: boolean;
|
|
21
21
|
}): Promise<void>;
|
|
22
|
+
export declare function renderSessionEvents(session: SessionMeta, parsedEvents: SessionEvent[], mode: ViewMode, filters: FilterOptions, options?: {
|
|
23
|
+
redact?: boolean;
|
|
24
|
+
}): void;
|
|
22
25
|
export declare function formatTodoCompact(todos?: Pick<TodoProgress, 'done' | 'total' | 'activeForm'> | null): string;
|
|
23
26
|
export declare function statusColor(status: ActiveSession['status']): (s: string) => string;
|
|
24
27
|
export declare function cleanPreview(text: string): string;
|
|
@@ -152,7 +152,10 @@ export async function renderSession(session, mode, filters, options = {}) {
|
|
|
152
152
|
const spinner = ora(`Parsing ${sessionDisplayAgent(session)} session...`).start();
|
|
153
153
|
const parsedEvents = parseSession(session.filePath, session.agent);
|
|
154
154
|
spinner.stop();
|
|
155
|
-
|
|
155
|
+
renderSessionEvents(session, parsedEvents, mode, filters, options);
|
|
156
|
+
}
|
|
157
|
+
export function renderSessionEvents(session, parsedEvents, mode, filters, options = {}) {
|
|
158
|
+
const events = filterEvents(parsedEvents, filters);
|
|
156
159
|
const shown = sessionDisplayAgent(session);
|
|
157
160
|
const agentColor = colorAgent(shown);
|
|
158
161
|
console.log('');
|
package/dist/lib/ssh-exec.d.ts
CHANGED
|
@@ -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 {
|
package/dist/lib/ssh-exec.js
CHANGED
|
@@ -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
|
-
|
|
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.
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function isRushSessionExpired(expiresAt: number | undefined): boolean;
|
package/dist/lib/rush-session.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
|
|
2
|
-
export declare function discoverCloudSessions(options?: {
|
|
3
|
-
limit?: number;
|
|
4
|
-
}): Promise<SessionMeta[]>;
|
|
5
|
-
export declare function ensureCloudSessionCached(executionId: string, destPath?: string): Promise<string>;
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
import { deriveShortId } from '../text/short-id.js';
|
|
4
|
-
import { getCacheDir } from '../state.js';
|
|
5
|
-
import { readToken, rushOrgHandle } from '../cloud/rush.js';
|
|
6
|
-
import { RUSH_API_BASE } from '../rush-api.js';
|
|
7
|
-
const CLOUD_CACHE_DIR = path.join(getCacheDir(), 'cloud-runs');
|
|
8
|
-
const CLOUD_EXECUTION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
9
|
-
async function api(endpoint, token, accept) {
|
|
10
|
-
return fetch(`${RUSH_API_BASE}${endpoint}`, {
|
|
11
|
-
headers: { Authorization: `Bearer ${token}`, ...(accept ? { Accept: accept } : {}) },
|
|
12
|
-
});
|
|
13
|
-
}
|
|
14
|
-
function harnessToFormat(harness) {
|
|
15
|
-
if (harness === 'claude' || harness === 'codex' || harness === 'opencode')
|
|
16
|
-
return harness;
|
|
17
|
-
return null;
|
|
18
|
-
}
|
|
19
|
-
function assertContained(candidate, rootDir) {
|
|
20
|
-
const root = path.resolve(rootDir);
|
|
21
|
-
const resolved = path.resolve(root, candidate);
|
|
22
|
-
if (!resolved.startsWith(root + path.sep)) {
|
|
23
|
-
throw new Error(`Path escapes cloud session cache: ${candidate}`);
|
|
24
|
-
}
|
|
25
|
-
return resolved;
|
|
26
|
-
}
|
|
27
|
-
function validateCloudExecutionId(executionId) {
|
|
28
|
-
if (!CLOUD_EXECUTION_ID_RE.test(executionId)) {
|
|
29
|
-
throw new Error(`Invalid cloud execution_id: ${JSON.stringify(executionId)}`);
|
|
30
|
-
}
|
|
31
|
-
return executionId;
|
|
32
|
-
}
|
|
33
|
-
function cachePathForExecution(executionId, agent) {
|
|
34
|
-
const id = validateCloudExecutionId(executionId);
|
|
35
|
-
return assertContained(path.join(id, `session.${agent}.jsonl`), CLOUD_CACHE_DIR);
|
|
36
|
-
}
|
|
37
|
-
export async function discoverCloudSessions(options) {
|
|
38
|
-
const token = readToken();
|
|
39
|
-
const org = await rushOrgHandle(token);
|
|
40
|
-
const limit = options?.limit ?? 50;
|
|
41
|
-
const res = await api(`/o/${encodeURIComponent(org)}/sessions?limit=${limit}`, token);
|
|
42
|
-
if (!res.ok) {
|
|
43
|
-
throw new Error(`cloud sessions list failed (${res.status})`);
|
|
44
|
-
}
|
|
45
|
-
const data = (await res.json());
|
|
46
|
-
const rows = data.sessions ?? [];
|
|
47
|
-
const out = [];
|
|
48
|
-
for (const row of rows) {
|
|
49
|
-
const agent = harnessToFormat(row.harness);
|
|
50
|
-
if (!agent)
|
|
51
|
-
continue;
|
|
52
|
-
const id = validateCloudExecutionId(row.id);
|
|
53
|
-
const timestamp = row.updated_at || row.created_at || new Date().toISOString();
|
|
54
|
-
const project = row.project ?? undefined;
|
|
55
|
-
const filePath = cachePathForExecution(id, agent);
|
|
56
|
-
out.push({
|
|
57
|
-
id,
|
|
58
|
-
shortId: deriveShortId(id),
|
|
59
|
-
agent,
|
|
60
|
-
timestamp,
|
|
61
|
-
project,
|
|
62
|
-
filePath,
|
|
63
|
-
topic: (row.title || row.prompt)?.split('\n')[0]?.slice(0, 120),
|
|
64
|
-
label: `[cloud/${row.status}]${row.branch ? ` ${row.branch}` : ''}`,
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
out.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
|
|
68
|
-
return out;
|
|
69
|
-
}
|
|
70
|
-
export async function ensureCloudSessionCached(executionId, destPath) {
|
|
71
|
-
const id = validateCloudExecutionId(executionId);
|
|
72
|
-
const callerPath = destPath ? assertContained(destPath, CLOUD_CACHE_DIR) : undefined;
|
|
73
|
-
const token = readToken();
|
|
74
|
-
const org = await rushOrgHandle(token);
|
|
75
|
-
const res = await api(`/o/${encodeURIComponent(org)}/p/_/sessions/${encodeURIComponent(id)}/trajectory`, token, 'application/x-ndjson');
|
|
76
|
-
if (!res.ok) {
|
|
77
|
-
const body = await res.text().catch(() => '');
|
|
78
|
-
throw new Error(`session.jsonl fetch ${res.status}: ${body.slice(0, 200)}`);
|
|
79
|
-
}
|
|
80
|
-
const format = (res.headers.get('X-Session-Format') || '').toLowerCase();
|
|
81
|
-
if (!['claude', 'codex', 'rush', 'opencode'].includes(format)) {
|
|
82
|
-
throw new Error(`Unknown X-Session-Format on cloud response: "${format}"`);
|
|
83
|
-
}
|
|
84
|
-
const finalPath = callerPath ?? cachePathForExecution(id, format);
|
|
85
|
-
fs.mkdirSync(path.dirname(finalPath), { recursive: true });
|
|
86
|
-
const body = Buffer.from(await res.arrayBuffer());
|
|
87
|
-
fs.writeFileSync(finalPath, body);
|
|
88
|
-
return finalPath;
|
|
89
|
-
}
|