@phnx-labs/agents-cli 1.23.3 → 1.23.5
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 +31 -0
- package/dist/bootstrap.js +14 -9
- package/dist/commands/exec.js +7 -7
- package/dist/commands/focus.js +17 -16
- package/dist/commands/go.js +2 -2
- package/dist/commands/ps-roster.d.ts +1 -1
- package/dist/commands/ps-roster.js +4 -3
- package/dist/commands/resume.d.ts +1 -0
- package/dist/commands/resume.js +9 -1
- package/dist/commands/sessions-resume.js +65 -18
- package/dist/commands/setup-terminal.js +3 -2
- package/dist/lib/exec.js +6 -1
- package/dist/lib/hosts/reconnect.d.ts +3 -2
- package/dist/lib/hosts/reconnect.js +8 -9
- package/dist/lib/launch-log.d.ts +15 -0
- package/dist/lib/launch-log.js +120 -0
- package/dist/lib/project-root.d.ts +1 -0
- package/dist/lib/project-root.js +9 -0
- package/dist/lib/remote-agents-json.d.ts +1 -0
- package/dist/lib/remote-agents-json.js +4 -2
- package/dist/lib/secrets-client.js +18 -3
- package/dist/lib/self-update.d.ts +1 -0
- package/dist/lib/self-update.js +4 -0
- package/dist/lib/session/active.d.ts +6 -1
- package/dist/lib/session/active.js +12 -2
- package/dist/lib/session/pid-registry.d.ts +1 -0
- package/dist/lib/session/pid-registry.js +6 -0
- package/dist/lib/session/remote/remote-list.d.ts +3 -1
- package/dist/lib/session/remote/remote-list.js +65 -19
- package/dist/lib/session/remote-active.d.ts +3 -1
- package/dist/lib/session/remote-active.js +4 -3
- package/dist/lib/session/session-cache.d.ts +1 -0
- package/dist/lib/session/session-cache.js +14 -1
- package/dist/lib/ssh-exec.js +1 -1
- package/dist/lib/terminal/backends/vscodium-agent.d.ts +31 -8
- package/dist/lib/terminal/backends/vscodium-agent.js +134 -7
- package/dist/lib/terminal/engine.d.ts +7 -1
- package/dist/lib/terminal/engine.js +68 -9
- package/dist/lib/terminal/index.d.ts +1 -1
- package/dist/lib/terminal/index.js +1 -1
- package/dist/lib/terminal/run-surface.d.ts +1 -0
- package/dist/lib/terminal/run-surface.js +8 -2
- package/dist/lib/terminal/types.d.ts +6 -2
- package/dist/lib/types.d.ts +1 -0
- package/dist/lib/types.js +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { getLogsDir } from './state.js';
|
|
4
|
+
export const LAUNCH_LOG_ENV = 'AGENTS_LAUNCH_LOG';
|
|
5
|
+
export function launchesDir() {
|
|
6
|
+
return path.join(getLogsDir(), 'launches');
|
|
7
|
+
}
|
|
8
|
+
export function launchFailurePath(sessionId) {
|
|
9
|
+
return path.join(launchesDir(), `${sessionId}.json`);
|
|
10
|
+
}
|
|
11
|
+
export function launchSessionId(argv) {
|
|
12
|
+
const resume = argv.indexOf('--resume');
|
|
13
|
+
if (resume >= 0 && argv[resume + 1] && !argv[resume + 1].startsWith('-'))
|
|
14
|
+
return argv[resume + 1];
|
|
15
|
+
const verbs = ['resume', 'focus'];
|
|
16
|
+
if (argv[0] === 'sessions' && verbs.includes(argv[1] ?? '') && argv[2] && !argv[2].startsWith('-'))
|
|
17
|
+
return argv[2];
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
export function launchesAgent(argv) {
|
|
21
|
+
const words = argv.filter((a) => !a.startsWith('-'));
|
|
22
|
+
return words[0] === 'run'
|
|
23
|
+
|| words[0] === 'focus'
|
|
24
|
+
|| (words[0] === 'ps' && words[1] === 'focus')
|
|
25
|
+
|| (words[0] === 'sessions' && (words[1] === 'resume' || words[1] === 'focus'));
|
|
26
|
+
}
|
|
27
|
+
const AGENT_STARTED = '[agents] launch handed to the agent';
|
|
28
|
+
export function markAgentStarted(env = process.env) {
|
|
29
|
+
const log = env[LAUNCH_LOG_ENV];
|
|
30
|
+
if (!log)
|
|
31
|
+
return;
|
|
32
|
+
try {
|
|
33
|
+
fs.appendFileSync(log, `${AGENT_STARTED}\n`, { mode: 0o600 });
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const LAUNCH_LOG_MAX_AGE_MS = 14 * 24 * 60 * 60_000;
|
|
39
|
+
function pruneLaunchLogs(dir, nowMs) {
|
|
40
|
+
let files;
|
|
41
|
+
try {
|
|
42
|
+
files = fs.readdirSync(dir);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const f of files) {
|
|
48
|
+
const file = path.join(dir, f);
|
|
49
|
+
try {
|
|
50
|
+
if (nowMs - fs.statSync(file).mtimeMs > LAUNCH_LOG_MAX_AGE_MS)
|
|
51
|
+
fs.rmSync(file, { force: true });
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
58
|
+
export function failureCause(log) {
|
|
59
|
+
const lines = log.replace(ANSI, '').split('\n').filter((l) => l.trim() && !/^\s/.test(l));
|
|
60
|
+
return lines.at(-1)?.trim() || 'it exited before the agent started, without saying why';
|
|
61
|
+
}
|
|
62
|
+
export function startQuietLaunch(argv, env = process.env) {
|
|
63
|
+
const outermost = !env[LAUNCH_LOG_ENV];
|
|
64
|
+
const log = env[LAUNCH_LOG_ENV] || path.join(launchesDir(), `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}.log`);
|
|
65
|
+
env[LAUNCH_LOG_ENV] = log;
|
|
66
|
+
fs.mkdirSync(path.dirname(log), { recursive: true, mode: 0o700 });
|
|
67
|
+
if (outermost)
|
|
68
|
+
pruneLaunchLogs(path.dirname(log), Date.now());
|
|
69
|
+
const sessionId = launchSessionId(argv);
|
|
70
|
+
if (sessionId)
|
|
71
|
+
fs.rmSync(launchFailurePath(sessionId), { force: true });
|
|
72
|
+
const ownStart = fs.existsSync(log) ? fs.statSync(log).size : 0;
|
|
73
|
+
const write = (chunk, encodingOrCb, cb) => {
|
|
74
|
+
try {
|
|
75
|
+
fs.appendFileSync(log, typeof chunk === 'string' || Buffer.isBuffer(chunk) ? chunk : String(chunk), { mode: 0o600 });
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
}
|
|
79
|
+
const done = typeof encodingOrCb === 'function' ? encodingOrCb : cb;
|
|
80
|
+
if (typeof done === 'function')
|
|
81
|
+
done();
|
|
82
|
+
return true;
|
|
83
|
+
};
|
|
84
|
+
process.stderr.write = write;
|
|
85
|
+
if (!outermost)
|
|
86
|
+
return log;
|
|
87
|
+
process.on('exit', (code) => {
|
|
88
|
+
const exitCode = code || (typeof process.exitCode === 'number' ? process.exitCode : 0);
|
|
89
|
+
if (!exitCode)
|
|
90
|
+
return;
|
|
91
|
+
let mine = '';
|
|
92
|
+
try {
|
|
93
|
+
const fd = fs.openSync(log, 'r');
|
|
94
|
+
const size = fs.fstatSync(fd).size;
|
|
95
|
+
const buf = Buffer.alloc(Math.max(0, size - ownStart));
|
|
96
|
+
fs.readSync(fd, buf, 0, buf.length, ownStart);
|
|
97
|
+
fs.closeSync(fd);
|
|
98
|
+
mine = buf.toString('utf8');
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
}
|
|
102
|
+
if (mine.includes(AGENT_STARTED))
|
|
103
|
+
return;
|
|
104
|
+
const cause = failureCause(mine);
|
|
105
|
+
if (sessionId) {
|
|
106
|
+
try {
|
|
107
|
+
const record = { status: 'failed', cause, log, exitCode, at: new Date().toISOString() };
|
|
108
|
+
fs.writeFileSync(launchFailurePath(sessionId), JSON.stringify(record), { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
fs.writeSync(2, `\nThe agent did not start: ${cause}\nFull output: ${log}\n`);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
return log;
|
|
120
|
+
}
|
|
@@ -2,6 +2,7 @@ export declare function toHomeRelative(abs: string): string;
|
|
|
2
2
|
export declare function expandLocalHome(p: string): string;
|
|
3
3
|
export declare function toRemotePortable(p: string): string;
|
|
4
4
|
export declare function homeRemainder(p: string): string | null;
|
|
5
|
+
export declare function localProjectFolder(cwd: string | undefined, home?: string): string | undefined;
|
|
5
6
|
export declare function deriveMirroredCwd(localCwd: string): string | undefined;
|
|
6
7
|
export declare function remoteCdPrefix(remoteCwd?: string, opts?: {
|
|
7
8
|
mirror?: boolean;
|
package/dist/lib/project-root.js
CHANGED
|
@@ -40,6 +40,15 @@ export function homeRemainder(p) {
|
|
|
40
40
|
return p.slice(6);
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
|
+
const FOREIGN_HOME_RE = /^\/(?:home|Users)\/[^/]+(?=\/|$)/;
|
|
44
|
+
const WORKTREE_RE = /\/\.agents\/worktrees\/[^/]+(?:\/.*)?$/;
|
|
45
|
+
export function localProjectFolder(cwd, home = HOME) {
|
|
46
|
+
if (!cwd)
|
|
47
|
+
return undefined;
|
|
48
|
+
const local = cwd.startsWith(home + '/') || cwd === home ? cwd : cwd.replace(FOREIGN_HOME_RE, home);
|
|
49
|
+
const folder = local.replace(WORKTREE_RE, '');
|
|
50
|
+
return folder !== home && fs.existsSync(folder) ? folder : undefined;
|
|
51
|
+
}
|
|
43
52
|
export function deriveMirroredCwd(localCwd) {
|
|
44
53
|
const portable = toRemotePortable(localCwd);
|
|
45
54
|
return homeRemainder(portable) === null ? undefined : portable;
|
|
@@ -29,6 +29,7 @@ interface RemoteAgentsJsonResult<T> {
|
|
|
29
29
|
deviceCount: number;
|
|
30
30
|
skipped: string[];
|
|
31
31
|
parseFailed: string[];
|
|
32
|
+
answered: string[];
|
|
32
33
|
discoveryFailed: boolean;
|
|
33
34
|
}
|
|
34
35
|
export declare function normalizeRemoteAgentsJsonParse<T>(parsed: T[] | RemoteAgentsJsonParseResult<T>): RemoteAgentsJsonParseResult<T>;
|
|
@@ -77,7 +77,7 @@ export async function gatherRemoteAgentsJson(options, deps = {}) {
|
|
|
77
77
|
devices = await loadDevices();
|
|
78
78
|
}
|
|
79
79
|
catch {
|
|
80
|
-
return { items: [], deviceCount: 0, skipped: [], parseFailed: [], discoveryFailed: true };
|
|
80
|
+
return { items: [], deviceCount: 0, skipped: [], parseFailed: [], answered: [], discoveryFailed: true };
|
|
81
81
|
}
|
|
82
82
|
for (const device of Object.values(devices)) {
|
|
83
83
|
if (!isDialableDevice(device))
|
|
@@ -101,6 +101,7 @@ export async function gatherRemoteAgentsJson(options, deps = {}) {
|
|
|
101
101
|
}
|
|
102
102
|
const skipped = [];
|
|
103
103
|
const parseFailed = [];
|
|
104
|
+
const answered = [];
|
|
104
105
|
const controller = options.earlyExit ? new AbortController() : undefined;
|
|
105
106
|
if (controller)
|
|
106
107
|
setMaxListeners(targets.length + 1, controller.signal);
|
|
@@ -132,6 +133,7 @@ export async function gatherRemoteAgentsJson(options, deps = {}) {
|
|
|
132
133
|
}
|
|
133
134
|
return [];
|
|
134
135
|
}
|
|
136
|
+
answered.push(target.machine);
|
|
135
137
|
if (controller && options.earlyExit && !earlyResolved
|
|
136
138
|
&& parsed.items.some((item) => options.earlyExit.isDefinitive(item, target.machine))) {
|
|
137
139
|
earlyResolved = true;
|
|
@@ -139,5 +141,5 @@ export async function gatherRemoteAgentsJson(options, deps = {}) {
|
|
|
139
141
|
}
|
|
140
142
|
return parsed.items;
|
|
141
143
|
}));
|
|
142
|
-
return { items: results.flat(), deviceCount: targets.length, skipped, parseFailed, discoveryFailed: false };
|
|
144
|
+
return { items: results.flat(), deviceCount: targets.length, skipped, parseFailed, answered, discoveryFailed: false };
|
|
143
145
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
2
4
|
import { findInPath } from './agent-spec/agents.js';
|
|
3
5
|
import { SECRETS_CLI_INSTALL_HINT } from './secrets-cli.js';
|
|
4
|
-
import { getUserAgentsDir } from './state.js';
|
|
6
|
+
import { getLogsDir, getUserAgentsDir } from './state.js';
|
|
5
7
|
export const PROTOCOL_VERSION = 1;
|
|
6
8
|
const MAX_PROTOCOL_BYTES = 8 * 1024 * 1024;
|
|
7
9
|
const SERVE_TIMEOUT_MS = 65_000;
|
|
@@ -158,15 +160,27 @@ function parseResponse(raw) {
|
|
|
158
160
|
return decodeWire(parsed.result);
|
|
159
161
|
throw new SecretsClientError(parsed.error.code, parsed.error.message);
|
|
160
162
|
}
|
|
163
|
+
function logServeStderr(chunk) {
|
|
164
|
+
if (!chunk || chunk.length === 0)
|
|
165
|
+
return;
|
|
166
|
+
try {
|
|
167
|
+
const file = path.join(getLogsDir(), 'secrets-serve.log');
|
|
168
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
169
|
+
fs.appendFileSync(file, chunk);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
}
|
|
173
|
+
}
|
|
161
174
|
// Anonymous fd3/fd4 pipes keep secret bytes off disk; success waits for both response EOF and child exit.
|
|
162
175
|
function serveOnce(op, args, context) {
|
|
163
176
|
const { command, prefix } = invocation(resolveSecretsBin());
|
|
164
177
|
const request = Buffer.from(JSON.stringify(buildRequest(op, args, context)));
|
|
165
178
|
return new Promise((resolve, reject) => {
|
|
166
179
|
const child = spawn(command, [...prefix, '__serve'], {
|
|
167
|
-
stdio: ['ignore', 'ignore', '
|
|
180
|
+
stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'],
|
|
168
181
|
env: buildServeEnv(),
|
|
169
182
|
});
|
|
183
|
+
child.stderr.on('data', logServeStderr);
|
|
170
184
|
let settled = false;
|
|
171
185
|
const fail = (error) => {
|
|
172
186
|
if (settled)
|
|
@@ -230,11 +244,12 @@ function serveOnceSync(op, args, context) {
|
|
|
230
244
|
const script = `exec ${serve} 3<&0 4>&1 1>/dev/null`;
|
|
231
245
|
const result = spawnSync('sh', ['-c', script], {
|
|
232
246
|
input: request,
|
|
233
|
-
stdio: ['pipe', 'pipe', '
|
|
247
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
234
248
|
env: buildServeEnv(),
|
|
235
249
|
timeout: syncServeTimeoutMs,
|
|
236
250
|
maxBuffer: MAX_PROTOCOL_BYTES + 4096,
|
|
237
251
|
});
|
|
252
|
+
logServeStderr(result.stderr);
|
|
238
253
|
if (result.error) {
|
|
239
254
|
const err = result.error;
|
|
240
255
|
if (err.code === 'ETIMEDOUT') {
|
|
@@ -11,6 +11,7 @@ export interface UpdateCheckCache {
|
|
|
11
11
|
export declare function readUpdateCache(file: string): UpdateCheckCache | null;
|
|
12
12
|
export declare function saveUpdateCheck(file: string, latestVersion: string): void;
|
|
13
13
|
export declare function dismissUpdateVersion(file: string, version: string): void;
|
|
14
|
+
export declare function isPeerHop(env?: NodeJS.ProcessEnv): boolean;
|
|
14
15
|
export declare function shouldPromptUpgrade(cache: UpdateCheckCache | null, currentVersion: string): boolean;
|
|
15
16
|
export declare const MULTI_INSTALL_SCAN_TTL_MS: number;
|
|
16
17
|
export interface MultiInstallScanCache {
|
package/dist/lib/self-update.js
CHANGED
|
@@ -8,6 +8,7 @@ import { promisify } from 'util';
|
|
|
8
8
|
const execFileAsync = promisify(execFile);
|
|
9
9
|
import { compareVersions } from './agent-spec/primitives.js';
|
|
10
10
|
import { needsWindowsShell } from './platform/index.js';
|
|
11
|
+
import { PEER_HOP_ENV } from './types.js';
|
|
11
12
|
export const NPM_PACKAGE_NAME = '@phnx-labs/agents-cli';
|
|
12
13
|
export const TOUCH_ID_STORM_FIXED_SINCE = '1.22.30';
|
|
13
14
|
export function bunGlobalDir() {
|
|
@@ -65,6 +66,9 @@ export function dismissUpdateVersion(file, version) {
|
|
|
65
66
|
catch {
|
|
66
67
|
}
|
|
67
68
|
}
|
|
69
|
+
export function isPeerHop(env = process.env) {
|
|
70
|
+
return env[PEER_HOP_ENV] === '1';
|
|
71
|
+
}
|
|
68
72
|
export function shouldPromptUpgrade(cache, currentVersion) {
|
|
69
73
|
if (!cache?.latestVersion)
|
|
70
74
|
return false;
|
|
@@ -25,6 +25,11 @@ export declare function sessionAccountLabel(kind: string, session: Pick<SessionM
|
|
|
25
25
|
export declare function backfillActiveRowsFromIndex(sessions: ActiveSession[]): void;
|
|
26
26
|
export declare function isRunningLiveSession(s: ActiveSession): boolean;
|
|
27
27
|
export declare function activeSessionProjectKey(s: Pick<ActiveSession, 'cwd' | 'context'>): string;
|
|
28
|
+
export type ArtifactKind = 'image' | 'video' | 'html' | 'markdown' | 'pdf' | 'other';
|
|
29
|
+
export type SessionArtifactRow = import('@phnx-labs/sessions-cli/reader').ProducedArtifact & {
|
|
30
|
+
kind?: ArtifactKind;
|
|
31
|
+
};
|
|
32
|
+
export declare function artifactKind(file: string): ArtifactKind;
|
|
28
33
|
export declare function serializeActiveSessionsForJson(sessions: ActiveSession[]): Array<Omit<ActiveSession, 'viewingIn'> & {
|
|
29
34
|
ticketId: string | null;
|
|
30
35
|
project: string;
|
|
@@ -102,7 +107,7 @@ export interface ActiveSession {
|
|
|
102
107
|
tokenCount?: number;
|
|
103
108
|
durationMs?: number;
|
|
104
109
|
subAgentCount?: number;
|
|
105
|
-
artifacts?:
|
|
110
|
+
artifacts?: SessionArtifactRow[];
|
|
106
111
|
planFile?: string;
|
|
107
112
|
sessionFile?: string;
|
|
108
113
|
startedAtMs?: number;
|
|
@@ -183,6 +183,16 @@ export function activeSessionProjectKey(s) {
|
|
|
183
183
|
return path.basename(s.cwd);
|
|
184
184
|
return s.context === 'cloud' ? 'cloud' : 'other';
|
|
185
185
|
}
|
|
186
|
+
const ARTIFACT_KINDS = [
|
|
187
|
+
[/\.(png|jpe?g|gif|webp|svg|avif|heic)$/i, 'image'],
|
|
188
|
+
[/\.(mp4|mov|webm|m4v)$/i, 'video'],
|
|
189
|
+
[/\.html?$/i, 'html'],
|
|
190
|
+
[/\.(md|markdown)$/i, 'markdown'],
|
|
191
|
+
[/\.pdf$/i, 'pdf'],
|
|
192
|
+
];
|
|
193
|
+
export function artifactKind(file) {
|
|
194
|
+
return ARTIFACT_KINDS.find(([re]) => re.test(file))?.[1] ?? 'other';
|
|
195
|
+
}
|
|
186
196
|
export function serializeActiveSessionsForJson(sessions) {
|
|
187
197
|
const defs = listProjectDefsCached();
|
|
188
198
|
return sessions.map((s) => ({
|
|
@@ -476,7 +486,7 @@ export function lifecycleStatus(pidAlive, mtimeMs, nowMs = Date.now()) {
|
|
|
476
486
|
}
|
|
477
487
|
export function resolveFallbackStatus(sessionFile, pidAlive, nowMs = Date.now()) {
|
|
478
488
|
const { mtimeMs } = sessionFileTimes(sessionFile);
|
|
479
|
-
return lifecycleStatus(pidAlive, mtimeMs, nowMs) ?? '
|
|
489
|
+
return lifecycleStatus(pidAlive, mtimeMs, nowMs) ?? 'unknown';
|
|
480
490
|
}
|
|
481
491
|
export function findSessionFileForKind(kind, cwd, sessionId) {
|
|
482
492
|
if (!cwd)
|
|
@@ -521,7 +531,7 @@ export function clearLiveSignalsCacheForTest() {
|
|
|
521
531
|
}
|
|
522
532
|
function parseLiveTail(kind, sessionFile, mtimeMs) {
|
|
523
533
|
if (kind === 'claude' || kind === 'codex') {
|
|
524
|
-
const { events, content } = readSessionTailWithRaw(sessionFile, kind);
|
|
534
|
+
const { events, content } = readSessionTailWithRaw(sessionFile, kind, undefined, undefined, { includeInterrupts: true });
|
|
525
535
|
const tokPerSec = events.length > 0 ? computeTokPerSec(content, kind) : 0;
|
|
526
536
|
return { mtimeMs, events, tokPerSec: tokPerSec > 0 ? tokPerSec : undefined };
|
|
527
537
|
}
|
|
@@ -30,4 +30,5 @@ export declare function writePidSessionEntry(entry: PidSessionEntry): void;
|
|
|
30
30
|
export declare function readPidSessionEntry(pid: number): PidSessionEntry | undefined;
|
|
31
31
|
export declare function readLivePidSessionEntry(pid: number, startTime?: string): PidSessionEntry | undefined;
|
|
32
32
|
export declare function listPidSessionEntries(): PidSessionEntry[];
|
|
33
|
+
export declare function liveSessionProcesses(sessionId: string): PidSessionEntry[];
|
|
33
34
|
export declare function prunePidSessionRegistry(isAlive?: (pid: number, startedAtMs?: number) => boolean | undefined): void;
|
|
@@ -238,6 +238,12 @@ export function listPidSessionEntries() {
|
|
|
238
238
|
}
|
|
239
239
|
return out;
|
|
240
240
|
}
|
|
241
|
+
export function liveSessionProcesses(sessionId) {
|
|
242
|
+
return listPidSessionEntries()
|
|
243
|
+
.filter((entry) => entry.sessionId === sessionId)
|
|
244
|
+
.map((entry) => readLivePidSessionEntry(entry.pid))
|
|
245
|
+
.filter((entry) => entry?.sessionId === sessionId);
|
|
246
|
+
}
|
|
241
247
|
export function prunePidSessionRegistry(isAlive) {
|
|
242
248
|
let files;
|
|
243
249
|
try {
|
|
@@ -39,11 +39,13 @@ export type PeerPreviewEnvelopeResult = {
|
|
|
39
39
|
};
|
|
40
40
|
export declare function fetchPeerPreviewEnvelope(sessionId: string, machine: string, timeoutMs?: number): Promise<PeerPreviewEnvelopeResult>;
|
|
41
41
|
export declare function parsePeerPreviewDigest(parsed: unknown): unknown | undefined;
|
|
42
|
-
export declare function peerHopOutcome(code: number | null): 'ok' | 'unreachable';
|
|
42
|
+
export declare function peerHopOutcome(code: number | null, hostAnswers: () => boolean): 'ok' | 'unreachable';
|
|
43
|
+
export declare function peerAnswers(target: string): boolean;
|
|
43
44
|
export declare function peerHopCloseNotice(opts: {
|
|
44
45
|
tty?: boolean;
|
|
45
46
|
sessionId?: string;
|
|
46
47
|
}, machine: string, code: number | null): string | undefined;
|
|
48
|
+
export declare function quietLoginShell(inner: string): string;
|
|
47
49
|
export declare function runOnPeer(args: string[], machine: string, opts?: {
|
|
48
50
|
tty?: boolean;
|
|
49
51
|
env?: Record<string, string>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { spawn } from 'child_process';
|
|
1
|
+
import { spawn, spawnSync } from 'child_process';
|
|
2
2
|
import chalk from 'chalk';
|
|
3
|
-
import { SSH_OPTS, controlOpts, assertValidSshTarget, shellQuote, SSH_CONN_FAILURE_CODE, REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator, } from '../../ssh-exec.js';
|
|
3
|
+
import { SSH_OPTS, controlOpts, sshExec, assertValidSshTarget, shellQuote, SSH_CONN_FAILURE_CODE, REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator, } from '../../ssh-exec.js';
|
|
4
4
|
import { connectionEndedNotice } from '../../hosts/reconnect.js';
|
|
5
5
|
import { sshTargetFor } from '../../devices/connect.js';
|
|
6
6
|
import { loadDevices, isDialableDevice } from '../../devices/registry.js';
|
|
@@ -9,6 +9,8 @@ import { gatherRemoteAgentsJson } from '../../remote-agents-json.js';
|
|
|
9
9
|
import { normalizeHost } from '../sync/config.js';
|
|
10
10
|
import { NO_FANOUT_ENV } from '../remote-active.js';
|
|
11
11
|
import { terminalWidth } from '../../text/width.js';
|
|
12
|
+
import { PEER_HOP_ENV } from '../../types.js';
|
|
13
|
+
import { markAgentStarted } from '../../launch-log.js';
|
|
12
14
|
export function remoteListCommand(forwardedArgs, os) {
|
|
13
15
|
if (remoteShellFor(os) === 'powershell') {
|
|
14
16
|
return buildWindowsAgentsCommand({
|
|
@@ -178,43 +180,87 @@ export function parsePeerPreviewDigest(parsed) {
|
|
|
178
180
|
return undefined;
|
|
179
181
|
return preview;
|
|
180
182
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
+
const PEER_PROBE_TIMEOUT_MS = 15_000;
|
|
184
|
+
export function peerHopOutcome(code, hostAnswers) {
|
|
185
|
+
if (code === null)
|
|
186
|
+
return 'unreachable';
|
|
187
|
+
if (code !== SSH_CONN_FAILURE_CODE)
|
|
188
|
+
return 'ok';
|
|
189
|
+
return hostAnswers() ? 'ok' : 'unreachable';
|
|
190
|
+
}
|
|
191
|
+
export function peerAnswers(target) {
|
|
192
|
+
return sshExec(target, 'true', { multiplex: false, timeoutMs: PEER_PROBE_TIMEOUT_MS }).code === 0;
|
|
183
193
|
}
|
|
184
194
|
export function peerHopCloseNotice(opts, machine, code) {
|
|
185
195
|
if (!opts.tty || !opts.sessionId)
|
|
186
196
|
return undefined;
|
|
187
197
|
return connectionEndedNotice({ kind: 'session', id: opts.sessionId }, machine, { dropped: code === SSH_CONN_FAILURE_CODE });
|
|
188
198
|
}
|
|
199
|
+
export function quietLoginShell(inner) {
|
|
200
|
+
const log = '"$HOME/.agents/.cache/logs/peer-login.log"';
|
|
201
|
+
const login = [
|
|
202
|
+
'mkdir -p "$HOME/.agents/.cache/logs"',
|
|
203
|
+
`exec 3>&1 4>&2 >>${log} 2>&1`,
|
|
204
|
+
'[ -r /etc/profile ] && . /etc/profile',
|
|
205
|
+
'for f in "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"; do if [ -r "$f" ]; then . "$f"; break; fi; done',
|
|
206
|
+
'exec 1>&3 2>&4 3>&- 4>&-',
|
|
207
|
+
].join('; ');
|
|
208
|
+
return `bash -c ${shellQuote(`${login}; ${inner}`)}`;
|
|
209
|
+
}
|
|
210
|
+
function spawnHop(sshArgs) {
|
|
211
|
+
return new Promise((resolve) => {
|
|
212
|
+
const child = spawn('ssh', sshArgs, { stdio: 'inherit' });
|
|
213
|
+
child.on('error', () => resolve(null));
|
|
214
|
+
child.on('close', (code) => resolve(code));
|
|
215
|
+
});
|
|
216
|
+
}
|
|
189
217
|
export async function runOnPeer(args, machine, opts = {}) {
|
|
190
218
|
const peer = await resolvePeerTarget(machine);
|
|
191
219
|
if (!peer)
|
|
192
220
|
return 'no-target';
|
|
193
221
|
assertValidSshTarget(peer.target);
|
|
194
222
|
const cols = terminalWidth();
|
|
195
|
-
const env = {
|
|
223
|
+
const env = {
|
|
224
|
+
...(cols > 0 ? { COLUMNS: String(cols) } : {}),
|
|
225
|
+
[PEER_HOP_ENV]: '1',
|
|
226
|
+
...opts.env,
|
|
227
|
+
};
|
|
196
228
|
const assignments = Object.entries(env).map(([k, v]) => `${k}=${shellQuote(v)}`);
|
|
197
229
|
const invocation = assignments.concat(['agents', ...args].map(shellQuote)).join(' ');
|
|
198
230
|
const remoteCmd = remoteShellFor(peer.os) === 'powershell'
|
|
199
231
|
? buildWindowsAgentsCommand({ args, env: assignments.length ? env : undefined, remapExit255: true })
|
|
200
|
-
:
|
|
201
|
-
const sshArgs = [...SSH_OPTS, ...controlOpts()];
|
|
232
|
+
: quietLoginShell(`${invocation}; agents_rc=$?; if [ "$agents_rc" -eq 255 ]; then exit 254; fi; exit "$agents_rc"`);
|
|
233
|
+
const sshArgs = [...SSH_OPTS, ...(opts.tty ? [] : controlOpts())];
|
|
202
234
|
if (opts.tty)
|
|
203
235
|
sshArgs.push('-tt');
|
|
204
236
|
sshArgs.push(peer.target, remoteCmd);
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
237
|
+
if (opts.tty)
|
|
238
|
+
markAgentStarted();
|
|
239
|
+
const code = await spawnHop(sshArgs);
|
|
240
|
+
if (code === null) {
|
|
241
|
+
process.stderr.write(chalk.red(`Failed to reach ${machine}: ssh failed to launch\n`));
|
|
242
|
+
return 'unreachable';
|
|
243
|
+
}
|
|
244
|
+
if (code === SSH_CONN_FAILURE_CODE && opts.tty && opts.sessionId && peerAnswers(peer.target)) {
|
|
245
|
+
const { reconnectInteractiveSession } = await import('../../hosts/reconnect.js');
|
|
246
|
+
const rc = await reconnectInteractiveSession({
|
|
247
|
+
hostName: machine,
|
|
248
|
+
target: { kind: 'session', id: opts.sessionId },
|
|
249
|
+
initialExit: code,
|
|
250
|
+
reattach: () => {
|
|
251
|
+
if (!peerAnswers(peer.target))
|
|
252
|
+
return { code: SSH_CONN_FAILURE_CODE, connected: false, heldMs: 0 };
|
|
253
|
+
const startedAt = Date.now();
|
|
254
|
+
const res = spawnSync('ssh', sshArgs, { stdio: 'inherit' });
|
|
255
|
+
return { code: res.status ?? SSH_CONN_FAILURE_CODE, connected: true, heldMs: Date.now() - startedAt };
|
|
256
|
+
},
|
|
216
257
|
});
|
|
217
|
-
|
|
258
|
+
return rc === SSH_CONN_FAILURE_CODE && !peerAnswers(peer.target) ? 'unreachable' : 'ok';
|
|
259
|
+
}
|
|
260
|
+
const notice = peerHopCloseNotice(opts, machine, code);
|
|
261
|
+
if (notice)
|
|
262
|
+
process.stderr.write(notice);
|
|
263
|
+
return peerHopOutcome(code, () => peerAnswers(peer.target));
|
|
218
264
|
}
|
|
219
265
|
export function hostToken(h) {
|
|
220
266
|
return normalizeHost(h.split('@').pop() || h);
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { type RemoteAgentsJsonParseResult } from '../remote-agents-json.js';
|
|
1
2
|
import type { ActiveSession } from './active.js';
|
|
2
3
|
export declare const NO_FANOUT_ENV = "AGENTS_SESSIONS_LOCAL";
|
|
3
|
-
export declare function parseRemoteActive(stdout: string, machine: string): ActiveSession
|
|
4
|
+
export declare function parseRemoteActive(stdout: string, machine: string): RemoteAgentsJsonParseResult<ActiveSession>;
|
|
4
5
|
interface RemoteActiveResult {
|
|
5
6
|
sessions: ActiveSession[];
|
|
6
7
|
deviceCount: number;
|
|
7
8
|
skipped: string[];
|
|
9
|
+
answered: string[];
|
|
8
10
|
discoveryFailed: boolean;
|
|
9
11
|
}
|
|
10
12
|
export declare function gatherRemoteActive(hosts?: string[], opts?: {
|
|
@@ -7,10 +7,10 @@ export function parseRemoteActive(stdout, machine) {
|
|
|
7
7
|
parsed = JSON.parse(stdout);
|
|
8
8
|
}
|
|
9
9
|
catch {
|
|
10
|
-
return [];
|
|
10
|
+
return { items: [], valid: false };
|
|
11
11
|
}
|
|
12
12
|
if (!Array.isArray(parsed))
|
|
13
|
-
return [];
|
|
13
|
+
return { items: [], valid: false };
|
|
14
14
|
const out = [];
|
|
15
15
|
for (const x of parsed) {
|
|
16
16
|
if (x && typeof x === 'object' && !Array.isArray(x)) {
|
|
@@ -23,7 +23,7 @@ export function parseRemoteActive(stdout, machine) {
|
|
|
23
23
|
out.push(row);
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
return out;
|
|
26
|
+
return { items: out, valid: true };
|
|
27
27
|
}
|
|
28
28
|
export async function gatherRemoteActive(hosts, opts) {
|
|
29
29
|
const result = await gatherRemoteAgentsJson({
|
|
@@ -38,6 +38,7 @@ export async function gatherRemoteActive(hosts, opts) {
|
|
|
38
38
|
sessions: result.items,
|
|
39
39
|
deviceCount: result.deviceCount,
|
|
40
40
|
skipped: result.skipped,
|
|
41
|
+
answered: result.answered,
|
|
41
42
|
discoveryFailed: result.discoveryFailed,
|
|
42
43
|
};
|
|
43
44
|
}
|
|
@@ -66,6 +66,7 @@ export declare function stripLiveStatusKeys<T extends Record<string, unknown>>(f
|
|
|
66
66
|
export declare function assertNoLiveStatusFields(fields: Record<string, unknown>): boolean;
|
|
67
67
|
export declare function updateImmutableMemos(sessions: ReadonlyArray<ActiveSession>, nowMs?: number): void;
|
|
68
68
|
export declare function resolveStreamSummaryState(current: import('@phnx-labs/sessions-cli/reader').SummaryState | undefined, nowMs?: number): import('@phnx-labs/sessions-cli/reader').SummaryState;
|
|
69
|
+
export declare function withCreatedArtifacts(s: ActiveSession): ActiveSession;
|
|
69
70
|
export declare function mergeSessionTimeline(s: ActiveSession): ActiveSession;
|
|
70
71
|
export declare function applyImmutableMemo(s: ActiveSession): ActiveSession;
|
|
71
72
|
interface LoadLocalActiveSessionsOptions {
|
|
@@ -3,7 +3,8 @@ import { writerProcessView, requireWriterProcessView } from './process-view.js';
|
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { createMemoryCache } from '../memory-cache.js';
|
|
5
5
|
import { getCacheDir } from '../state.js';
|
|
6
|
-
import { backfillActiveRowsFromIndex, foldRecap, sessionProcessIsLocal } from './active.js';
|
|
6
|
+
import { artifactKind, backfillActiveRowsFromIndex, foldRecap, sessionProcessIsLocal } from './active.js';
|
|
7
|
+
import { extractArtifacts, mergeArtifacts } from '@phnx-labs/sessions-cli/reader';
|
|
7
8
|
import { enrichGlanceFiles } from './glance-files.js';
|
|
8
9
|
import { readSessionSummaryAny, readSessionTimelineAny } from './db.js';
|
|
9
10
|
import { isSummarizerReady } from '../summarizer/config.js';
|
|
@@ -319,6 +320,15 @@ export function resolveStreamSummaryState(current, nowMs = Date.now()) {
|
|
|
319
320
|
return current;
|
|
320
321
|
return isSummarizerReady(nowMs) ? 'pending' : 'skipped';
|
|
321
322
|
}
|
|
323
|
+
export function withCreatedArtifacts(s) {
|
|
324
|
+
const created = (s.files?.changes ?? [])
|
|
325
|
+
.filter((c) => c.op === 'created')
|
|
326
|
+
.map((c) => ({ path: path.isAbsolute(c.path) || !s.cwd ? c.path : path.resolve(s.cwd, c.path), op: c.op }));
|
|
327
|
+
const merged = created.length > 0 ? mergeArtifacts(extractArtifacts(created), s.artifacts ?? []) : (s.artifacts ?? []);
|
|
328
|
+
if (merged.length > 0)
|
|
329
|
+
s.artifacts = merged.map((a) => ({ ...a, kind: artifactKind(a.path) }));
|
|
330
|
+
return s;
|
|
331
|
+
}
|
|
322
332
|
export function mergeSessionTimeline(s) {
|
|
323
333
|
if (!s.sessionId)
|
|
324
334
|
return s;
|
|
@@ -348,6 +358,9 @@ export function mergeSessionTimeline(s) {
|
|
|
348
358
|
return s;
|
|
349
359
|
}
|
|
350
360
|
export function applyImmutableMemo(s) {
|
|
361
|
+
return withCreatedArtifacts(applyStoredFields(s));
|
|
362
|
+
}
|
|
363
|
+
function applyStoredFields(s) {
|
|
351
364
|
if (!s.sessionId)
|
|
352
365
|
return s;
|
|
353
366
|
mergeSessionSummary(s);
|
package/dist/lib/ssh-exec.js
CHANGED
|
@@ -361,7 +361,7 @@ export function saveLocalTerminal() {
|
|
|
361
361
|
}
|
|
362
362
|
export function sshStream(target, remoteCmd, opts = {}) {
|
|
363
363
|
assertValidSshTarget(target);
|
|
364
|
-
const mux = opts.multiplex === false ? [] : controlOpts();
|
|
364
|
+
const mux = opts.multiplex === false || opts.tty ? [] : controlOpts();
|
|
365
365
|
const tty = opts.tty ? ['-tt'] : [];
|
|
366
366
|
const args = [...sshConnectOpts(mux, opts.hostKeyOpts), ...(opts.extraSshArgs ?? []), ...tty, target, remoteCmd];
|
|
367
367
|
const saved = opts.tty ? saveLocalTerminal() : undefined;
|
|
@@ -1,18 +1,41 @@
|
|
|
1
|
-
import type { TerminalBackend, LaunchSpec, SplitDirection } from '../types.js';
|
|
1
|
+
import type { TerminalBackend, LaunchSpec, SplitDirection, SurfaceMeta } from '../types.js';
|
|
2
2
|
export interface EditorVariant {
|
|
3
3
|
cli: string;
|
|
4
4
|
scheme: string;
|
|
5
5
|
app: string;
|
|
6
6
|
label: string;
|
|
7
|
+
dataDir?: string;
|
|
7
8
|
}
|
|
8
9
|
export declare const EDITOR_VARIANTS: EditorVariant[];
|
|
9
|
-
export declare function
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}): string;
|
|
10
|
+
export declare function editorWindowFor(folder: string, storageJson: string | undefined): string;
|
|
11
|
+
export declare function editorFolderNamed(project: string, storageJson: string | undefined): string | undefined;
|
|
12
|
+
export declare function storageJsonFor(variant: EditorVariant, env?: NodeJS.ProcessEnv): string | undefined;
|
|
13
|
+
export declare function spawnUri(scheme: string, cwd: string, command: string[], direction?: SplitDirection, meta?: SurfaceMeta): string;
|
|
14
14
|
export declare function editorVariantForHost(host: string | undefined): EditorVariant | undefined;
|
|
15
15
|
export declare function focusUri(scheme: string, terminalId: string): string;
|
|
16
16
|
export declare function focusTabSpecs(variant: EditorVariant, folder: string, terminalId: string): LaunchSpec[];
|
|
17
|
-
export declare function makeVscodiumAgentBackend(variant: EditorVariant): TerminalBackend
|
|
18
|
-
|
|
17
|
+
export declare function makeVscodiumAgentBackend(variant: EditorVariant): TerminalBackend & {
|
|
18
|
+
variant: EditorVariant;
|
|
19
|
+
};
|
|
20
|
+
export declare const vscodiumAgentBackend: TerminalBackend & {
|
|
21
|
+
variant: EditorVariant;
|
|
22
|
+
};
|
|
23
|
+
export type SpawnAckStatus = 'opened' | 'focused-existing' | 'wrong-window' | 'failed';
|
|
24
|
+
export interface SpawnAck {
|
|
25
|
+
nonce: string;
|
|
26
|
+
status: SpawnAckStatus;
|
|
27
|
+
windowFolders: string[];
|
|
28
|
+
workspaceName?: string;
|
|
29
|
+
terminalId?: string;
|
|
30
|
+
title?: string;
|
|
31
|
+
sessionId?: string;
|
|
32
|
+
pid?: number;
|
|
33
|
+
reason?: string;
|
|
34
|
+
at: number;
|
|
35
|
+
}
|
|
36
|
+
export declare const SPAWN_ACK_TIMEOUT_MS = 15000;
|
|
37
|
+
export declare function spawnAckRelPath(nonce: string): string;
|
|
38
|
+
export declare function localSpawnAckPath(nonce: string): string;
|
|
39
|
+
export declare function parseSpawnAck(raw: string, nonce: string): SpawnAck | undefined;
|
|
40
|
+
export declare function awaitSpawnAck(nonce: string, read: () => string | undefined, timeoutMs?: number): Promise<SpawnAck | undefined>;
|
|
41
|
+
export declare function ackLandedIn(ack: SpawnAck, project: string | undefined): boolean;
|