@phnx-labs/agents-cli 1.23.4 → 1.23.6

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/bootstrap.js +14 -9
  3. package/dist/commands/exec.js +7 -7
  4. package/dist/commands/focus.js +17 -16
  5. package/dist/commands/go.js +2 -2
  6. package/dist/commands/ps-roster.d.ts +1 -1
  7. package/dist/commands/ps-roster.js +7 -5
  8. package/dist/commands/resume.d.ts +1 -0
  9. package/dist/commands/resume.js +9 -1
  10. package/dist/commands/sessions-resume.js +65 -18
  11. package/dist/commands/setup-terminal.js +3 -2
  12. package/dist/lib/exec.js +6 -1
  13. package/dist/lib/hosts/reconnect.d.ts +3 -2
  14. package/dist/lib/hosts/reconnect.js +8 -9
  15. package/dist/lib/launch-log.d.ts +15 -0
  16. package/dist/lib/launch-log.js +120 -0
  17. package/dist/lib/project-root.d.ts +1 -0
  18. package/dist/lib/project-root.js +9 -0
  19. package/dist/lib/remote-agents-json.d.ts +1 -0
  20. package/dist/lib/remote-agents-json.js +4 -2
  21. package/dist/lib/secrets-client.js +18 -3
  22. package/dist/lib/self-update.d.ts +1 -0
  23. package/dist/lib/self-update.js +4 -0
  24. package/dist/lib/session/active.d.ts +9 -3
  25. package/dist/lib/session/active.js +19 -5
  26. package/dist/lib/session/pid-registry.d.ts +1 -0
  27. package/dist/lib/session/pid-registry.js +6 -0
  28. package/dist/lib/session/remote/remote-list.d.ts +3 -1
  29. package/dist/lib/session/remote/remote-list.js +65 -19
  30. package/dist/lib/session/remote-active.d.ts +3 -1
  31. package/dist/lib/session/remote-active.js +4 -3
  32. package/dist/lib/session/session-cache.d.ts +1 -0
  33. package/dist/lib/session/session-cache.js +14 -1
  34. package/dist/lib/ssh-exec.js +1 -1
  35. package/dist/lib/terminal/backends/vscodium-agent.d.ts +31 -8
  36. package/dist/lib/terminal/backends/vscodium-agent.js +134 -7
  37. package/dist/lib/terminal/engine.d.ts +7 -1
  38. package/dist/lib/terminal/engine.js +68 -9
  39. package/dist/lib/terminal/index.d.ts +1 -1
  40. package/dist/lib/terminal/index.js +1 -1
  41. package/dist/lib/terminal/run-surface.d.ts +1 -0
  42. package/dist/lib/terminal/run-surface.js +8 -2
  43. package/dist/lib/terminal/types.d.ts +6 -2
  44. package/dist/lib/types.d.ts +1 -0
  45. package/dist/lib/types.js +1 -0
  46. package/package.json +1 -1
