@phnx-labs/agents-cli 1.23.18 → 1.23.19

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 (71) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/dist/bootstrap.js +1 -1
  3. package/dist/commands/cloud.js +1 -1
  4. package/dist/commands/config.js +1 -1
  5. package/dist/commands/detach.js +5 -1
  6. package/dist/commands/doctor.js +11 -7
  7. package/dist/commands/exec.d.ts +0 -17
  8. package/dist/commands/exec.js +16 -50
  9. package/dist/commands/focus.d.ts +10 -2
  10. package/dist/commands/focus.js +80 -19
  11. package/dist/commands/projects-todo.js +10 -5
  12. package/dist/commands/ps.d.ts +8 -2
  13. package/dist/commands/ps.js +175 -92
  14. package/dist/commands/sessions-picker.d.ts +0 -7
  15. package/dist/commands/sessions-picker.js +5 -299
  16. package/dist/commands/sessions-stop.js +2 -2
  17. package/dist/lib/account-registry.d.ts +3 -0
  18. package/dist/lib/account-registry.js +40 -0
  19. package/dist/lib/accounting/usage-sync.d.ts +1 -0
  20. package/dist/lib/accounting/usage-sync.js +20 -3
  21. package/dist/lib/accounting/usage.d.ts +4 -1
  22. package/dist/lib/accounting/usage.js +38 -6
  23. package/dist/lib/agent-spec/agents.js +12 -11
  24. package/dist/lib/cloud/store.d.ts +5 -1
  25. package/dist/lib/cloud/store.js +10 -3
  26. package/dist/lib/config-keys.d.ts +1 -1
  27. package/dist/lib/config-keys.js +1 -0
  28. package/dist/lib/daemon/account-state-daemon-service.js +9 -2
  29. package/dist/lib/daemon/self-update-service.js +1 -1
  30. package/dist/lib/device-config.d.ts +2 -1
  31. package/dist/lib/device-config.js +21 -11
  32. package/dist/lib/devices/health.d.ts +6 -0
  33. package/dist/lib/devices/health.js +11 -4
  34. package/dist/lib/feed/watch.js +2 -1
  35. package/dist/lib/fleet/apply.d.ts +1 -1
  36. package/dist/lib/fleet/apply.js +5 -2
  37. package/dist/lib/fleet-shared-state.d.ts +2 -0
  38. package/dist/lib/fleet-shared-state.js +3 -1
  39. package/dist/lib/github/project-prs.js +14 -1
  40. package/dist/lib/helper-versions.js +1 -1
  41. package/dist/lib/installations/versions.js +4 -3
  42. package/dist/lib/project-root.d.ts +1 -0
  43. package/dist/lib/project-root.js +11 -3
  44. package/dist/lib/projects.js +2 -2
  45. package/dist/lib/quick-todo.d.ts +5 -1
  46. package/dist/lib/quick-todo.js +14 -1
  47. package/dist/lib/remote-agents-json.js +4 -2
  48. package/dist/lib/self-update.d.ts +1 -1
  49. package/dist/lib/self-update.js +59 -2
  50. package/dist/lib/session/db.js +1 -1
  51. package/dist/lib/session/glance-files.d.ts +21 -0
  52. package/dist/lib/session/glance-files.js +123 -0
  53. package/dist/lib/session/presentation.d.ts +3 -0
  54. package/dist/lib/session/preview-digest.d.ts +13 -0
  55. package/dist/lib/session/preview-digest.js +328 -0
  56. package/dist/lib/session/remote/remote-list.d.ts +3 -2
  57. package/dist/lib/session/remote/remote-list.js +12 -6
  58. package/dist/lib/session/remote/watch.d.ts +2 -0
  59. package/dist/lib/session/remote/watch.js +86 -5
  60. package/dist/lib/smart-launch.js +6 -1
  61. package/dist/lib/teams/placement-probe.d.ts +2 -0
  62. package/dist/lib/teams/placement-probe.js +8 -3
  63. package/dist/lib/terminal/engine.d.ts +2 -0
  64. package/dist/lib/terminal/engine.js +5 -3
  65. package/dist/lib/terminal/index.d.ts +1 -1
  66. package/dist/lib/terminal/index.js +1 -1
  67. package/dist/lib/terminal/run-surface.d.ts +1 -0
  68. package/dist/lib/terminal/run-surface.js +9 -0
  69. package/package.json +1 -1
  70. package/dist/lib/onepassword.d.ts +0 -57
  71. package/dist/lib/onepassword.js +0 -140
@@ -7,6 +7,7 @@ import { execFile } from 'child_process';
7
7
  import { promisify } from 'util';
8
8
  const execFileAsync = promisify(execFile);
9
9
  import { compareVersions } from './agent-spec/primitives.js';
10
+ import { atomicWriteJsonSync } from './fs-atomic.js';
10
11
  import { needsWindowsShell } from './platform/index.js';
11
12
  import { PEER_HOP_ENV } from './types.js';
12
13
  export const NPM_PACKAGE_NAME = '@phnx-labs/agents-cli';
