@phnx-labs/agents-cli 1.23.18 → 1.23.20

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 (78) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/README.md +1 -1
  3. package/dist/bootstrap.js +1 -1
  4. package/dist/commands/cloud.js +1 -1
  5. package/dist/commands/config.js +1 -1
  6. package/dist/commands/detach.js +5 -1
  7. package/dist/commands/doctor.js +11 -7
  8. package/dist/commands/exec.d.ts +0 -17
  9. package/dist/commands/exec.js +17 -51
  10. package/dist/commands/focus.d.ts +10 -2
  11. package/dist/commands/focus.js +80 -19
  12. package/dist/commands/projects-todo.js +10 -5
  13. package/dist/commands/ps.d.ts +8 -2
  14. package/dist/commands/ps.js +175 -92
  15. package/dist/commands/sessions-picker.d.ts +0 -7
  16. package/dist/commands/sessions-picker.js +5 -299
  17. package/dist/commands/sessions-stop.js +2 -2
  18. package/dist/lib/account-registry.d.ts +3 -0
  19. package/dist/lib/account-registry.js +40 -0
  20. package/dist/lib/accounting/account-pool-collect.d.ts +2 -2
  21. package/dist/lib/accounting/account-pool-collect.js +4 -4
  22. package/dist/lib/accounting/account-pool.d.ts +1 -1
  23. package/dist/lib/accounting/account-pool.js +3 -1
  24. package/dist/lib/accounting/usage-sync.d.ts +1 -0
  25. package/dist/lib/accounting/usage-sync.js +20 -3
  26. package/dist/lib/accounting/usage.d.ts +4 -1
  27. package/dist/lib/accounting/usage.js +38 -6
  28. package/dist/lib/agent-spec/agents.js +12 -11
  29. package/dist/lib/cloud/store.d.ts +5 -1
  30. package/dist/lib/cloud/store.js +10 -3
  31. package/dist/lib/config-keys.d.ts +1 -1
  32. package/dist/lib/config-keys.js +1 -0
  33. package/dist/lib/daemon/account-state-daemon-service.js +9 -2
  34. package/dist/lib/daemon/self-update-service.js +1 -1
  35. package/dist/lib/device-config.d.ts +2 -1
  36. package/dist/lib/device-config.js +21 -11
  37. package/dist/lib/devices/health.d.ts +6 -0
  38. package/dist/lib/devices/health.js +11 -4
  39. package/dist/lib/feed/watch.js +2 -1
  40. package/dist/lib/fleet/apply.d.ts +1 -1
  41. package/dist/lib/fleet/apply.js +5 -2
  42. package/dist/lib/fleet-shared-state.d.ts +2 -0
  43. package/dist/lib/fleet-shared-state.js +3 -1
  44. package/dist/lib/github/project-prs.js +14 -1
  45. package/dist/lib/helper-versions.js +1 -1
  46. package/dist/lib/installations/versions.js +4 -3
  47. package/dist/lib/project-root.d.ts +1 -0
  48. package/dist/lib/project-root.js +11 -3
  49. package/dist/lib/projects.js +2 -2
  50. package/dist/lib/quick-todo.d.ts +5 -1
  51. package/dist/lib/quick-todo.js +14 -1
  52. package/dist/lib/remote-agents-json.js +4 -2
  53. package/dist/lib/self-update.d.ts +1 -1
  54. package/dist/lib/self-update.js +59 -2
  55. package/dist/lib/session/db.js +1 -1
  56. package/dist/lib/session/glance-files.d.ts +21 -0
  57. package/dist/lib/session/glance-files.js +123 -0
  58. package/dist/lib/session/presentation.d.ts +3 -0
  59. package/dist/lib/session/preview-digest.d.ts +13 -0
  60. package/dist/lib/session/preview-digest.js +328 -0
  61. package/dist/lib/session/recovery.d.ts +1 -1
  62. package/dist/lib/session/recovery.js +1 -1
  63. package/dist/lib/session/remote/remote-list.d.ts +3 -2
  64. package/dist/lib/session/remote/remote-list.js +12 -6
  65. package/dist/lib/session/remote/watch.d.ts +2 -0
  66. package/dist/lib/session/remote/watch.js +86 -5
  67. package/dist/lib/smart-launch.js +6 -1
  68. package/dist/lib/teams/placement-probe.d.ts +2 -0
  69. package/dist/lib/teams/placement-probe.js +8 -3
  70. package/dist/lib/terminal/engine.d.ts +2 -0
  71. package/dist/lib/terminal/engine.js +5 -3
  72. package/dist/lib/terminal/index.d.ts +1 -1
  73. package/dist/lib/terminal/index.js +1 -1
  74. package/dist/lib/terminal/run-surface.d.ts +1 -0
  75. package/dist/lib/terminal/run-surface.js +9 -0
  76. package/package.json +1 -1
  77. package/dist/lib/onepassword.d.ts +0 -57
  78. package/dist/lib/onepassword.js +0 -140