@@ -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;
@@ -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', 'inherit', 'pipe', 'pipe'],
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', 'inherit'],
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 {
@@ -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;
@@ -17,7 +17,7 @@ export declare function clearActiveScanCachesForTest(): void;
17
17
  export declare function processTableLiveReadCountForTest(): number;
18
18
  export declare function unattributedFullRescanCountForTest(): number;
19
19
  export declare function attributedSetLostPids(prev: Set<number>, next: Set<number>): boolean;
20
- export declare function filterCachedUnattributed(sessions: ActiveSession[], attributed: Set<number>, alive: (pid: number, startedAtMs?: number) => boolean, ppidMap?: Map<number, number>): ActiveSession[];
20
+ export declare function filterCachedUnattributed(sessions: ActiveSession[], attributed: Set<number>, alive: (pid: number, processStartedAtMs?: number) => boolean, ppidMap?: Map<number, number>): ActiveSession[];
21
21
  type ActiveContext = 'terminal' | 'teams' | 'cloud' | 'headless';
22
22
  export type BackfillMeta = Pick<SessionMeta, 'version' | 'account' | 'accountId' | 'accountKey' | 'timestamp' | 'label' | 'firstUserMessage' | 'lastUserMessage' | 'generatedTitle' | 'ticketId' | 'prUrl' | 'prNumber' | 'origin' | 'routineName' | 'harness' | 'tokenCount' | 'durationMs' | 'subAgentCount' | 'lastActivity'>;
23
23
  export declare function backfillActiveRowsFromMeta(sessions: ActiveSession[], metaById: Map<string, BackfillMeta>): void;
@@ -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,10 +107,11 @@ export interface ActiveSession {
102
107
  tokenCount?: number;
103
108
  durationMs?: number;
104
109
  subAgentCount?: number;
105
- artifacts?: import('@phnx-labs/sessions-cli/reader').ProducedArtifact[];
110
+ artifacts?: SessionArtifactRow[];
106
111
  planFile?: string;
107
112
  sessionFile?: string;
108
113
  startedAtMs?: number;
114
+ processStartedAtMs?: number;
109
115
  version?: string;
110
116
  account?: string;
111
117
  accountLabel?: string;
@@ -173,7 +179,7 @@ export declare function resolveNamesToSessionIds(sessionNames: string[], deps: {
173
179
  }): Map<string, string>;
174
180
  export declare const PROCESS_START_CACHE_TTL_MS = 30000;
175
181
  export declare function processStartMs(pid: number, now?: number): number | null;
176
- export declare function isPidAlive(pid: number, startedAtMs?: number): boolean;
182
+ export declare function isPidAlive(pid: number, processStartedAtMs?: number): boolean;
177
183
  export declare function pickClaudeSessionFileAcrossRoots(projectRoots: string[], cwd: string, sessionId?: string): string | undefined;
178
184
  export declare function pickSessionFile(projectDir: string, sessionId?: string): string | undefined;
179
185
  export declare function sessionFileTimes(sessionFile: string | undefined): {
@@ -77,7 +77,7 @@ export function filterCachedUnattributed(sessions, attributed, alive, ppidMap) {
77
77
  return false;
78
78
  if (attributed.has(s.pid) || (ppidMap && hasAttributedAncestor(s.pid, ppidMap, attributed)))
79
79
  return false;
80
- return alive(s.pid, s.startedAtMs);
80
+ return alive(s.pid, s.processStartedAtMs);
81
81
  });
82
82
  }
83
83
  export function backfillActiveRowsFromMeta(sessions, metaById) {
@@ -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) => ({
@@ -331,7 +341,7 @@ export function processStartMs(pid, now = Date.now()) {
331
341
  processStartCache.set(pid, ms);
332
342
  return ms;
333
343
  }
334
- export function isPidAlive(pid, startedAtMs) {
344
+ export function isPidAlive(pid, processStartedAtMs) {
335
345
  if (!pid || pid < 1)
336
346
  return false;
337
347
  try {
@@ -341,10 +351,10 @@ export function isPidAlive(pid, startedAtMs) {
341
351
  if (err?.code !== 'EPERM')
342
352
  return false;
343
353
  }
344
- if (startedAtMs && startedAtMs > 0) {
354
+ if (processStartedAtMs && processStartedAtMs > 0) {
345
355
  // A live recycled PID must not revive an unrelated dead session.
346
356
  const procStartMs = processStartMs(pid);
347
- if (procStartMs !== null && procStartMs > startedAtMs + PID_REUSE_TOLERANCE_MS) {
357
+ if (procStartMs !== null && procStartMs > processStartedAtMs + PID_REUSE_TOLERANCE_MS) {
348
358
  return false;
349
359
  }
350
360
  }
@@ -1084,6 +1094,9 @@ async function listUnattributedActiveLive(attributed) {
1084
1094
  if (stateRec)
1085
1095
  exactId = stateRec.session_id;
1086
1096
  }
1097
+ const launchId = entry?.launchId ?? hookRec?.launch_id;
1098
+ if (!exactId && !launchId)
1099
+ continue;
1087
1100
  const cwd = cwds[i] ?? entry?.cwd ?? undefined;
1088
1101
  const sessionFile = findSessionFileForKind(kind, cwd, exactId);
1089
1102
  const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
@@ -1109,10 +1122,11 @@ async function listUnattributedActiveLive(attributed) {
1109
1122
  tokPerSec,
1110
1123
  sessionFile,
1111
1124
  startedAtMs: hookRec?.ts ?? birthtimeMs,
1125
+ processStartedAtMs: parseStartMs(procByPid.get(pid)?.startTime ?? '') ?? undefined,
1112
1126
  lastActivityMs: mtimeMs,
1113
1127
  pidCount: 1 + (foldedByRoot.get(pid) ?? 0),
1114
1128
  owner: resolveOwner(entry?.actor, resolvedId),
1115
- launchId: entry?.launchId ?? hookRec?.launch_id,
1129
+ launchId,
1116
1130
  terminalId: entry?.terminalId ?? hookRec?.terminal_id,
1117
1131
  originTerminal: entry?.originTerminal,
1118
1132
  }, state, sessionFile, true));
@@ -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
- export function peerHopOutcome(code) {
182
- return code === SSH_CONN_FAILURE_CODE || code === null ? 'unreachable' : 'ok';
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 = { ...(cols > 0 ? { COLUMNS: String(cols) } : {}), ...opts.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
- : `bash -lc ${shellQuote(`${invocation}; agents_rc=$?; if [ "$agents_rc" -eq 255 ]; then exit 254; fi; exit "$agents_rc"`)}`;
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
- return new Promise((resolve) => {
206
- const child = spawn('ssh', sshArgs, { stdio: 'inherit' });
207
- child.on('error', (err) => {
208
- process.stderr.write(chalk.red(`Failed to reach ${machine}: ${err?.message ?? 'ssh failed to launch'}\n`));
209
- resolve('unreachable');
210
- });
211
- child.on('close', (code) => {
212
- const notice = peerHopCloseNotice(opts, machine, code);
213
- if (notice)
214
- process.stderr.write(notice);
215
- resolve(peerHopOutcome(code));
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);
@@ -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;