@@ -243,11 +244,67 @@ export function installLooksSettled(packageRoot, settleMs = INSTALL_SETTLE_MS, n
243
244
  return false;
244
245
  }
245
246
  }
246
- export async function installPackageWithBun(spec, signal) {
247
+ function readBunGlobalManifest(globalDir) {
248
+ try {
249
+ const parsed = JSON.parse(fs.readFileSync(path.join(globalDir, 'package.json'), 'utf-8'));
250
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
251
+ ? parsed
252
+ : null;
253
+ }
254
+ catch {
255
+ return null;
256
+ }
257
+ }
258
+ function setBunGlobalDependency(globalDir, spec) {
259
+ const manifest = readBunGlobalManifest(globalDir);
260
+ if (!manifest)
261
+ return null;
262
+ const deps = manifest.dependencies;
263
+ if (!deps || typeof deps !== 'object' || Array.isArray(deps))
264
+ return null;
265
+ const entries = deps;
266
+ const previous = entries[NPM_PACKAGE_NAME] ?? null;
267
+ if (spec === null) {
268
+ if (!(NPM_PACKAGE_NAME in entries))
269
+ return previous;
270
+ delete entries[NPM_PACKAGE_NAME];
271
+ }
272
+ else {
273
+ if (entries[NPM_PACKAGE_NAME] === spec)
274
+ return previous;
275
+ entries[NPM_PACKAGE_NAME] = spec;
276
+ }
277
+ atomicWriteJsonSync(path.join(globalDir, 'package.json'), manifest);
278
+ return previous;
279
+ }
280
+ function restoreBunGlobalDependency(globalDir, spec) {
281
+ try {
282
+ setBunGlobalDependency(globalDir, spec);
283
+ }
284
+ catch { }
285
+ }
286
+ export async function installPackageWithBun(spec, globalDir, signal) {
247
287
  const { execFile } = await import('child_process');
248
288
  const { promisify } = await import('util');
249
289
  const execFileAsync = promisify(execFile);
250
- await execFileAsync('bun', ['add', '-g', spec, '--ignore-scripts'], { shell: needsWindowsShell('bun'), signal });
290
+ const previous = setBunGlobalDependency(globalDir, null);
291
+ try {
292
+ await execFileAsync('bun', ['add', '-g', spec, '--ignore-scripts'], {
293
+ shell: needsWindowsShell('bun'),
294
+ signal,
295
+ env: { ...process.env, BUN_INSTALL: path.dirname(path.dirname(globalDir)) },
296
+ });
297
+ }
298
+ catch (err) {
299
+ restoreBunGlobalDependency(globalDir, previous);
300
+ throw err;
301
+ }
302
+ try {
303
+ setBunGlobalDependency(globalDir, await readInstalledVersion(path.join(globalDir, 'node_modules', NPM_PACKAGE_NAME)));
304
+ }
305
+ catch {
306
+ restoreBunGlobalDependency(globalDir, null);
307
+ }
251
308
  }
252
309
  // Fail closed on anything except the registry's sha512 bytes before handing a tarball to a package manager.
253
310
  export function verifyTarballIntegrity(tarball, integrity) {
@@ -507,7 +507,7 @@ CREATE INDEX IF NOT EXISTS idx_remote_preview_cache_fetched ON session_remote_pr
507
507
  `;
508
508
  export const INSIGHTS_EXTRACTOR_VERSION = 7;
509
509
  export const SESSION_TOPIC_EXTRACTOR_VERSION = 2;
510
- const PREVIEW_EXTRACTOR_VERSION = 3;
510
+ const PREVIEW_EXTRACTOR_VERSION = 5;
511
511
  export const SESSION_PHENOTYPE_EXTRACTOR_VERSION = 1;
512
512
  export const SESSION_SUMMARY_EXTRACTOR_VERSION = 1;
513
513
  let dbInstance = null;
@@ -18,3 +18,24 @@ export declare function cacheInlineImage(sessionId: string, data: string, mediaT
18
18
  } | undefined;
19
19
  export declare function materializeInlineImages(events: SessionEvent[], sessionId: string, root?: string): void;
20
20
  export declare function enrichGlanceFiles(rows: ActiveSession[], nowMs?: number): void;
21
+ export interface PreviewSubAgent {
22
+ id?: string;
23
+ description: string;
24
+ agentType?: string;
25
+ status: 'running' | 'completed' | 'failed';
26
+ startedAt?: string;
27
+ durationMs?: number;
28
+ }
29
+ export interface PreviewImage {
30
+ path: string;
31
+ source: 'attached' | 'produced' | 'read';
32
+ at?: string;
33
+ }
34
+ export declare function previewSubAgentsFromEvents(events: SessionEvent[], isSubAgent: (tool: string, command: string) => boolean): PreviewSubAgent[];
35
+ export declare function previewSubAgentsFromFiles(sessionFile: string, fromEvents: readonly PreviewSubAgent[], nowMs?: number): PreviewSubAgent[] | undefined;
36
+ export declare function previewImagesFromEvents(events: SessionEvent[], changes: ReadonlyArray<{
37
+ path: string;
38
+ op: string;
39
+ }>, cwd?: string): PreviewImage[];
40
+ export declare function cachedAttachmentImages(sessionId: string, root?: string): PreviewImage[];
41
+ export declare function mergePreviewImages(...lists: PreviewImage[][]): PreviewImage[];
@@ -287,3 +287,126 @@ export function enrichGlanceFiles(rows, nowMs = Date.now()) {
287
287
  }
288
288
  }
289
289
  }
290
+ const PREVIEW_SUBAGENTS_MAX = 30;
291
+ const PREVIEW_IMAGES_MAX = 6;
292
+ const IMAGE_PATH_RE = /\.(png|jpe?g|gif|webp|bmp|tiff?|heic|svg)$/i;
293
+ const IMAGE_READ_TOOLS = new Set(['Read', 'read_file', 'view_file', 'view_image', 'cat_file', 'get_file']);
294
+ export function previewSubAgentsFromEvents(events, isSubAgent) {
295
+ const rows = [];
296
+ const byCall = new Map();
297
+ for (const event of events) {
298
+ if (event.type === 'tool_use' && !event._local && isSubAgent(event.tool ?? '', event.command ?? '')) {
299
+ const args = event.args ?? {};
300
+ const text = (value) => typeof value === 'string' && value.trim() ? value.replace(/\s+/g, ' ').trim() : undefined;
301
+ const row = {
302
+ ...(event.callId ? { id: event.callId } : {}),
303
+ description: (text(args.description) ?? text(args.prompt) ?? text(event.command) ?? event.tool ?? 'subagent').slice(0, 200),
304
+ ...(text(args.subagent_type) ? { agentType: text(args.subagent_type) } : {}),
305
+ status: 'running',
306
+ ...(event.timestamp ? { startedAt: event.timestamp } : {}),
307
+ ...(args.run_in_background === true ? { background: true } : {}),
308
+ };
309
+ rows.push(row);
310
+ if (event.callId)
311
+ byCall.set(event.callId, row);
312
+ }
313
+ else if ((event.type === 'tool_result' || event.type === 'error') && event.callId) {
314
+ const row = byCall.get(event.callId);
315
+ if (!row)
316
+ continue;
317
+ row.status = event.type === 'error' || event.success === false ? 'failed' : row.background ? 'running' : 'completed';
318
+ const started = row.startedAt ? Date.parse(row.startedAt) : NaN;
319
+ const ended = Date.parse(event.timestamp);
320
+ if (row.status !== 'running' && Number.isFinite(started) && Number.isFinite(ended) && ended >= started)
321
+ row.durationMs = ended - started;
322
+ }
323
+ }
324
+ return rows.slice(-PREVIEW_SUBAGENTS_MAX).map(({ background: _background, ...row }) => row);
325
+ }
326
+ export function previewSubAgentsFromFiles(sessionFile, fromEvents, nowMs = Date.now()) {
327
+ const children = readSessionSubagents(sessionFile, true, [], nowMs);
328
+ if (!children?.length)
329
+ return undefined;
330
+ const settled = new Map(fromEvents.filter(row => row.id && row.status !== 'running').map(row => [row.id, row]));
331
+ return children.map((child) => {
332
+ const metaPath = child.transcriptPath.replace(/\.jsonl$/, '.meta.json');
333
+ let toolUseId;
334
+ try {
335
+ toolUseId = JSON.parse(fs.readFileSync(metaPath, 'utf8')).toolUseId;
336
+ }
337
+ catch { }
338
+ const result = toolUseId ? settled.get(toolUseId) : undefined;
339
+ const status = result?.status ?? (child.status === 'failed' ? 'failed' : child.status === 'running' ? 'running' : 'completed');
340
+ let endedAtMs;
341
+ try {
342
+ endedAtMs = fs.statSync(child.transcriptPath).mtimeMs;
343
+ }
344
+ catch { }
345
+ const durationMs = result?.durationMs
346
+ ?? (child.startedAtMs !== undefined && endedAtMs !== undefined && endedAtMs >= child.startedAtMs ? Math.round(endedAtMs - child.startedAtMs) : undefined);
347
+ return {
348
+ id: child.id,
349
+ description: child.description,
350
+ ...(child.agentType ? { agentType: child.agentType } : {}),
351
+ status,
352
+ ...(child.startedAtMs !== undefined ? { startedAt: new Date(child.startedAtMs).toISOString() } : {}),
353
+ ...(durationMs !== undefined && status !== 'running' ? { durationMs } : {}),
354
+ };
355
+ });
356
+ }
357
+ export function previewImagesFromEvents(events, changes, cwd) {
358
+ const resolve = (p) => path.isAbsolute(p) || !cwd ? p : path.resolve(cwd, p);
359
+ const out = [];
360
+ const lastTouch = new Map();
361
+ for (const event of events) {
362
+ if (event.type === 'attachment' && event.path && (event.mediaType ?? '').startsWith('image/')) {
363
+ out.push({ path: resolve(event.path), source: 'attached', ...(event.timestamp ? { at: event.timestamp } : {}) });
364
+ continue;
365
+ }
366
+ if (event.type !== 'tool_use' || event._local)
367
+ continue;
368
+ const raw = event.path || event.args?.file_path || event.args?.path;
369
+ if (typeof raw !== 'string' || !IMAGE_PATH_RE.test(raw))
370
+ continue;
371
+ const abs = resolve(raw);
372
+ if (event.timestamp)
373
+ lastTouch.set(abs, event.timestamp);
374
+ if (IMAGE_READ_TOOLS.has(event.tool ?? ''))
375
+ out.push({ path: abs, source: 'read', ...(event.timestamp ? { at: event.timestamp } : {}) });
376
+ }
377
+ for (const change of changes) {
378
+ if (change.op === 'deleted' || !IMAGE_PATH_RE.test(change.path))
379
+ continue;
380
+ const abs = resolve(change.path);
381
+ const at = lastTouch.get(abs);
382
+ out.push({ path: abs, source: 'produced', ...(at ? { at } : {}) });
383
+ }
384
+ return mergePreviewImages(out.filter(image => fs.existsSync(image.path)));
385
+ }
386
+ export function cachedAttachmentImages(sessionId, root = path.join(getUserAgentsDir(), '.cache', 'attachments')) {
387
+ if (!sessionId || path.basename(sessionId) !== sessionId)
388
+ return [];
389
+ const dir = path.join(root, sessionId);
390
+ try {
391
+ return fs.readdirSync(dir)
392
+ .filter(name => IMAGE_PATH_RE.test(name))
393
+ .map((name) => {
394
+ const file = path.join(dir, name);
395
+ return { path: file, source: 'attached', at: new Date(fs.statSync(file).mtimeMs).toISOString() };
396
+ });
397
+ }
398
+ catch {
399
+ return [];
400
+ }
401
+ }
402
+ export function mergePreviewImages(...lists) {
403
+ const byPath = new Map();
404
+ for (const image of lists.flat()) {
405
+ const prior = byPath.get(image.path);
406
+ if (!prior || (image.at ?? '') >= (prior.at ?? ''))
407
+ byPath.set(image.path, prior?.source === 'attached' ? { ...image, source: 'attached' } : image);
408
+ }
409
+ return [...byPath.values()]
410
+ .sort((a, b) => (a.at ?? '').localeCompare(b.at ?? ''))
411
+ .slice(-PREVIEW_IMAGES_MAX);
412
+ }
@@ -79,6 +79,8 @@ export interface SessionPreviewDigest {
79
79
  planFile: string;
80
80
  todos?: TodoProgress;
81
81
  subAgentCount: number;
82
+ subAgents?: import('./glance-files.js').PreviewSubAgent[];
83
+ images?: import('./glance-files.js').PreviewImage[];
82
84
  backgroundShellCount?: number;
83
85
  toolTags: string[];
84
86
  changes: ReturnType<typeof changeCounts>;
@@ -86,6 +88,7 @@ export interface SessionPreviewDigest {
86
88
  dirs: string[];
87
89
  repos: string[];
88
90
  artifacts: ReturnType<typeof extractArtifacts>;
91
+ producedArtifacts?: ReturnType<typeof extractArtifacts>;
89
92
  skills: ReturnType<typeof extractSkills>;
90
93
  plugins: string[];
91
94
  hooks: ReturnType<typeof extractHooks>;
@@ -0,0 +1,13 @@
1
+ import type { SessionEvent, SessionMeta } from '@phnx-labs/sessions-cli/reader';
2
+ import type { SessionPreviewDigest } from './presentation.js';
3
+ export declare const DIRS_TOUCHED_MAX = 5;
4
+ export declare const CHANGED_FILES_MAX = 200;
5
+ export declare function sanitizeMeta(s: SessionMeta): SessionMeta;
6
+ export declare function readCachedPreviewDigest(session: SessionMeta): SessionPreviewDigest | undefined;
7
+ export declare function loadSessionPreviewDigest(session: SessionMeta): {
8
+ digest?: SessionPreviewDigest;
9
+ events: SessionEvent[];
10
+ error?: string;
11
+ };
12
+ export declare function buildSessionPreviewDigest(events: SessionEvent[], session: SessionMeta): SessionPreviewDigest;
13
+ export declare function relativizeDir(filePath: string, cwd?: string): string | undefined;
@@ -0,0 +1,328 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { changeCounts, classifyFileChanges, detectTestResult, extractArtifacts, extractHooks, extractLinks, extractRepos, extractSkills, extractTodoProgressFromEvents, firstUserMessageFromEvents, harnessTracksBackgroundShells, inferSessionState, isBackgroundShellStart, isSubAgentTool, parseSession, readSessionHead, readSessionTail, sanitizeForTerminal, toolHistogram, WORKTREE_RE, } from '@phnx-labs/sessions-cli/reader';
4
+ import { formatBytes } from '../format.js';
5
+ import { getSessionPlugins, readArchivedSessionPreview, readSessionPreviewCache, writeSessionPreviewCache } from './db.js';
6
+ import { cachedAttachmentImages, materializeInlineImages, mergePreviewImages, previewImagesFromEvents, previewSubAgentsFromEvents, previewSubAgentsFromFiles } from './glance-files.js';
7
+ export const DIRS_TOUCHED_MAX = 5;
8
+ export const CHANGED_FILES_MAX = 200;
9
+ const PREVIEW_DIGEST_MAX_PARSE_BYTES = 4 * 1024 * 1024;
10
+ // Peer metadata is untrusted: bound its shape and strip terminal escapes before rendering.
11
+ export function sanitizeMeta(s) {
12
+ const clean = (v) => (v == null ? v : sanitizeForTerminal(v));
13
+ const todos = s.todos
14
+ ? {
15
+ ...s.todos,
16
+ activeForm: clean(s.todos.activeForm),
17
+ items: s.todos.items.map((it) => ({
18
+ ...it,
19
+ content: sanitizeForTerminal(it.content),
20
+ activeForm: clean(it.activeForm),
21
+ })),
22
+ }
23
+ : s.todos;
24
+ return {
25
+ ...s,
26
+ id: sanitizeForTerminal(s.id),
27
+ shortId: sanitizeForTerminal(s.shortId),
28
+ filePath: sanitizeForTerminal(s.filePath),
29
+ cwd: clean(s.cwd),
30
+ project: clean(s.project),
31
+ gitBranch: clean(s.gitBranch),
32
+ version: clean(s.version),
33
+ account: clean(s.account),
34
+ topic: clean(s.topic),
35
+ firstUserMessage: clean(s.firstUserMessage),
36
+ label: clean(s.label),
37
+ generatedTitle: clean(s.generatedTitle),
38
+ ticketId: clean(s.ticketId),
39
+ prUrl: clean(s.prUrl),
40
+ plan: clean(s.plan),
41
+ spawnedTeam: clean(s.spawnedTeam),
42
+ recentDirectoriesTouched: s.recentDirectoriesTouched?.map(sanitizeForTerminal),
43
+ todos,
44
+ };
45
+ }
46
+ export function readCachedPreviewDigest(session) {
47
+ if (!session.filePath)
48
+ return readArchivedSessionPreview(session.id);
49
+ let stamp;
50
+ try {
51
+ stamp = fs.statSync(session.filePath);
52
+ }
53
+ catch {
54
+ return readArchivedSessionPreview(session.id);
55
+ }
56
+ return readSessionPreviewCache(session.id, { fileMtimeMs: stamp.mtimeMs, fileSize: stamp.size });
57
+ }
58
+ export function loadSessionPreviewDigest(session) {
59
+ if (!session.filePath || !fs.existsSync(session.filePath)) {
60
+ const archived = readArchivedSessionPreview(session.id);
61
+ if (archived) {
62
+ archived.plugins = getSessionPlugins(session.id);
63
+ return { digest: archived, events: [] };
64
+ }
65
+ return { events: [], error: 'no local transcript for this session (metadata-only entry, no archived digest)' };
66
+ }
67
+ const safe = sanitizeMeta(session);
68
+ let events = [];
69
+ let sourceStamp;
70
+ try {
71
+ sourceStamp = fs.statSync(session.filePath);
72
+ }
73
+ catch (err) {
74
+ return { events, error: sanitizeForTerminal(err?.message ?? String(err)) };
75
+ }
76
+ let digest = readSessionPreviewCache(session.id, {
77
+ fileMtimeMs: sourceStamp.mtimeMs,
78
+ fileSize: sourceStamp.size,
79
+ });
80
+ if (!digest) {
81
+ // Large uncached transcripts use bounded tail plus bounded head, so a tail follow-up is never mislabeled as the first prompt.
82
+ if (sourceStamp.size > PREVIEW_DIGEST_MAX_PARSE_BYTES) {
83
+ events = readSessionTail(session.filePath, session.agent);
84
+ digest = buildSessionPreviewDigest(events, safe);
85
+ if (session.firstUserMessage) {
86
+ digest.firstUser = session.firstUserMessage;
87
+ }
88
+ else {
89
+ digest.firstUser = firstUserMessageFromEvents(readSessionHead(session.filePath, session.agent)) ?? '';
90
+ }
91
+ digest.partial = true;
92
+ digest.partialReason = `transcript is ${formatBytes(sourceStamp.size)}, over the ${formatBytes(PREVIEW_DIGEST_MAX_PARSE_BYTES)} bounded-parse limit for an uncached preview; digest reflects only the last ~128 KiB (tail) of the transcript, not the whole session`;
93
+ writeSessionPreviewCache({
94
+ id: session.id,
95
+ fileMtimeMs: sourceStamp.mtimeMs,
96
+ fileSize: sourceStamp.size,
97
+ preview: digest,
98
+ });
99
+ }
100
+ else {
101
+ try {
102
+ events = parseSession(session.filePath, session.agent, { includeInlineImages: true });
103
+ if (session.agent === 'claude')
104
+ materializeInlineImages(events, session.id);
105
+ digest = buildSessionPreviewDigest(events, safe);
106
+ writeSessionPreviewCache({
107
+ id: session.id,
108
+ fileMtimeMs: sourceStamp.mtimeMs,
109
+ fileSize: sourceStamp.size,
110
+ preview: digest,
111
+ });
112
+ }
113
+ catch (err) {
114
+ return { events, error: sanitizeForTerminal(err?.message ?? String(err)) };
115
+ }
116
+ }
117
+ }
118
+ digest.plugins = getSessionPlugins(session.id);
119
+ applyLiveSessionFiles(digest, session);
120
+ return { digest, events };
121
+ }
122
+ function applyLiveSessionFiles(digest, session) {
123
+ if (session.agent === 'claude' && session.filePath) {
124
+ const children = previewSubAgentsFromFiles(session.filePath, digest.subAgents ?? []);
125
+ if (children) {
126
+ digest.subAgents = children;
127
+ digest.subAgentCount = children.length;
128
+ }
129
+ }
130
+ const known = new Set((digest.images ?? []).map(image => image.path));
131
+ const images = mergePreviewImages(digest.images ?? [], cachedAttachmentImages(session.id).filter(image => !known.has(image.path)));
132
+ if (images.length)
133
+ digest.images = images;
134
+ else
135
+ delete digest.images;
136
+ if (!digest.subAgents?.length)
137
+ delete digest.subAgents;
138
+ }
139
+ const SYSTEM_MESSAGE_PATTERNS = [
140
+ /^\s*<environment_context>/i,
141
+ /^\s*<system-reminder>/i,
142
+ /^\s*<permissions\s/i,
143
+ /^\s*<collaboration_mode>/i,
144
+ /^\s*<local-command-caveat>/i,
145
+ /^\s*# AGENTS\.md instructions for\b/i,
146
+ /^\s*<command-(message|name|args)>/i,
147
+ ];
148
+ export function buildSessionPreviewDigest(events, session) {
149
+ let firstUser = '';
150
+ let lastAssistant = '';
151
+ const filesRead = new Set();
152
+ const toolCounts = {};
153
+ let toolCalls = 0;
154
+ let planFile = '';
155
+ let subAgentCount = 0;
156
+ let backgroundShellCount = harnessTracksBackgroundShells(session.agent)
157
+ ? 0
158
+ : undefined;
159
+ const toolTags = new Set();
160
+ const knownToolUsage = session.usedBrowser !== undefined;
161
+ for (const event of events) {
162
+ if (event.type === 'message') {
163
+ if (event.role === 'user' && !event._synthetic && !firstUser && event.content) {
164
+ if (!SYSTEM_MESSAGE_PATTERNS.some(p => p.test(event.content))) {
165
+ firstUser = event.content;
166
+ }
167
+ }
168
+ if (event.role === 'assistant' && event.content) {
169
+ lastAssistant = event.content;
170
+ }
171
+ }
172
+ else if (event.type === 'tool_use' && !event._local) {
173
+ const tool = event.tool || '';
174
+ const command = event.command || '';
175
+ if (!knownToolUsage) {
176
+ for (const tag of classifySessionTool(tool, command))
177
+ toolTags.add(tag);
178
+ }
179
+ if (isSubAgentTool(tool, command))
180
+ subAgentCount++;
181
+ if (backgroundShellCount !== undefined && isBackgroundShellStart(event))
182
+ backgroundShellCount++;
183
+ const p = event.path || event.args?.file_path || event.args?.path || '';
184
+ if (['Read', 'read_file', 'view_file', 'cat_file', 'get_file'].includes(tool) && p) {
185
+ filesRead.add(p);
186
+ }
187
+ if (!planFile && p && /\/plans\/[^/]+\.md$/.test(p)) {
188
+ planFile = p;
189
+ }
190
+ if (tool)
191
+ toolCounts[tool] = (toolCounts[tool] ?? 0) + 1;
192
+ toolCalls++;
193
+ }
194
+ }
195
+ if (session.usedBrowser)
196
+ toolTags.add('browser');
197
+ if (session.usedComputer)
198
+ toolTags.add('computer');
199
+ const todos = extractTodoProgressFromEvents(events) ?? session.todos;
200
+ const changes = classifyFileChanges(events);
201
+ const chg = changeCounts(changes);
202
+ const errorEvents = events.filter(e => e.type === 'error');
203
+ const subAgents = previewSubAgentsFromEvents(events, isSubAgentTool);
204
+ const producedArtifacts = inferSessionState(events, { cwd: session.cwd }).artifacts ?? [];
205
+ const images = previewImagesFromEvents(events, changes, session.cwd);
206
+ return {
207
+ schemaVersion: 1,
208
+ firstUser,
209
+ lastAssistant,
210
+ filesRead: filesRead.size,
211
+ toolCalls,
212
+ planFile,
213
+ todos,
214
+ subAgentCount,
215
+ ...(subAgents.length ? { subAgents } : {}),
216
+ ...(images.length ? { images } : {}),
217
+ backgroundShellCount,
218
+ toolTags: [...toolTags],
219
+ changes: chg,
220
+ changedFiles: changes.slice(0, CHANGED_FILES_MAX),
221
+ dirs: directoriesTouched(session, events, changes),
222
+ repos: extractRepos(events, session.cwd),
223
+ artifacts: extractArtifacts(changes),
224
+ ...(producedArtifacts.length ? { producedArtifacts } : {}),
225
+ skills: extractSkills(events),
226
+ plugins: getSessionPlugins(session.id),
227
+ hooks: extractHooks(events),
228
+ links: extractLinks(events),
229
+ errorCount: errorEvents.length,
230
+ firstError: errorEvents[0]?.tool,
231
+ toolHistogram: toolHistogram(toolCounts, 4),
232
+ test: detectTestResult(events),
233
+ };
234
+ }
235
+ function classifySessionTool(tool, command) {
236
+ const toolName = tool.toLowerCase();
237
+ const commandUses = (surface) => (new RegExp(`\\b(?:agents|ag)\\b[^\\n;&|]*\\b${surface}\\b`).test(command.toLowerCase()));
238
+ const tags = [];
239
+ if (/browser|webfetch|websearch/.test(toolName) || commandUses('browser'))
240
+ tags.push('browser');
241
+ if (/computer/.test(toolName) || commandUses('computer'))
242
+ tags.push('computer');
243
+ return tags;
244
+ }
245
+ function directoriesTouched(session, events, changes) {
246
+ const fromMeta = session.recentDirectoriesTouched;
247
+ if (Array.isArray(fromMeta) && fromMeta.length > 0) {
248
+ const seen = new Set();
249
+ for (const raw of fromMeta) {
250
+ const dir = relativizeDir(sanitizeForTerminal(String(raw).trim()), session.cwd);
251
+ if (dir)
252
+ seen.add(dir);
253
+ if (seen.size >= DIRS_TOUCHED_MAX)
254
+ break;
255
+ }
256
+ if (seen.size > 0)
257
+ return [...seen];
258
+ }
259
+ const counts = new Map();
260
+ const bump = (raw) => {
261
+ const dir = relativizeDir(raw, session.cwd);
262
+ if (!dir)
263
+ return;
264
+ counts.set(dir, (counts.get(dir) ?? 0) + 1);
265
+ };
266
+ for (const ch of changes)
267
+ bump(ch.path);
268
+ for (const event of events) {
269
+ if (event.type !== 'tool_use' || event._local)
270
+ continue;
271
+ const p = event.path || event.args?.file_path || event.args?.path || '';
272
+ if (p)
273
+ bump(p);
274
+ }
275
+ return [...counts.entries()]
276
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
277
+ .map(([d]) => d)
278
+ .slice(0, DIRS_TOUCHED_MAX);
279
+ }
280
+ function encodeClaudeSlug(absPath) {
281
+ return absPath.replace(/[/.]/g, '-');
282
+ }
283
+ const SLUG_WORKTREE_RE = /--agents-worktrees-(.+)$/;
284
+ export function relativizeDir(filePath, cwd) {
285
+ const norm = filePath.replace(/\\/g, '/');
286
+ if (!norm || norm.includes('node_modules') || norm.includes('/.git/') || norm.includes('/plans/')) {
287
+ return undefined;
288
+ }
289
+ const normBase = cwd?.replace(/\\/g, '/').replace(/\/$/, '');
290
+ const underCwd = normBase && (norm === normBase || norm.startsWith(normBase + '/'));
291
+ if (!underCwd && (norm.includes('/.agents/.history/') || /\/\.agents\/worktrees(\/[^/]+)?\/?$/.test(norm))) {
292
+ return undefined;
293
+ }
294
+ let dir = path.posix.dirname(norm);
295
+ if (dir.startsWith('-')) {
296
+ const slash = dir.indexOf('/');
297
+ const slug = slash === -1 ? dir : dir.slice(0, slash);
298
+ if (cwd) {
299
+ const cwdSlug = encodeClaudeSlug(cwd.replace(/\\/g, '/').replace(/\/$/, ''));
300
+ if (slug === cwdSlug || slug.startsWith(cwdSlug + '-'))
301
+ return undefined;
302
+ }
303
+ const wtSlug = slug.match(SLUG_WORKTREE_RE);
304
+ if (wtSlug)
305
+ return `⧉ ${wtSlug[1]}`;
306
+ const segs = slug.split('-').filter(Boolean);
307
+ return segs.length ? segs[segs.length - 1] : undefined;
308
+ }
309
+ if (cwd) {
310
+ const base = cwd.replace(/\\/g, '/').replace(/\/$/, '');
311
+ if (dir === base)
312
+ return '.';
313
+ if (dir.startsWith(base + '/'))
314
+ return dir.slice(base.length + 1);
315
+ }
316
+ const wt = dir.match(WORKTREE_RE);
317
+ if (wt) {
318
+ const after = dir.slice(dir.indexOf(wt[0]) + wt[0].length).replace(/^\//, '');
319
+ return after ? `⧉ ${wt[1]}/${after}` : `⧉ ${wt[1]}`;
320
+ }
321
+ const home = (process.env.HOME || '').replace(/\\/g, '/');
322
+ if (home && dir.startsWith(home + '/'))
323
+ dir = '~' + dir.slice(home.length);
324
+ const parts = dir.split('/').filter(Boolean);
325
+ if (parts.length > 3 && dir.startsWith('/'))
326
+ dir = parts.slice(-3).join('/');
327
+ return dir || undefined;
328
+ }
@@ -41,7 +41,8 @@ export type PeerPreviewEnvelopeResult = {
41
41
  };
42
42
  export declare function fetchPeerPreviewEnvelope(sessionId: string, machine: string, timeoutMs?: number): Promise<PeerPreviewEnvelopeResult>;
43
43
  export declare function parsePeerPreviewDigest(parsed: unknown): unknown | undefined;
44
- export declare function peerHopOutcome(code: number | null, hostAnswers: () => boolean): 'ok' | 'unreachable';
44
+ export type PeerHopOutcome = 'ok' | 'unreachable' | 'failed';
45
+ export declare function peerHopOutcome(code: number | null, hostAnswers: () => boolean, oneShot?: boolean): PeerHopOutcome;
45
46
  export declare function peerAnswers(target: string): boolean;
46
47
  export declare function peerHopCloseNotice(opts: {
47
48
  tty?: boolean;
@@ -52,7 +53,7 @@ export declare function runOnPeer(args: string[], machine: string, opts?: {
52
53
  tty?: boolean;
53
54
  env?: Record<string, string>;
54
55
  sessionId?: string;
55
- }): Promise<'ok' | 'no-target' | 'unreachable'>;
56
+ }): Promise<PeerHopOutcome | 'no-target'>;
56
57
  export declare function hostToken(h: string): string;
57
58
  export declare function shouldIncludeLocal(hosts: string[] | undefined, self: string): boolean;
58
59
  export declare function remoteHostsToDial(hosts: string[] | undefined, self: string): string[] | undefined;
@@ -3,6 +3,7 @@ import chalk from 'chalk';
3
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
+ import { resolveDeviceProfile } from '../../devices/resolve-profile.js';
6
7
  import { loadDevices, isDialableDevice } from '../../devices/registry.js';
7
8
  import { remoteShellFor, buildWindowsAgentsCommand, stripClixml } from '../../hosts/remote-cmd.js';
8
9
  import { gatherRemoteAgentsJson } from '../../remote-agents-json.js';
@@ -108,7 +109,8 @@ export function isAutomaticSessionPeer(d, self) {
108
109
  return false;
109
110
  if (normalizeHost(d.name) === self)
110
111
  return false;
111
- return d.platform === 'windows' || d.platform === 'linux' || d.platform === 'macos';
112
+ const platform = resolveDeviceProfile(d).platform;
113
+ return platform === 'windows' || platform === 'linux' || platform === 'macos';
112
114
  }
113
115
  export async function gatherRemoteList(forwardedArgs, hosts, opts) {
114
116
  const safeResolver = forwardedArgs[0] === 'ps' && forwardedArgs[1] === 'resolve';
@@ -143,7 +145,7 @@ export async function resolvePeerTarget(machine) {
143
145
  if (normalizeHost(d.name) !== machine)
144
146
  continue;
145
147
  try {
146
- return { target: sshTargetFor(d), os: d.platform };
148
+ return { target: sshTargetFor(d), os: resolveDeviceProfile(d).platform };
147
149
  }
148
150
  catch {
149
151
  return undefined;
@@ -182,12 +184,16 @@ export function parsePeerPreviewDigest(parsed) {
182
184
  return preview;
183
185
  }
184
186
  const PEER_PROBE_TIMEOUT_MS = 15_000;
185
- export function peerHopOutcome(code, hostAnswers) {
187
+ export function peerHopOutcome(code, hostAnswers, oneShot = false) {
186
188
  if (code === null)
187
189
  return 'unreachable';
188
- if (code !== SSH_CONN_FAILURE_CODE)
190
+ if (code === 0)
189
191
  return 'ok';
190
- return hostAnswers() ? 'ok' : 'unreachable';
192
+ if (code !== SSH_CONN_FAILURE_CODE)
193
+ return oneShot ? 'failed' : 'ok';
194
+ if (!hostAnswers())
195
+ return 'unreachable';
196
+ return oneShot ? 'failed' : 'ok';
191
197
  }
192
198
  export function peerAnswers(target) {
193
199
  return sshExec(target, 'true', { multiplex: false, timeoutMs: PEER_PROBE_TIMEOUT_MS }).code === 0;
@@ -261,7 +267,7 @@ export async function runOnPeer(args, machine, opts = {}) {
261
267
  const notice = peerHopCloseNotice(opts, machine, code);
262
268
  if (notice)
263
269
  process.stderr.write(notice);
264
- return peerHopOutcome(code, () => peerAnswers(peer.target));
270
+ return peerHopOutcome(code, () => peerAnswers(peer.target), !opts.tty);
265
271
  }
266
272
  export function hostToken(h) {
267
273
  return normalizeHost(h.split('@').pop() || h);