@@ -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
+ }
@@ -51,6 +51,6 @@ export declare function inspectNativeResumeSession(session: SessionMeta, version
51
51
  export declare function resolveSessionRecoveryFromCandidates(session: SessionMeta, candidates: RotateCandidate[], supportsNative?: (agent: AgentId, version?: string) => boolean, nativeInspection?: NativeResumeInspection, options?: SessionRecoverySelection): SessionRecoveryTarget;
52
52
  export declare function sessionTranscriptReadable(session: SessionMeta): boolean;
53
53
  export declare function assertRecoverableTranscript(session: SessionMeta): void;
54
- export declare function resolveSessionRecovery(session: SessionMeta, collect?: (agent: AgentId) => Promise<RotateCandidate[]>, options?: SessionRecoverySelection): Promise<SessionRecoveryTarget>;
54
+ export declare function resolveSessionRecovery(session: SessionMeta, collect?: (agent: AgentId, includeKeyed?: boolean) => Promise<RotateCandidate[]>, options?: SessionRecoverySelection): Promise<SessionRecoveryTarget>;
55
55
  export declare function sessionRecoveryRunArgs(session: Pick<SessionMeta, 'id'>): string[];
56
56
  export {};
@@ -331,7 +331,7 @@ export async function resolveSessionRecovery(session, collect = collectRunCandid
331
331
  const installation = resolveManagedInstallation(agent);
332
332
  if (!installation)
333
333
  throw new SessionRecoveryError(`No managed ${agent} installation is available. Install it with: agents add ${agent}`);
334
- return resolveSessionRecoveryFromCandidates(session, await collect(agent), undefined, undefined, {
334
+ return resolveSessionRecoveryFromCandidates(session, await collect(agent, Boolean(options.account?.trim())), undefined, undefined, {
335
335
  ...options, executableVersion: installation.label,
336
336
  });
337
337
  }
@@ -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);
@@ -82,6 +82,7 @@ export declare class SessionWatchState {
82
82
  reset(scope: string, sourceRows: ActiveSession[], indexedRows?: SessionMeta[]): SessionWatchEnvelope;
83
83
  update(scope: string, sourceRows: ActiveSession[]): SessionWatchEnvelope[];
84
84
  patch(scope: string, upserts: ActiveSession[], removes: string[]): SessionWatchEnvelope[];
85
+ refreshPrevious(scope: string, session: SessionMeta, accounts?: import("../../account-registry.js").NativeAccount[]): SessionWatchEnvelope | undefined;
85
86
  scope(scope: string, status: SessionWatchScopeStatus, reason?: string): SessionWatchEnvelope;
86
87
  heartbeat(scope: string, capturedAt?: number): SessionWatchEnvelope;
87
88
  }
@@ -97,6 +98,7 @@ export interface WatchLocalOptions {
97
98
  journalPollMs?: number;
98
99
  }
99
100
  export declare function readPreviousSessionsForWatch(scope: string): SessionMeta[];
101
+ export declare function previewDigestBuildsForTest(): number;
100
102
  export declare function watchLocalSessions(options: WatchLocalOptions): Promise<void>;
101
103
  interface WatchFleetOptions {
102
104
  signal: AbortSignal;
@@ -4,13 +4,16 @@ import { createHash, randomUUID } from 'node:crypto';
4
4
  import * as fs from 'node:fs';
5
5
  import * as path from 'node:path';
6
6
  import { loadDevices, isDialableDevice } from '../../devices/registry.js';
7
+ import { resolveDeviceProfile } from '../../devices/resolve-profile.js';
7
8
  import { machineId, normalizeHost } from '../../machine-id.js';
8
9
  import { shellQuote } from '../../ssh-exec.js';
9
10
  import { streamFromPeer } from './peer-stream.js';
10
11
  import { buildWindowsAgentsCommand, remoteShellFor } from '../../hosts/remote-cmd.js';
11
- import { isReapableOrphan, sessionAccountLabel } from '../active.js';
12
+ import { artifactKind, deriveImportantMessage, deriveSessionRecap, isReapableOrphan, sessionAccountLabel } from '../active.js';
13
+ import { loadSessionPreviewDigest, readCachedPreviewDigest } from '../preview-digest.js';
14
+ import { indexArtifactSidecars, mergeArtifacts } from '@phnx-labs/sessions-cli/reader';
12
15
  import { listNativeAccounts } from '../../account-registry.js';
13
- import { readMeta } from '../../state.js';
16
+ import { getUserAgentsDir, readMeta } from '../../state.js';
14
17
  import { querySessions, readSessionSummaryAny, readSessionTimelineAny } from '../db.js';
15
18
  import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
16
19
  import { sessionAgentSupportsResume } from '../recovery.js';
@@ -57,6 +60,28 @@ function previousSessionWatchRowKey(scope, sessionId) {
57
60
  function previousRowTitle(session, foldedHeadline) {
58
61
  return session.label || session.generatedTitle || foldedHeadline || session.topic || undefined;
59
62
  }
63
+ function previousRowCard(session, request, attachments) {
64
+ const digest = readCachedPreviewDigest(session);
65
+ const recap = deriveSessionRecap({
66
+ ...session,
67
+ tail: digest?.lastAssistant ? [digest.lastAssistant] : undefined,
68
+ attachments,
69
+ request,
70
+ });
71
+ const sidecars = indexArtifactSidecars(path.join(getUserAgentsDir(), 'artifacts')).get(session.id) ?? [];
72
+ const artifacts = mergeArtifacts(digest?.producedArtifacts ?? [], sidecars).map((artifact) => ({ ...artifact, kind: artifactKind(artifact.path) }));
73
+ const todos = digest?.todos ?? session.todos;
74
+ const importantMessage = deriveImportantMessage({ status: 'closed', lastAgentLine: recap.lastAgentLine });
75
+ return {
76
+ ...(recap.lastAgentLine ? { lastAgentLine: recap.lastAgentLine } : {}),
77
+ ...(recap.request ? { request: recap.request } : {}),
78
+ ...(recap.userPromptClean ? { userPromptClean: recap.userPromptClean } : {}),
79
+ ...(recap.userPromptKind ? { userPromptKind: recap.userPromptKind } : {}),
80
+ ...(todos?.total ? { todos } : {}),
81
+ ...(artifacts.length ? { artifacts } : {}),
82
+ ...(importantMessage ? { importantMessage } : {}),
83
+ };
84
+ }
60
85
  export function toPreviousSessionWatchRow(scope, session, accounts = listNativeAccounts(readMeta())) {
61
86
  const resumable = sessionAgentSupportsResume(session.agent);
62
87
  const sourceDevice = normalizeHost(session.machine ?? scope);
@@ -76,6 +101,7 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
76
101
  const folded = readSessionTimelineAny(session.id);
77
102
  const model = folded?.model ?? session.model;
78
103
  const title = previousRowTitle(session, folded?.request?.headline);
104
+ const card = previousRowCard(session, folded?.request, folded?.attachments);
79
105
  return {
80
106
  context: 'recent',
81
107
  kind: session.agent,
@@ -105,7 +131,7 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
105
131
  ...(summary?.checkpoints ? { checkpoints: summary.checkpoints } : {}),
106
132
  ...(summary?.summaryChecklist ? { summaryChecklist: summary.summaryChecklist } : {}),
107
133
  summaryState: resolveStreamSummaryState(summary?.summaryState),
108
- ...(folded?.request ? { request: folded.request } : {}),
134
+ ...card,
109
135
  ...(folded?.timeline ? { timeline: folded.timeline } : {}),
110
136
  ...(folded?.files ? { files: folded.files } : {}),
111
137
  ...(model ? { model } : {}),
@@ -272,6 +298,18 @@ export class SessionWatchState {
272
298
  this.rows.set(scope, current);
273
299
  return events;
274
300
  }
301
+ refreshPrevious(scope, session, accounts = listNativeAccounts(readMeta())) {
302
+ const rows = this.rows.get(scope);
303
+ const rowKey = previousSessionWatchRowKey(scope, session.id);
304
+ const current = rows?.get(rowKey);
305
+ if (!rows || !current)
306
+ return undefined;
307
+ const row = toPreviousSessionWatchRow(scope, session, accounts);
308
+ if (sameRow(current, row))
309
+ return undefined;
310
+ rows.set(rowKey, row);
311
+ return { ...this.base('upsert'), scope, rowKey, row };
312
+ }
275
313
  scope(scope, status, reason) {
276
314
  return { ...this.base('scope'), scope, status, ...(reason ? { reason } : {}) };
277
315
  }
@@ -294,6 +332,47 @@ export function readPreviousSessionsForWatch(scope) {
294
332
  return [];
295
333
  }
296
334
  }
335
+ const failedPreviewDigests = new Map();
336
+ let previewDigestBuilds = 0;
337
+ export function previewDigestBuildsForTest() {
338
+ return previewDigestBuilds;
339
+ }
340
+ function transcriptStamp(session) {
341
+ try {
342
+ const stat = fs.statSync(session.filePath);
343
+ return `${stat.mtimeMs}:${stat.size}`;
344
+ }
345
+ catch {
346
+ return 'missing';
347
+ }
348
+ }
349
+ async function fillPreviousCards(state, options, sessions) {
350
+ const accounts = sessions.length ? listNativeAccounts(readMeta()) : [];
351
+ for (const session of sessions) {
352
+ if (options.signal.aborted)
353
+ return;
354
+ const stamp = transcriptStamp(session);
355
+ if (failedPreviewDigests.get(session.id) === stamp || readCachedPreviewDigest(session))
356
+ continue;
357
+ await new Promise((resolve) => setImmediate(resolve));
358
+ if (options.signal.aborted)
359
+ return;
360
+ try {
361
+ previewDigestBuilds++;
362
+ if (!loadSessionPreviewDigest(session).digest) {
363
+ failedPreviewDigests.set(session.id, stamp);
364
+ continue;
365
+ }
366
+ failedPreviewDigests.delete(session.id);
367
+ const event = state.refreshPrevious(options.scope, session, accounts);
368
+ if (event)
369
+ options.emit(event);
370
+ }
371
+ catch {
372
+ failedPreviewDigests.set(session.id, stamp);
373
+ }
374
+ }
375
+ }
297
376
  export async function watchLocalSessions(options) {
298
377
  const state = new SessionWatchState();
299
378
  const readCache = options.readCache ?? readActiveSessionsCache;
@@ -306,10 +385,12 @@ export async function watchLocalSessions(options) {
306
385
  }
307
386
  catch { }
308
387
  const initial = readCache('local');
309
- options.emit(state.reset(options.scope, initial?.sessions ?? [], readPrevious(options.scope)));
388
+ const previous = readPrevious(options.scope);
389
+ options.emit(state.reset(options.scope, initial?.sessions ?? [], previous));
310
390
  options.emit(state.scope(options.scope, initial ? 'available' : 'unavailable', initial ? undefined : 'awaiting publisher'));
311
391
  if (options.signal.aborted)
312
392
  return;
393
+ void fillPreviousCards(state, options, previous);
313
394
  noteActiveSessionsJournalReader();
314
395
  await new Promise((resolve) => {
315
396
  let partial = '';
@@ -388,7 +469,7 @@ export async function watchFleetSessions(options) {
388
469
  return;
389
470
  }
390
471
  const self = machineId();
391
- const peers = Object.values(devices).filter((device) => isDialableDevice(device)
472
+ const peers = Object.values(devices).map(resolveDeviceProfile).filter((device) => isDialableDevice(device)
392
473
  && normalizeHost(device.name) !== self
393
474
  && ['windows', 'linux', 'macos'].includes(device.platform));
394
475
  const peerTasks = peers.map(async (device) => {
@@ -56,7 +56,12 @@ export function formatNoHealthyDeviceError(pool, signals, agent) {
56
56
  const excluded = pool.map((key) => {
57
57
  const signal = signals.get(key);
58
58
  let reason;
59
- if (signal?.reachable === true) {
59
+ if (signal?.reachable === true && signal.headroom !== 'loaded' && signal.installed === undefined) {
60
+ if (signal.timedOut)
61
+ timedOutCount++;
62
+ reason = signal.timedOut ? 'readiness probe timed out' : 'readiness probe did not answer';
63
+ }
64
+ else if (signal?.reachable === true) {
60
65
  reason = signal.headroom === 'loaded'
61
66
  ? 'overloaded'
62
67
  : signal.installed !== true || signal.signedIn !== true
@@ -9,6 +9,8 @@ interface ReadinessInfo {
9
9
  installed: boolean | undefined;
10
10
  signedIn: boolean | undefined;
11
11
  pickerEligible: boolean | undefined;
12
+ reason?: string;
13
+ timedOut?: boolean;
12
14
  }
13
15
  export declare function mergePlacementSignal(stats: DeviceStats | undefined, readiness: ReadinessInfo | undefined): DevicePlacementSignal;
14
16
  export declare function probePoolSignals(pool: string[], agent?: AgentType, opts?: {
@@ -3,6 +3,7 @@ import { buildFleetStatePayload } from '../accounting/usage-sync.js';
3
3
  import { probeFleetStats, headroom } from '../devices/health.js';
4
4
  import { loadDevicesSync } from '../devices/registry.js';
5
5
  import { buildSshInvocation, writeAskpassShim } from '../devices/connect.js';
6
+ import { resolveDeviceProfile } from '../devices/resolve-profile.js';
6
7
  import { buildReadyProbeCommand, parseReadyProbe, viewAgentAccountEligibility, viewHasAgent, } from '../hosts/ready.js';
7
8
  import { collectRunCandidates, isSignInRecoverable, readinessFromCandidate, } from '../accounting/rotate.js';
8
9
  import { localMachineId } from '../origin-machine.js';
@@ -23,7 +24,7 @@ function probeRemoteReadiness(device, agent, usagePayload) {
23
24
  let env;
24
25
  try {
25
26
  const shim = writeAskpassShim();
26
- const cmd = buildReadyProbeCommand(device.shell === 'powershell' ? 'windows' : undefined, { ingestUsage: true });
27
+ const cmd = buildReadyProbeCommand(resolveDeviceProfile(device).shell === 'powershell' ? 'windows' : undefined, { ingestUsage: true });
27
28
  ({ args, env } = buildSshInvocation(device, [cmd], shim, {}, { agentOnly: true }));
28
29
  }
29
30
  catch {
@@ -45,7 +46,8 @@ function probeRemoteReadiness(device, agent, usagePayload) {
45
46
  clearTimeout(killTimer);
46
47
  resolve(value);
47
48
  };
48
- const timer = setTimeout(() => child.kill('SIGTERM'), READY_PROBE_TIMEOUT_MS);
49
+ let timedOut = false;
50
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGTERM'); }, READY_PROBE_TIMEOUT_MS);
49
51
  const killTimer = setTimeout(() => { if (!settled)
50
52
  child.kill('SIGKILL'); }, READY_PROBE_TIMEOUT_MS + 250);
51
53
  killTimer.unref?.();
@@ -54,6 +56,8 @@ function probeRemoteReadiness(device, agent, usagePayload) {
54
56
  child.stderr.resume();
55
57
  child.on('error', () => finish(unknown));
56
58
  child.on('close', (code) => {
59
+ if (timedOut)
60
+ return finish({ ...unknown, timedOut: true });
57
61
  if (code !== 0 || !stdout)
58
62
  return finish(unknown);
59
63
  const probe = parseReadyProbe(stdout);
@@ -75,13 +79,14 @@ export function mergePlacementSignal(stats, readiness) {
75
79
  const reachable = readiness?.answered === true ? true : stats?.reachable;
76
80
  return {
77
81
  reachable,
78
- timedOut: reachable === true ? undefined : stats?.timedOut,
82
+ timedOut: reachable === true ? readiness?.timedOut : stats?.timedOut,
79
83
  headroom: stats ? headroom(stats) : undefined,
80
84
  loadPercent: stats?.loadPercent,
81
85
  memPercent: stats?.memPercent,
82
86
  installed: readiness?.installed,
83
87
  signedIn: readiness?.signedIn,
84
88
  pickerEligible: readiness?.pickerEligible,
89
+ reason: readiness?.reason,
85
90
  };
86
91
  }
87
92
  export async function probePoolSignals(pool, agent, opts = {}) {