@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
@@ -20,7 +20,9 @@ import { buildPreview } from './sessions-picker.js';
20
20
  import { multiItemPicker } from '../lib/picker.js';
21
21
  import { sessionRecoveryRunArgs } from '../lib/session/recovery.js';
22
22
  import { shellQuote, assertValidSshTarget } from '../lib/ssh-exec.js';
23
- import { openSurfaces, describeLaunch, currentContext, availableBackends, detectCurrentBackend, } from '../lib/terminal/index.js';
23
+ import { openSurfaces, describeLaunch, currentContext, resolveLaunchBackend, describeBackendChoice, liveHostSamples, } from '../lib/terminal/index.js';
24
+ import { stopInteractive } from './detach.js';
25
+ import { localizeHome, localProjectFolder } from '../lib/project-root.js';
24
26
  import { addressabilityRecoveryHint } from '../lib/terminal/resolve.js';
25
27
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
26
28
  import { setHelpSections } from '../lib/help.js';
@@ -381,7 +383,7 @@ async function pickFocusCandidates(sessions, liveById, initialSearch) {
381
383
  export function focusTargetForResolved(poolMatch, resolved) {
382
384
  return poolMatch ?? resolved;
383
385
  }
384
- export async function focusResolvedSession(meta, liveById, self, fallback, attachOnly, reconnectReattach = false) {
386
+ export async function focusResolvedSession(meta, liveById, self, fallback, attachOnly, reconnectReattach = false, deps = {}) {
385
387
  const active = liveById.get(meta.id);
386
388
  if (active && isAttachableLiveSession(active)) {
387
389
  await jumpTo(active, self, fallback, meta.id);
@@ -400,6 +402,10 @@ export async function focusResolvedSession(meta, liveById, self, fallback, attac
400
402
  ` To see what happened: agents ps preview ${meta.shortId}`));
401
403
  }
402
404
  const remote = sessionProcessHost(meta, self);
405
+ if (!(deps.interactive ?? isInteractiveTerminal())) {
406
+ await resumeInTab(active ?? activeFromMeta(meta), remote, { ...deps, meta, interactive: false });
407
+ return;
408
+ }
403
409
  if (remote) {
404
410
  console.log(chalk.gray(`Recovering ${meta.shortId} on ${remote}…`));
405
411
  const rc = await runOnPeer(sessionRecoveryRunArgs(meta), remote, { tty: true, sessionId: meta.id });
@@ -531,7 +537,19 @@ export async function openFocusTabs(targets, self, deps = {}) {
531
537
  await jumpTo(openable[0].s, self, selectFallback(deps.attachOnly));
532
538
  return;
533
539
  }
534
- const results = await open(openable.map((p) => ({
540
+ const ready = [];
541
+ const stopped = new Set();
542
+ for (const p of openable) {
543
+ if (p.plan.kind === 'resume' && p.s.sessionId && isLiveHeadless(p.s)) {
544
+ if (!(await stopHeadlessCopy(p.s, p.s.sessionId, sessionProcessHost(p.s, self))))
545
+ continue;
546
+ stopped.add(p.s);
547
+ }
548
+ ready.push(p);
549
+ }
550
+ if (ready.length === 0)
551
+ return;
552
+ const results = await open(ready.map((p) => ({
535
553
  cwd: cwdFor(p.s, byId),
536
554
  project: cwdFor(p.s, byId),
537
555
  command: p.plan.command,
@@ -539,12 +557,12 @@ export async function openFocusTabs(targets, self, deps = {}) {
539
557
  sessionId: p.s.sessionId || undefined,
540
558
  })), { backend, packing: 'tabs' });
541
559
  results.forEach((r, i) => {
542
- const p = openable[i];
560
+ const p = ready[i];
543
561
  const line = describeLaunch(r, { verb: 'Opened', label: `${shortId(p.s)} (${p.plan.note})` });
544
562
  if (r.ok)
545
563
  console.log(line);
546
564
  else {
547
- console.error(chalk.red(line));
565
+ console.error(chalk.red(stopped.has(p.s) ? `${line} ${stoppedNotice(p.s.sessionId)}` : line));
548
566
  process.exitCode = 1;
549
567
  }
550
568
  });
@@ -575,38 +593,81 @@ async function richMetaById(id) {
575
593
  return undefined;
576
594
  }
577
595
  }
578
- const resumeInNewTab = async (s, remote) => {
596
+ export function isLiveHeadless(s) {
597
+ return s.context === 'headless' && isRunningLiveSession(s);
598
+ }
599
+ async function stopHeadlessCopy(s, id, remote) {
600
+ if (!remote) {
601
+ console.log(chalk.gray(`${shortId(s)} is running headless (pid ${s.pid}); stopping it so the tab is its only writer.`));
602
+ await stopInteractive(s);
603
+ return true;
604
+ }
605
+ console.log(chalk.gray(`${shortId(s)} is running headless on ${remote}; stopping it there so the tab is its only writer.`));
606
+ const rc = await runOnPeer(['ps', 'stop', id, '--local'], remote);
607
+ if (rc === 'ok')
608
+ return true;
609
+ console.error(chalk.red(rc === 'failed'
610
+ ? `agents ps stop ${shortId(s)} --local failed on ${remote}, so its headless run may still be live; no second copy was opened.`
611
+ : `Can't reach ${remote} to stop the headless ${shortId(s)}, so no second copy was opened.`));
612
+ process.exitCode = 1;
613
+ return false;
614
+ }
615
+ function stoppedNotice(id) {
616
+ return `The headless run was stopped; resume it with agents run auto --resume ${id}`;
617
+ }
618
+ export async function resumeInTab(s, remote, deps = {}) {
579
619
  const id = s.sessionId ?? '';
580
620
  if (!id) {
581
621
  console.log(chalk.yellow('This session has no id to resume.'));
582
622
  return;
583
623
  }
584
- if (remote) {
585
- console.log(chalk.gray(`${shortId(s)} has no live terminal on ${remote} — resuming it there over SSH…`));
624
+ const headless = isLiveHeadless(s);
625
+ const interactive = deps.interactive ?? isInteractiveTerminal();
626
+ if (remote && interactive) {
627
+ if (headless && !(await stopHeadlessCopy(s, id, remote)))
628
+ return;
629
+ console.log(chalk.gray(`${shortId(s)} has no live terminal on ${remote}; resuming it there over SSH…`));
586
630
  const rc = await runOnPeer(sessionRecoveryRunArgs({ id }), remote, { tty: true, sessionId: id });
587
631
  if (rc === 'no-target') {
588
632
  console.log(chalk.red(`${remote} isn't reachable as a device. Try: agents devices sync`));
589
633
  console.log(chalk.gray(` recovery must run on ${remote}, where the indexed session originated`));
634
+ process.exitCode = 1;
590
635
  }
591
636
  return;
592
637
  }
593
- const meta = (await richMetaById(id)) ?? metaFromActive(s);
594
- const command = [...buildSessionRecoveryCommand(meta), '--quiet'];
595
- const cwd = meta.cwd && fs.existsSync(meta.cwd) ? meta.cwd : process.cwd();
596
- const ctx = currentContext();
597
- const backend = detectCurrentBackend(ctx) ?? availableBackends(ctx)[0]?.id;
598
- if (!backend) {
638
+ const meta = deps.meta ?? (await richMetaById(id)) ?? metaFromActive(s);
639
+ const command = [...buildSessionRecoveryCommand(meta, !!remote), '--quiet'];
640
+ const recorded = meta.cwd ?? s.cwd;
641
+ const localCwd = recorded ? localizeHome(recorded) : undefined;
642
+ const cwd = localCwd && fs.existsSync(localCwd) ? localCwd : localProjectFolder(recorded) ?? process.cwd();
643
+ const project = localProjectFolder(cwd) ?? cwd;
644
+ const choice = deps.choice !== undefined ? deps.choice : resolveLaunchBackend(currentContext(), await liveHostSamples());
645
+ if (!choice) {
646
+ if (!interactive || remote) {
647
+ console.error(chalk.red(`No terminal this machine can drive to reopen ${shortId(s)}. Run: agents run auto --resume ${id}`));
648
+ process.exitCode = 1;
649
+ return;
650
+ }
651
+ if (headless && !(await stopHeadlessCopy(s, id, undefined)))
652
+ return;
599
653
  await resumeSessionInPlace(meta);
600
654
  return;
601
655
  }
602
- console.log(chalk.gray(`${shortId(s)} has no live terminal to attach — opening a new ${backend} tab and resuming a copy.`));
603
- const results = await openSurfaces([{ cwd, project: cwd, command }], { backend, packing: 'tabs' });
656
+ if (headless && !(await stopHeadlessCopy(s, id, remote)))
657
+ return;
658
+ const what = headless ? 'resuming it' : 'resuming a copy';
659
+ const where = remote ? ` (it runs on ${remote})` : '';
660
+ console.log(chalk.gray(`${shortId(s)} has no live terminal to attach${where}; opening a new tab in ${describeBackendChoice(choice)} and ${what}.`));
661
+ const open = deps.open ?? openSurfaces;
662
+ const results = await open([{ cwd, project, command, agent: s.kind || undefined, sessionId: id }], { backend: choice.backend, packing: 'tabs' });
604
663
  const line = describeLaunch(results[0], { verb: 'Resumed', label: shortId(s) });
605
664
  if (results[0].ok)
606
665
  console.log(line);
607
666
  else {
608
- console.error(chalk.red(line));
609
- console.error(chalk.gray(` Resume it in this terminal instead: agents run auto --resume ${meta.id}`));
667
+ console.error(chalk.red(headless ? `${line} ${stoppedNotice(id)}` : line));
668
+ if (!headless)
669
+ console.error(chalk.gray(` Resume it in a terminal instead: agents run auto --resume ${meta.id}`));
610
670
  process.exitCode = 1;
611
671
  }
612
- };
672
+ }
673
+ const resumeInNewTab = (s, remote) => resumeInTab(s, remote);
@@ -63,12 +63,13 @@ export function registerProjectTodoCommands(projects) {
63
63
  });
64
64
  const listCmd = todo
65
65
  .command('list')
66
- .description(`Your open quick to-dos and anything assigned to you due today or overdue (at most ${TODO_LIST_LIMIT}).`)
66
+ .description(`Your open quick to-dos and anything assigned to you due today or overdue, or one project's open issues (at most ${TODO_LIST_LIMIT}).`)
67
+ .option('--project <name>', "List this project's open issues instead: an agents project or a Linear project name")
67
68
  .option('--json', 'Machine-readable result')
68
69
  .action(async (opts) => {
69
70
  let listed;
70
71
  try {
71
- listed = await listQuickTodos(new Date());
72
+ listed = await listQuickTodos(new Date(), { project: opts.project, defs: listProjectDefs() });
72
73
  }
73
74
  catch (err) {
74
75
  const error = linearFailure(err);
@@ -83,7 +84,7 @@ export function registerProjectTodoCommands(projects) {
83
84
  return;
84
85
  }
85
86
  if (listed.todos.length === 0)
86
- console.log('Nothing to do: no open quick to-dos, nothing due.');
87
+ console.log(opts.project ? `Nothing open in ${opts.project}.` : 'Nothing to do: no open quick to-dos, nothing due.');
87
88
  for (const t of listed.todos)
88
89
  console.log(todoLine(t));
89
90
  if (listed.total > listed.todos.length)
@@ -93,11 +94,15 @@ export function registerProjectTodoCommands(projects) {
93
94
  examples: `
94
95
  agents projects todo list
95
96
  agents projects todo list --json
97
+ agents projects todo list --project rush --json
96
98
  `,
97
99
  notes: `
98
100
  One linear tasks read of your open issues. Due ones come first (earliest due),
99
- then the newest quick to-dos. --json: { todos: [{ identifier, url, title,
100
- project, due, priority, state, createdAt, quick }], total, error }.
101
+ then the newest quick to-dos. --project lists every open issue in that
102
+ project instead (anyone's, any cycle), due ones first, then the newest.
103
+ total is the full count; todos holds at most ${TODO_LIST_LIMIT}. --json: { todos:
104
+ [{ identifier, url, title, project, due, priority, state, createdAt, quick }],
105
+ total, error }.
101
106
  `,
102
107
  });
103
108
  todo
@@ -1,10 +1,11 @@
1
1
  import type { Command } from 'commander';
2
2
  import { type LiveStatusFilter, type LiveStatusFlags } from './ps-roster.js';
3
+ import type { ActiveSession } from '../lib/session/active.js';
3
4
  export declare const PS_STATUSES: readonly LiveStatusFilter[];
4
5
  export declare function statusFlags(values: string[] | undefined): LiveStatusFlags;
5
6
  export declare function deviceScope(devices: string[] | undefined): string[] | undefined;
6
7
  export declare function registerPsCommand(program: Command): void;
7
- export declare function renderSessionPreview(query: string, scope: {
8
+ type PreviewScope = {
8
9
  agent?: string;
9
10
  project?: string;
10
11
  local?: boolean;
@@ -12,4 +13,9 @@ export declare function renderSessionPreview(query: string, scope: {
12
13
  json?: boolean;
13
14
  refresh?: boolean;
14
15
  revision?: string;
15
- }): Promise<void>;
16
+ };
17
+ type PreviewJson = Record<string, unknown>;
18
+ export declare function previewJsonFor(query: string, scope: PreviewScope, live: Promise<Map<string, ActiveSession>>): Promise<PreviewJson>;
19
+ export declare function renderSessionPreviews(queries: string[], scope: PreviewScope, read?: typeof previewJsonFor): Promise<void>;
20
+ export declare function renderSessionPreview(query: string, scope: PreviewScope): Promise<void>;
21
+ export {};
@@ -1,11 +1,13 @@
1
+ import { stripVTControlCharacters } from 'node:util';
1
2
  import chalk from 'chalk';
2
3
  import { setHelpSections } from '../lib/help.js';
3
4
  import { indexActiveBySessionId, runLiveRoster } from './ps-roster.js';
4
- import { buildPreview, loadSessionPreviewDigest, transcriptOnPeerOf } from './sessions-picker.js';
5
+ import { buildPreview, transcriptOnPeerOf } from './sessions-picker.js';
6
+ import { loadSessionPreviewDigest } from '../lib/session/preview-digest.js';
5
7
  import { isBookmarked } from '../lib/session/bookmarks.js';
6
8
  import { discoverSessions, isCompleteSessionId } from '../lib/session/discover.js';
7
9
  import { buildSessionDetailBlock, formatLiveStatusHeadline, notFoundByIdMessage, sessionTranscriptStamp } from '../lib/session/presentation.js';
8
- import { runOnPeer, shouldIncludeLocal } from '../lib/session/remote-list.js';
10
+ import { fetchPeerPreviewEnvelope, runOnPeer, shouldIncludeLocal } from '../lib/session/remote-list.js';
9
11
  import { applyScopeFilters, computeLocalMetadataMatches, metadataResolveOutcome, resolveSessionMetadataValue, resolveSessionQuery, selectorAllowsEarlyExit, serializeResolvedSessionsJson } from '../lib/session/selection.js';
10
12
  import { NO_FANOUT_ENV } from '../lib/session/remote-active.js';
11
13
  import { loadLocalActiveSessions } from '../lib/session/session-cache.js';
@@ -164,8 +166,8 @@ function registerPeerResolveCommand(ps) {
164
166
  function registerSessionPreviewCommand(parent) {
165
167
  const previewCmd = parent
166
168
  .command('preview')
167
- .argument('<id>', 'Full session ID or displayed 8-character short ID')
168
- .description('Show one rich session card without rendering the full transcript')
169
+ .argument('<id...>', 'Full session IDs or displayed 8-character short IDs')
170
+ .description('Show rich session cards without rendering the full transcripts')
169
171
  .option('-a, --agent <agent>', 'Narrow the ID to one agent type/version')
170
172
  .option('-p, --project <name>', 'Narrow the ID to one project')
171
173
  .option('--local', 'Only this machine; do not resolve the ID across the fleet')
@@ -187,19 +189,23 @@ function registerSessionPreviewCommand(parent) {
187
189
 
188
190
  # Full ID + one --device: durable-cached fast path (PHNX-3999); force a fresh fetch
189
191
  agents ps preview c70ecdea-6210-4039-9845-246a3a7a9942 --device zion --json --refresh
192
+
193
+ # Several cards in one call: a JSON array in argument order
194
+ agents ps preview 407b8dd5 c70ecdea --json
190
195
  `,
191
196
  notes: `
192
197
  - Full UUIDs are globally unique and may stop the fleet lookup at the first exact hit.
193
198
  - Short IDs wait for every selected device so ambiguity is never hidden.
194
199
  - Active status is refreshed through the bounded live-state TTL; transcript-derived details use the durable session index.
195
200
  - A full UUID with exactly one --device and --json is served from a local durable cache (~45s fresh window); the JSON envelope's "cache" field reports fresh/stale/offline state. --refresh forces one bounded re-fetch.
201
+ - With several IDs, --json prints one array in argument order; each element is the single-ID envelope plus "query", and an ID that does not resolve is an element with "error" set. The exit code is 1 only when no ID resolved.
196
202
  - Put -D after the verb: 'ps -D box preview <id>' reads 'preview' as a device.
197
203
  `,
198
204
  });
199
- previewCmd.action(async (id) => {
205
+ previewCmd.action(async (ids) => {
200
206
  const options = previewCmd.optsWithGlobals();
201
207
  const hosts = [...(options.host ?? []), ...(options.device ?? [])];
202
- await renderSessionPreview(id, {
208
+ const scope = {
203
209
  agent: options.agent,
204
210
  project: options.project,
205
211
  local: options.local,
@@ -207,29 +213,37 @@ function registerSessionPreviewCommand(parent) {
207
213
  json: options.json,
208
214
  refresh: options.refresh,
209
215
  revision: options.revision,
210
- });
216
+ };
217
+ if (ids.length === 1)
218
+ await renderSessionPreview(ids[0], scope);
219
+ else
220
+ await renderSessionPreviews(ids, scope);
211
221
  });
212
222
  }
213
- export async function renderSessionPreview(query, scope) {
214
- if (scope.json && !scope.local && scope.hosts?.length === 1
215
- && scope.hosts[0] !== machineId() && isCompleteSessionId(query.trim())) {
216
- const { getRemoteSessionPreview } = await import('../lib/session/remote-preview-cache.js');
217
- const result = await getRemoteSessionPreview(query.trim(), scope.hosts[0], {
218
- refresh: scope.refresh,
219
- revision: scope.revision,
220
- });
221
- const envelope = result.envelope;
222
- console.log(JSON.stringify({
223
- schemaVersion: 1,
224
- session: envelope?.session ?? null,
225
- active: result.cache.source === 'live' ? (envelope?.active ?? null) : null,
226
- preview: envelope?.preview ?? null,
227
- error: envelope?.error ?? (envelope ? null : result.cache.reason),
228
- details: envelope?.details ?? null,
229
- cache: result.cache,
230
- }));
231
- return;
232
- }
223
+ function previewErrorJson(message) {
224
+ return { schemaVersion: 1, session: null, active: null, preview: null, error: message, details: null };
225
+ }
226
+ async function remoteCachedPreviewJson(query, scope) {
227
+ if (!scope.json || scope.local || scope.hosts?.length !== 1
228
+ || scope.hosts[0] === machineId() || !isCompleteSessionId(query.trim()))
229
+ return undefined;
230
+ const { getRemoteSessionPreview } = await import('../lib/session/remote-preview-cache.js');
231
+ const result = await getRemoteSessionPreview(query.trim(), scope.hosts[0], {
232
+ refresh: scope.refresh,
233
+ revision: scope.revision,
234
+ });
235
+ const envelope = result.envelope;
236
+ return {
237
+ schemaVersion: 1,
238
+ session: envelope?.session ?? null,
239
+ active: result.cache.source === 'live' ? (envelope?.active ?? null) : null,
240
+ preview: envelope?.preview ?? null,
241
+ error: envelope?.error ?? (envelope ? null : result.cache.reason),
242
+ details: envelope?.details ?? null,
243
+ cache: result.cache,
244
+ };
245
+ }
246
+ async function resolvePreviewSession(query, scope) {
233
247
  let outcome = await resolveSessionMetadataValue(query, scope);
234
248
  if (outcome.kind !== 'resolved'
235
249
  && (!scope.hosts?.length || shouldIncludeLocal(scope.hosts, machineId()))) {
@@ -246,29 +260,140 @@ export async function renderSessionPreview(query, scope) {
246
260
  }
247
261
  if (outcome.kind === 'partial') {
248
262
  const offline = outcome.failedPeers;
249
- console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
250
- console.error(chalk.red(`No session matching "${query}" on any reachable device (${offline.length} unreachable, not checked).`));
251
- console.error(chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'));
252
- process.exitCode = 1;
253
- return;
263
+ return { errorLines: [
264
+ chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`),
265
+ chalk.red(`No session matching "${query}" on any reachable device (${offline.length} unreachable, not checked).`),
266
+ chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'),
267
+ ] };
254
268
  }
255
- if (outcome.kind === 'not-found') {
256
- notFoundByIdMessage(query).forEach(l => console.error(l));
257
- process.exitCode = 1;
269
+ if (outcome.kind === 'not-found')
270
+ return { errorLines: notFoundByIdMessage(query) };
271
+ if (outcome.kind === 'ambiguous') {
272
+ return { errorLines: [
273
+ chalk.red(`Multiple sessions match "${query}" across the fleet:`),
274
+ ...outcome.candidates.map((candidate) => {
275
+ const match = candidate.hits[0].session;
276
+ const machines = candidate.hits.map(hit => hit.machine).join(', ');
277
+ return chalk.cyan(` ${match.shortId} ${match.id}`) + chalk.gray(` ${machines} ${match.agent}${match.version ? ` ${match.version}` : ''}`);
278
+ }),
279
+ chalk.gray('Pass the full session ID to narrow it down.'),
280
+ ] };
281
+ }
282
+ return { session: outcome.session };
283
+ }
284
+ function localPreviewJson(session, live) {
285
+ const sourceStamp = sessionTranscriptStamp(session);
286
+ const { digest, error, events } = loadSessionPreviewDigest(session);
287
+ return {
288
+ schemaVersion: 1,
289
+ session: {
290
+ id: session.id,
291
+ shortId: session.shortId,
292
+ agent: session.agent,
293
+ version: session.version,
294
+ model: session.model,
295
+ account: session.account,
296
+ machine: session.machine ?? machineId(),
297
+ cwd: session.cwd,
298
+ project: session.project,
299
+ gitBranch: session.gitBranch,
300
+ createdAt: session.timestamp,
301
+ lastActivity: session.lastActivity,
302
+ durationMs: session.durationMs,
303
+ messageCount: session.messageCount,
304
+ tokenCount: session.tokenCount,
305
+ costUsd: session.costUsd,
306
+ label: session.label,
307
+ topic: session.topic,
308
+ ticketId: session.ticketId,
309
+ prUrl: session.prUrl,
310
+ },
311
+ active: live ? {
312
+ status: live.status,
313
+ activity: live.activity,
314
+ awaitingReason: live.awaitingReason,
315
+ lastActivityMs: live.lastActivityMs,
316
+ startedAtMs: live.startedAtMs,
317
+ pid: live.pid,
318
+ host: live.host,
319
+ } : null,
320
+ preview: digest ?? null,
321
+ error: error ?? null,
322
+ details: buildSessionDetailBlock(session, digest, events, sourceStamp),
323
+ };
324
+ }
325
+ async function liveSessionsById() {
326
+ try {
327
+ return indexActiveBySessionId((await loadLocalActiveSessions()).sessions);
328
+ }
329
+ catch {
330
+ return new Map();
331
+ }
332
+ }
333
+ export async function previewJsonFor(query, scope, live) {
334
+ const cached = await remoteCachedPreviewJson(query, scope);
335
+ if (cached)
336
+ return cached;
337
+ const resolved = await resolvePreviewSession(query, scope);
338
+ if ('errorLines' in resolved)
339
+ return previewErrorJson(resolved.errorLines.map(line => stripVTControlCharacters(line).trim()).join(' '));
340
+ const { session } = resolved;
341
+ const transcriptPeer = transcriptOnPeerOf(session);
342
+ if (transcriptPeer) {
343
+ const fetched = await fetchPeerPreviewEnvelope(session.id, transcriptPeer);
344
+ if (fetched.ok && fetched.envelope && typeof fetched.envelope === 'object' && !Array.isArray(fetched.envelope))
345
+ return fetched.envelope;
346
+ return previewErrorJson(`Session ${session.id} is on ${transcriptPeer}, but that device did not answer (${fetched.ok ? 'invalid-json' : fetched.reason}).`);
347
+ }
348
+ return localPreviewJson(session, (await live).get(session.id));
349
+ }
350
+ export async function renderSessionPreviews(queries, scope, read = previewJsonFor) {
351
+ if (!scope.json) {
352
+ const shown = [];
353
+ for (const [index, query] of queries.entries()) {
354
+ if (index > 0)
355
+ console.log('');
356
+ try {
357
+ shown.push(await printSessionPreview(query, scope));
358
+ }
359
+ catch (err) {
360
+ console.error(chalk.red(`${query}: ${err.message}`));
361
+ shown.push(false);
362
+ }
363
+ }
364
+ if (!shown.some(Boolean))
365
+ process.exitCode = 1;
258
366
  return;
259
367
  }
260
- if (outcome.kind === 'ambiguous') {
261
- console.error(chalk.red(`Multiple sessions match "${query}" across the fleet:`));
262
- for (const candidate of outcome.candidates) {
263
- const match = candidate.hits[0].session;
264
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
265
- console.error(chalk.cyan(` ${match.shortId} ${match.id}`) + chalk.gray(` ${machines} ${match.agent}${match.version ? ` ${match.version}` : ''}`));
368
+ const live = liveSessionsById();
369
+ const results = await Promise.all(queries.map(async (query) => {
370
+ try {
371
+ return { query, ...await read(query, scope, live) };
266
372
  }
267
- console.error(chalk.gray('Pass the full session ID to narrow it down.'));
373
+ catch (err) {
374
+ return { query, ...previewErrorJson(err.message) };
375
+ }
376
+ }));
377
+ console.log(JSON.stringify(results));
378
+ if (results.every(result => result.session === null))
268
379
  process.exitCode = 1;
269
- return;
380
+ }
381
+ export async function renderSessionPreview(query, scope) {
382
+ if (!await printSessionPreview(query, scope))
383
+ process.exitCode = 1;
384
+ }
385
+ async function printSessionPreview(query, scope) {
386
+ const cached = await remoteCachedPreviewJson(query, scope);
387
+ if (cached) {
388
+ console.log(JSON.stringify(cached));
389
+ return true;
390
+ }
391
+ const resolved = await resolvePreviewSession(query, scope);
392
+ if ('errorLines' in resolved) {
393
+ resolved.errorLines.forEach(line => console.error(line));
394
+ return false;
270
395
  }
271
- const session = outcome.session;
396
+ const { session } = resolved;
272
397
  const transcriptPeer = transcriptOnPeerOf(session);
273
398
  if (transcriptPeer) {
274
399
  const args = ['ps', 'preview', session.id, '--local'];
@@ -277,60 +402,18 @@ export async function renderSessionPreview(query, scope) {
277
402
  const rendered = await runOnPeer(args, transcriptPeer);
278
403
  if (rendered === 'no-target') {
279
404
  console.error(chalk.red(`Session ${session.id} is on ${transcriptPeer}, but that device is not reachable.`));
280
- process.exitCode = 1;
405
+ return false;
281
406
  }
282
- return;
407
+ return true;
283
408
  }
284
- let live;
285
- try {
286
- const loaded = await loadLocalActiveSessions();
287
- live = indexActiveBySessionId(loaded.sessions).get(session.id);
288
- }
289
- catch { }
409
+ const live = (await liveSessionsById()).get(session.id);
290
410
  if (scope.json) {
291
- const sourceStamp = sessionTranscriptStamp(session);
292
- const { digest, error, events } = loadSessionPreviewDigest(session);
293
- console.log(JSON.stringify({
294
- schemaVersion: 1,
295
- session: {
296
- id: session.id,
297
- shortId: session.shortId,
298
- agent: session.agent,
299
- version: session.version,
300
- model: session.model,
301
- account: session.account,
302
- machine: session.machine ?? machineId(),
303
- cwd: session.cwd,
304
- project: session.project,
305
- gitBranch: session.gitBranch,
306
- createdAt: session.timestamp,
307
- lastActivity: session.lastActivity,
308
- durationMs: session.durationMs,
309
- messageCount: session.messageCount,
310
- tokenCount: session.tokenCount,
311
- costUsd: session.costUsd,
312
- label: session.label,
313
- topic: session.topic,
314
- ticketId: session.ticketId,
315
- prUrl: session.prUrl,
316
- },
317
- active: live ? {
318
- status: live.status,
319
- activity: live.activity,
320
- awaitingReason: live.awaitingReason,
321
- lastActivityMs: live.lastActivityMs,
322
- startedAtMs: live.startedAtMs,
323
- pid: live.pid,
324
- host: live.host,
325
- } : null,
326
- preview: digest ?? null,
327
- error: error ?? null,
328
- details: buildSessionDetailBlock(session, digest, events, sourceStamp),
329
- }));
330
- return;
411
+ console.log(JSON.stringify(localPreviewJson(session, live)));
412
+ return true;
331
413
  }
332
414
  const headline = formatLiveStatusHeadline(live, isBookmarked(session.id));
333
415
  if (headline)
334
416
  console.log(headline);
335
417
  console.log(buildPreview(session));
418
+ return true;
336
419
  }
@@ -24,11 +24,6 @@ export declare function setPeerDigestFetcherForTest(fetcher?: typeof fetchPeerPr
24
24
  export declare function clearRemoteDigestCacheForTest(): void;
25
25
  export declare function sanitizeRemoteDigest(raw: unknown): SessionPreviewDigest | undefined;
26
26
  export declare function clearPreviewMemoryCacheForTest(): void;
27
- export declare function loadSessionPreviewDigest(session: SessionMeta): {
28
- digest?: SessionPreviewDigest;
29
- events: SessionEvent[];
30
- error?: string;
31
- };
32
27
  export declare function buildPreview(session: SessionMeta): string;
33
28
  export declare function formatFanOut(session: SessionMeta, derived?: {
34
29
  subAgentCount?: number;
@@ -40,8 +35,6 @@ export declare function extractTiming(session: Pick<SessionMeta, 'timestamp' | '
40
35
  lastActiveAgo?: string;
41
36
  duration?: string;
42
37
  };
43
- export declare function buildSessionPreviewDigest(events: SessionEvent[], session: SessionMeta): SessionPreviewDigest;
44
- export declare function relativizeDir(filePath: string, cwd?: string): string | undefined;
45
38
  export declare function renderLastResponse(content: string, maxLines?: number, width?: number): string[];
46
39
  export declare function sessionPicker(config: SessionPickerConfig): Promise<PickedSession | null>;
47
40
  export declare function pickSessionInteractive(sessions: SessionMeta[], message?: string, initialSearch?: string, hiddenCount?: number, enterHint?: string, scope?: SessionSearchScope): Promise<PickedSession | null>;