@phnx-labs/agents-cli 1.23.0 → 1.23.2

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 (59) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -0
  3. package/dist/commands/cloud-transcripts.js +1 -2
  4. package/dist/commands/daemon.js +70 -11
  5. package/dist/commands/exec.js +1 -1
  6. package/dist/commands/feed.js +1 -2
  7. package/dist/commands/focus.js +4 -1
  8. package/dist/commands/go.js +3 -2
  9. package/dist/commands/logs.js +1 -1
  10. package/dist/commands/menubar.js +28 -3
  11. package/dist/commands/ps-roster.d.ts +0 -11
  12. package/dist/commands/ps-roster.js +3 -116
  13. package/dist/commands/ps.d.ts +10 -0
  14. package/dist/commands/ps.js +182 -1
  15. package/dist/commands/resume.js +1 -1
  16. package/dist/commands/sessions-browser.d.ts +0 -1
  17. package/dist/commands/sessions-browser.js +6 -23
  18. package/dist/commands/sessions-export.js +1 -1
  19. package/dist/commands/sessions-migrate.js +1 -1
  20. package/dist/commands/sessions-picker.d.ts +6 -32
  21. package/dist/commands/sessions-picker.js +81 -8
  22. package/dist/commands/sessions-render.js +1 -1
  23. package/dist/commands/sessions-resume.js +2 -2
  24. package/dist/commands/sessions-share.js +1 -1
  25. package/dist/commands/sessions-trace.js +1 -1
  26. package/dist/commands/sessions.d.ts +2 -165
  27. package/dist/commands/sessions.js +16 -1216
  28. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  29. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  30. package/dist/lib/daemon/attention-notify-service.js +8 -4
  31. package/dist/lib/daemon/daemon.d.ts +5 -1
  32. package/dist/lib/daemon/daemon.js +53 -6
  33. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  34. package/dist/lib/daemon/diagnostics.js +185 -0
  35. package/dist/lib/daemon/service.d.ts +1 -1
  36. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  37. package/dist/lib/daemon/session-state-service.js +2 -2
  38. package/dist/lib/daemon/supervisor.d.ts +8 -0
  39. package/dist/lib/daemon/supervisor.js +47 -6
  40. package/dist/lib/daemon-services.d.ts +3 -0
  41. package/dist/lib/daemon-services.js +36 -0
  42. package/dist/lib/daemon-ticks.d.ts +3 -1
  43. package/dist/lib/daemon-ticks.js +18 -12
  44. package/dist/lib/feed/tool-activity.js +10 -3
  45. package/dist/lib/feed/watch.js +8 -5
  46. package/dist/lib/helper-versions.js +1 -1
  47. package/dist/lib/menubar/install-menubar.d.ts +19 -1
  48. package/dist/lib/menubar/install-menubar.js +81 -12
  49. package/dist/lib/session/active.js +18 -14
  50. package/dist/lib/session/pid-registry.js +9 -6
  51. package/dist/lib/session/presentation.d.ts +107 -1
  52. package/dist/lib/session/presentation.js +543 -4
  53. package/dist/lib/session/remote/remote-list.d.ts +3 -0
  54. package/dist/lib/session/remote/remote-list.js +13 -0
  55. package/dist/lib/session/resume-command.d.ts +9 -0
  56. package/dist/lib/session/resume-command.js +107 -0
  57. package/dist/lib/session/selection.d.ts +102 -0
  58. package/dist/lib/session/selection.js +443 -0
  59. package/package.json +1 -1
@@ -1,58 +1,46 @@
1
1
  import * as fs from 'fs';
2
2
  import * as os from 'os';
3
3
  import * as path from 'path';
4
- import { spawn } from 'child_process';
5
4
  import { Option } from 'commander';
6
5
  import chalk from 'chalk';
7
- import { truncate, padRight, humanDuration, formatBytes } from '../lib/format.js';
8
- import { sanitizeForTerminal, redactSecrets } from '../lib/redact.js';
6
+ import { padRight, humanDuration, formatBytes } from '../lib/format.js';
9
7
  import { resolveProjectKey } from '../lib/project-key.js';
10
8
  import { listProjectDefs, resolveProjectNameForCwd } from '../lib/projects.js';
11
9
  import ora from 'ora';
12
10
  import { interruptibleSpinner } from '../lib/spinner.js';
13
- import { SESSION_AGENTS, isAgentTmuxAlias, sessionDisplayAgent } from '@phnx-labs/sessions-cli/reader';
11
+ import { SESSION_AGENTS, sessionDisplayAgent } from '@phnx-labs/sessions-cli/reader';
14
12
  import { discoverArtifacts, readArtifact, resolveArtifact } from '@phnx-labs/sessions-cli/reader';
15
- import { looksLikePath, toComparablePath, homeDir, needsWindowsShell, composeWin32CommandLine } from '../lib/platform/index.js';
16
- import { getActiveSessions, serializeSessionsJson, shortIdFromName } from '../lib/session/active.js';
13
+ import { looksLikePath, toComparablePath } from '../lib/platform/index.js';
14
+ import { getActiveSessions, serializeSessionsJson } from '../lib/session/active.js';
17
15
  export { activeSessionProjectKey, backfillActiveRowsFromIndex, backfillActiveRowsFromMeta, isRunningLiveSession, serializeActiveSessionsForJson, serializeSessionsJson } from '../lib/session/active.js';
18
16
  import { viewingInLabel } from '../lib/session/viewing-in.js';
19
17
  import { machineId } from '../lib/session/sync/config.js';
20
18
  import { NO_FANOUT_ENV } from '../lib/session/remote-active.js';
21
- import { loadLocalActiveSessions, readActiveSessionsCache, } from '../lib/session/session-cache.js';
22
- import { gatherRemoteList, runOnPeer } from '../lib/session/remote-list.js';
19
+ import { gatherRemoteList, runOnPeer, shouldIncludeLocal } from '../lib/session/remote-list.js';
23
20
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
24
- import { discoverSessions, countSessionsInScope, resolveSessionById, isCompleteSessionId, looksLikeSessionId, searchContentIndex, getSessionRoots } from '../lib/session/discover.js';
25
- import { findSessionsById, querySessions, readSessionTimelineAny } from '../lib/session/db.js';
26
- import { foldTimeline, emptyTimelineState, projectTimeline, projectSessionFiles } from '@phnx-labs/sessions-cli/reader';
27
- import { readSessionTail } from '@phnx-labs/sessions-cli/reader';
28
- import { liveSessionMetas, fleetExecutionMachineById, reconcileLiveMetaMachine } from '../lib/session/live-metadata.js';
21
+ import { discoverSessions, countSessionsInScope, resolveSessionById, looksLikeSessionId, getSessionRoots } from '../lib/session/discover.js';
29
22
  import { sessionHeadline } from '../lib/session/title.js';
30
23
  import { filterTeamSessions, shouldShowTeamSessions, safeTeamText, groupSessionsByTeam, NO_TEAM_GROUP_KEY, } from '@phnx-labs/sessions-cli/reader';
31
24
  import { runRemoteSessions, buildForwardedArgs, ensureWholeIndex } from '../lib/session/remote.js';
32
25
  import { formatRelativeTime, sessionAgeParts } from '../lib/session/relative-time.js';
33
- import { linkPath, linkUrl, shortenModel, formatTokenCount } from '@phnx-labs/sessions-cli/reader';
34
- import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
35
- import { sessionOwnerDevice, RESUME_PINNED_ENV } from '../lib/session/resume-owner.js';
36
- import { AGENTS, colorAgent, resolveAgentName } from '../lib/agents.js';
37
- import { getShimsDir } from '../lib/state.js';
26
+ import { shortenModel, formatTokenCount } from '@phnx-labs/sessions-cli/reader';
27
+ import { colorAgent } from '../lib/agents.js';
38
28
  import { listJobs, listJobsWithRuns, listRuns, getRunDir } from '../lib/scheduling/routines.js';
39
29
  import { formatUsd } from '../lib/pricing/cost.js';
40
- import { fuzzyMatch, FUZZY_PRESETS } from '../lib/fuzzy.js';
41
30
  import { itemPicker } from '../lib/picker.js';
42
- import { resolveSessionAlias } from '../lib/session/actor-sidecar.js';
43
- import { listInstalledVersions, resolveVersionAliasLoose } from '../lib/installations/versions.js';
44
- import { getAgentsInvocation } from '../lib/daemon/daemon.js';
45
- import { sessionAgentSupportsResume, sessionRecoveryRunArgs } from '../lib/session/recovery.js';
46
31
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
47
- import { sessionPicker, buildPreview, loadSessionPreviewDigest, transcriptOnPeerOf, formatTodoCompact, } from './sessions-picker.js';
32
+ import { transcriptOnPeerOf, handlePickedSession, pickSessionInteractive, } from './sessions-picker.js';
48
33
  import { setHelpSections } from '../lib/help.js';
49
- import { cleanPreview, gatherActiveSessions, indexActiveBySessionId, isAwaitingUser, liveGlyphAndPreview, liveStatusWord, requestedLiveStatuses, resolveRoutineName, runLiveRoster, shouldIncludeLocal, statusColor, } from './ps-roster.js';
50
- import { buildFilterOptions, hasAnyFilter, metaSignals, renderSession, resolveViewMode, signalBadges, } from '../lib/session/presentation.js';
34
+ import { gatherActiveSessions, indexActiveBySessionId, requestedLiveStatuses, resolveRoutineName, runLiveRoster, } from './ps-roster.js';
35
+ import { buildFilterOptions, cleanPreview, formatTeamHiddenFooter, formatTodoCompact, hasAnyFilter, liveGlyphAndPreview, liveStatusCell, metaSignals, notFoundByIdMessage, printSessionTable, renderSession, resolveViewMode, signalBadges, timeCell, treeSessionRow, } from '../lib/session/presentation.js';
36
+ import { buildResumeCommand } from '../lib/session/resume-command.js';
51
37
  export { buildFilterOptions, renderSession, renderSessionLog, renderSessionLogJson, resolveViewMode, } from '../lib/session/presentation.js';
38
+ import { applyScopeFilters, computeLocalMetadataMatches, filterSessionsByQuery, fleetCandidatesByQuery, isDefinitiveMatch, matchesTeam, mergeLocalFirst, parseAgentFilter, parseInstalledAgentVersionQuery, resolveSessionMetadataValue, resolveSessionQuery, scopedContentIndex, selectorAllowsEarlyExit, serializeResolvedSessionsJson, } from '../lib/session/selection.js';
39
+ import { registerSessionPreviewCommand, renderSessionPreview } from './ps.js';
52
40
  import { registerSessionsResumeCommand } from './sessions-resume.js';
53
41
  import { registerSessionsForkCommand } from './fork.js';
54
42
  import { registerSessionsBookmarkCommand } from './sessions-bookmark.js';
55
- import { isBookmarked, listBookmarks } from '../lib/session/bookmarks.js';
43
+ import { listBookmarks } from '../lib/session/bookmarks.js';
56
44
  import { registerFocusCommand } from './focus.js';
57
45
  import { registerDetachCommand } from './detach.js';
58
46
  import { registerSessionsStopCommand } from './sessions-stop.js';
@@ -81,20 +69,6 @@ function applyAgentShorthands(options) {
81
69
  if (hit)
82
70
  options.agent = hit;
83
71
  }
84
- export function parseInstalledAgentVersionQuery(query, installedVersions = (agent) => (agent in AGENTS ? listInstalledVersions(agent) : [])) {
85
- const trimmed = query?.trim();
86
- if (!trimmed)
87
- return undefined;
88
- const at = trimmed.indexOf('@');
89
- if (at <= 0 || at !== trimmed.lastIndexOf('@') || at === trimmed.length - 1)
90
- return undefined;
91
- const agentName = trimmed.slice(0, at).toLowerCase();
92
- if (!SESSION_AGENTS.includes(agentName))
93
- return undefined;
94
- const agent = agentName;
95
- const version = trimmed.slice(at + 1);
96
- return installedVersions(agent).includes(version) ? `${agent}@${version}` : undefined;
97
- }
98
72
  function applyVersionFilters(query, options) {
99
73
  const explicitVersion = options.version ?? options.sessionVersion;
100
74
  if (explicitVersion) {
@@ -153,7 +127,6 @@ function createScanProgressTracker(verbs, suffix, spinner) {
153
127
  },
154
128
  };
155
129
  }
156
- const PICKER_RECENT_COUNT = 15;
157
130
  const DEFAULT_LIMIT = '50';
158
131
  const WHOLE_TEAM_POOL_LIMIT = 5000;
159
132
  const OVERVIEW_ROWS_PER_PROJECT = 5;
@@ -214,44 +187,11 @@ function contextColor(context) {
214
187
  case 'headless': return chalk.gray;
215
188
  }
216
189
  }
217
- function shortCwd(cwd) {
218
- if (!cwd)
219
- return '-';
220
- const home = homeDir();
221
- return toComparablePath(cwd).startsWith(toComparablePath(home))
222
- ? '~' + cwd.slice(home.length)
223
- : cwd;
224
- }
225
190
  function formatStartedAt(startedAtMs) {
226
191
  if (!startedAtMs)
227
192
  return '-';
228
193
  return formatRelativeTime(new Date(startedAtMs).toISOString());
229
194
  }
230
- const LIVE_STATUS_W = 8;
231
- function liveStatusCell(live) {
232
- const word = liveStatusWord(live);
233
- if (!word || !live)
234
- return { cell: '', width: 0 };
235
- return { cell: statusColor(live.status)(padToWidth(word, LIVE_STATUS_W)), width: LIVE_STATUS_W };
236
- }
237
- export function ticketLabel(s) {
238
- return s.ticketId ?? (s.prNumber ? `PR#${s.prNumber}` : '');
239
- }
240
- function ticketUrl(s) {
241
- if (s.ticketId)
242
- return linearIssueUrl(s.ticketId);
243
- return s.prNumber ? s.prUrl : undefined;
244
- }
245
- export function linkTicketCell(s, label) {
246
- const url = ticketUrl(s);
247
- return url && label.trim() !== '-' ? linkUrl(url, label) : label;
248
- }
249
- export function linkCwdCell(s, label) {
250
- return s.cwd && !s._remote ? linkPath(s.cwd, label) : label;
251
- }
252
- function modelLabel(model) {
253
- return model ? shortenModel(model) : '-';
254
- }
255
195
  export function serializeSessionPickerRows(sessions, liveSessions, self = machineId()) {
256
196
  const liveById = new Map(liveSessions.filter((row) => row.sessionId).map((row) => [row.sessionId, row]));
257
197
  return sessions.map((session) => {
@@ -274,50 +214,6 @@ export function serializeSessionPickerRows(sessions, liveSessions, self = machin
274
214
  };
275
215
  });
276
216
  }
277
- export function mergeLocalFirst(sessions, localMachine) {
278
- const byMachine = new Map();
279
- const seen = new Set();
280
- for (const s of sessions) {
281
- const machine = s.machine || localMachine;
282
- if (s.id) {
283
- const dedupeKey = `${machine}:${s.id}`;
284
- if (seen.has(dedupeKey))
285
- continue;
286
- seen.add(dedupeKey);
287
- }
288
- (byMachine.get(machine) ?? byMachine.set(machine, []).get(machine)).push(s);
289
- }
290
- const keys = Array.from(byMachine.keys()).sort((a, b) => {
291
- if (a === localMachine)
292
- return -1;
293
- if (b === localMachine)
294
- return 1;
295
- const ac = byMachine.get(a).length, bc = byMachine.get(b).length;
296
- if (ac !== bc)
297
- return bc - ac;
298
- return a.localeCompare(b);
299
- });
300
- return keys.flatMap((k) => byMachine.get(k));
301
- }
302
- // Peer resolution exposes launch identity only; paths, plans, costs, and content stay local.
303
- export function serializeResolvedSessionsJson(sessions) {
304
- const safe = sessions.map((session) => ({
305
- id: session.id,
306
- shortId: session.shortId,
307
- agent: session.agent,
308
- harness: session.harness,
309
- origin: session.origin,
310
- timestamp: session.timestamp,
311
- lastActivity: session.lastActivity,
312
- project: session.project,
313
- version: session.version,
314
- mode: session.mode,
315
- label: session.label,
316
- topic: session.topic,
317
- machine: session.machine,
318
- }));
319
- return JSON.stringify(safe, null, 2) + '\n';
320
- }
321
217
  async function runRemoteSessionsJson(hosts) {
322
218
  const forwarded = ensureWholeIndex(buildForwardedArgs(process.argv, new Set(hosts)));
323
219
  if (!forwarded.includes('--json'))
@@ -675,214 +571,6 @@ function canonicalSessionsCommand(query, options) {
675
571
  a.push(JSON.stringify(q));
676
572
  return 'ag ' + a.join(' ');
677
573
  }
678
- const SESSION_DETAIL_MAX_MESSAGES = 8;
679
- const SESSION_DETAIL_MESSAGE_MAX_CHARS = 4_000;
680
- function sessionTranscriptStamp(session) {
681
- try {
682
- if (!session.filePath)
683
- return undefined;
684
- const stat = fs.statSync(session.filePath);
685
- return { fileMtimeMs: stat.mtimeMs, fileSize: stat.size };
686
- }
687
- catch {
688
- return undefined;
689
- }
690
- }
691
- export function buildSessionDetailBlock(session, digest, events, sourceStamp) {
692
- const bound = (text) => redactSecrets(sanitizeForTerminal(text)).slice(0, SESSION_DETAIL_MESSAGE_MAX_CHARS);
693
- const stamp = sourceStamp ?? sessionTranscriptStamp(session);
694
- const canDateEvents = sourceStamp !== undefined || events.length === 0;
695
- const daemonProjection = stamp ? readSessionTimelineAny(session.id, stamp) : undefined;
696
- let foldEvents = events;
697
- if (foldEvents.length === 0 && session.filePath) {
698
- foldEvents = readSessionTail(session.filePath, session.agent);
699
- }
700
- let projection = daemonProjection;
701
- let onDemand = false;
702
- if (!projection && foldEvents.length > 0) {
703
- const state = foldTimeline(foldEvents, emptyTimelineState());
704
- projection = {
705
- request: state.request,
706
- timeline: projectTimeline(state, undefined),
707
- files: projectSessionFiles(state),
708
- };
709
- onDemand = true;
710
- }
711
- let messages;
712
- if (foldEvents.length > 0) {
713
- messages = foldEvents
714
- .filter((e) => e.type === 'message' && !e._synthetic && Boolean(e.content) && (e.role === 'user' || e.role === 'assistant'))
715
- .slice(-SESSION_DETAIL_MAX_MESSAGES)
716
- .map(e => ({ role: e.role, text: bound(e.content), at: e.timestamp ?? null }));
717
- }
718
- else {
719
- messages = [];
720
- if (digest?.firstUser)
721
- messages.push({ role: 'user', text: bound(digest.firstUser), at: session.timestamp ?? null });
722
- if (digest?.lastAssistant)
723
- messages.push({ role: 'assistant', text: bound(digest.lastAssistant), at: session.lastActivity ?? null });
724
- }
725
- const endStamp = sessionTranscriptStamp(session);
726
- const unchanged = canDateEvents && stamp !== undefined && endStamp !== undefined
727
- && stamp.fileMtimeMs === endStamp.fileMtimeMs && stamp.fileSize === endStamp.fileSize;
728
- const partial = Boolean(digest?.partial) || !daemonProjection || !unchanged;
729
- const reason = digest?.partialReason
730
- ?? (onDemand
731
- ? 'background timeline pass has not reached this session yet; request/timeline/files below are an on-demand bounded fold, not the full-history daemon projection'
732
- : (!projection ? 'no transcript available to fold request/timeline/files for this session' : null));
733
- return {
734
- request: projection?.request ?? null,
735
- timeline: projection?.timeline ?? null,
736
- files: projection?.files ?? null,
737
- messages,
738
- sourceRevision: unchanged ? new Date(stamp.fileMtimeMs).toISOString() : null,
739
- partial,
740
- reason,
741
- };
742
- }
743
- export async function renderSessionPreview(query, scope) {
744
- if (scope.json && !scope.local && scope.hosts?.length === 1
745
- && scope.hosts[0] !== machineId() && isCompleteSessionId(query.trim())) {
746
- const { getRemoteSessionPreview } = await import('../lib/session/remote-preview-cache.js');
747
- const result = await getRemoteSessionPreview(query.trim(), scope.hosts[0], {
748
- refresh: scope.refresh,
749
- revision: scope.revision,
750
- });
751
- const envelope = result.envelope;
752
- console.log(JSON.stringify({
753
- schemaVersion: 1,
754
- session: envelope?.session ?? null,
755
- active: result.cache.source === 'live' ? (envelope?.active ?? null) : null,
756
- preview: envelope?.preview ?? null,
757
- error: envelope?.error ?? (envelope ? null : result.cache.reason),
758
- details: envelope?.details ?? null,
759
- cache: result.cache,
760
- }));
761
- return;
762
- }
763
- let outcome = await resolveSessionMetadataValue(query, scope);
764
- if (outcome.kind !== 'resolved'
765
- && (!scope.hosts?.length || shouldIncludeLocal(scope.hosts, machineId()))) {
766
- const discovered = applyScopeFilters(await discoverSessions({ all: true, cwd: process.cwd(), limit: 5000, waitForScan: true }), scope);
767
- const localMatches = resolveSessionQuery(discovered, query, { indexFallback: false, scope }).matches
768
- .map(session => ({ ...session, machine: session.machine || machineId() }));
769
- const exact = localMatches.find(session => selectorAllowsEarlyExit(query)
770
- && session.id.toLowerCase() === query.trim().toLowerCase());
771
- if (exact)
772
- outcome = { kind: 'resolved', session: exact };
773
- else if (outcome.kind === 'not-found' && localMatches.length > 0) {
774
- outcome = metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, query);
775
- }
776
- }
777
- if (outcome.kind === 'partial') {
778
- const offline = outcome.failedPeers;
779
- console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
780
- console.error(chalk.red(`No session matching "${query}" on any reachable device (${offline.length} unreachable, not checked).`));
781
- console.error(chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'));
782
- process.exitCode = 1;
783
- return;
784
- }
785
- if (outcome.kind === 'not-found') {
786
- notFoundByIdMessage(query).forEach(l => console.error(l));
787
- process.exitCode = 1;
788
- return;
789
- }
790
- if (outcome.kind === 'ambiguous') {
791
- console.error(chalk.red(`Multiple sessions match "${query}" across the fleet:`));
792
- for (const candidate of outcome.candidates) {
793
- const match = candidate.hits[0].session;
794
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
795
- console.error(chalk.cyan(` ${match.shortId} ${match.id}`) + chalk.gray(` ${machines} ${match.agent}${match.version ? ` ${match.version}` : ''}`));
796
- }
797
- console.error(chalk.gray('Pass the full session ID to narrow it down.'));
798
- process.exitCode = 1;
799
- return;
800
- }
801
- const session = outcome.session;
802
- const transcriptPeer = transcriptOnPeerOf(session);
803
- if (transcriptPeer) {
804
- const args = ['sessions', 'preview', session.id, '--local'];
805
- if (scope.json)
806
- args.push('--json');
807
- const rendered = await runOnPeer(args, transcriptPeer);
808
- if (rendered === 'no-target') {
809
- console.error(chalk.red(`Session ${session.id} is on ${transcriptPeer}, but that device is not reachable.`));
810
- process.exitCode = 1;
811
- }
812
- return;
813
- }
814
- let live;
815
- try {
816
- const loaded = await loadLocalActiveSessions();
817
- live = indexActiveBySessionId(loaded.sessions).get(session.id);
818
- }
819
- catch { }
820
- if (scope.json) {
821
- const sourceStamp = sessionTranscriptStamp(session);
822
- const { digest, error, events } = loadSessionPreviewDigest(session);
823
- console.log(JSON.stringify({
824
- schemaVersion: 1,
825
- session: {
826
- id: session.id,
827
- shortId: session.shortId,
828
- agent: session.agent,
829
- version: session.version,
830
- model: session.model,
831
- account: session.account,
832
- machine: session.machine ?? machineId(),
833
- cwd: session.cwd,
834
- project: session.project,
835
- gitBranch: session.gitBranch,
836
- createdAt: session.timestamp,
837
- lastActivity: session.lastActivity,
838
- durationMs: session.durationMs,
839
- messageCount: session.messageCount,
840
- tokenCount: session.tokenCount,
841
- costUsd: session.costUsd,
842
- label: session.label,
843
- topic: session.topic,
844
- ticketId: session.ticketId,
845
- prUrl: session.prUrl,
846
- },
847
- active: live ? {
848
- status: live.status,
849
- activity: live.activity,
850
- awaitingReason: live.awaitingReason,
851
- lastActivityMs: live.lastActivityMs,
852
- startedAtMs: live.startedAtMs,
853
- pid: live.pid,
854
- host: live.host,
855
- } : null,
856
- preview: digest ?? null,
857
- error: error ?? null,
858
- details: buildSessionDetailBlock(session, digest, events, sourceStamp),
859
- }));
860
- return;
861
- }
862
- const headline = formatLiveStatusHeadline(live, isBookmarked(session.id));
863
- if (headline)
864
- console.log(headline);
865
- console.log(buildPreview(session));
866
- }
867
- export function formatLiveStatusHeadline(live, bookmarked = false) {
868
- const star = bookmarked ? chalk.yellow('★ ') : '';
869
- if (!live)
870
- return bookmarked ? chalk.yellow('★ bookmarked') : '';
871
- const { glyph } = liveGlyphAndPreview(live);
872
- const word = liveStatusWord(live) || live.status;
873
- const needsYou = isAwaitingUser(live);
874
- const reason = live.awaitingReason ? ` (${live.awaitingReason.replace('_', ' ')})` : '';
875
- let suffix = needsYou ? chalk.yellow(` ← needs you${reason}`) : '';
876
- if (live.status === 'crashed') {
877
- suffix = chalk.redBright(' ← the host app or connection went away and took the agent with it');
878
- }
879
- else if (live.status === 'orphaned') {
880
- suffix = needsYou
881
- ? chalk.yellow(` ← waiting on you${reason}, and no client is attached to answer it`)
882
- : chalk.yellow(' ← still running, but no client is attached — nothing is showing it');
883
- }
884
- return `${star}${glyph} ${statusColor(live.status)(word)}${suffix}`;
885
- }
886
574
  async function sessionsAction(query, options, limitSource) {
887
575
  const liveStatuses = requestedLiveStatuses(options);
888
576
  const liveOnly = options.active === true || liveStatuses.length > 0;
@@ -1259,130 +947,6 @@ async function sessionsAction(query, options, limitSource) {
1259
947
  process.exit(1);
1260
948
  }
1261
949
  }
1262
- function teamTag(session) {
1263
- const origin = session.teamOrigin;
1264
- if (!origin)
1265
- return '';
1266
- const handle = safeTeamText(origin.handle);
1267
- const team = safeTeamText(origin.team);
1268
- if (team)
1269
- return `[${team}${handle ? `/${handle}` : ''}] `;
1270
- return handle ? `[${handle}] ` : '[team] ';
1271
- }
1272
- export function matchesTeam(session, team) {
1273
- const want = safeTeamText(team)?.trim().toLowerCase();
1274
- if (!want)
1275
- return true;
1276
- return (safeTeamText(session.spawnedTeam)?.toLowerCase() === want ||
1277
- safeTeamText(session.teamOrigin?.team)?.toLowerCase() === want);
1278
- }
1279
- const TEAM_BADGE_MAX = 10;
1280
- export function teamBadge(session) {
1281
- const team = safeTeamText(session.spawnedTeam);
1282
- if (!team)
1283
- return { plain: '', width: 0 };
1284
- const plain = `team:${truncate(team, TEAM_BADGE_MAX)} `;
1285
- return { plain, width: stringWidth(plain) };
1286
- }
1287
- function originTag(session) {
1288
- if (session.origin !== 'routine')
1289
- return '';
1290
- return `[routine${session.routineName ? ` · ${session.routineName}` : ''}] `;
1291
- }
1292
- const MIN_TOPIC_W = 16;
1293
- function timeCell(age, topicSlack) {
1294
- const lastOnly = { plain: age.last, text: chalk.gray(age.last), extraW: 0 };
1295
- if (!age.created)
1296
- return lastOnly;
1297
- const prefix = `${age.created} → `;
1298
- const extraW = stringWidth(prefix);
1299
- if (topicSlack - extraW < MIN_TOPIC_W)
1300
- return lastOnly;
1301
- return { plain: prefix + age.last, text: chalk.dim(prefix) + chalk.gray(age.last), extraW };
1302
- }
1303
- export function flatSessionRow(session, live, showTicket = false, cols = {}, bookmarked = false) {
1304
- const shown = sessionDisplayAgent(session);
1305
- const agentColor = colorAgent(shown);
1306
- const age = sessionAgeParts(session.timestamp, session.lastActivity);
1307
- const project = session.project || '-';
1308
- const tag = originTag(session) || teamTag(session);
1309
- const label = session.label;
1310
- const { glyph, preview } = liveGlyphAndPreview(live);
1311
- const restingTodo = !live ? formatTodoCompact(session.todos) : '';
1312
- const topicBase = tag ? `${tag}${session.topic ?? ''}` : session.topic;
1313
- const doing = [restingTodo, preview || topicBase].filter(Boolean).join(' · ') || undefined;
1314
- const wt = session.worktreeSlug ? chalk.magenta(`wt:${session.worktreeSlug}`) : '';
1315
- const team = teamBadge(session);
1316
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1317
- const machineColW = cols.machineWidth ?? PICKER_MACHINE_W;
1318
- const machineCell = cols.showMachine
1319
- ? chalk.gray(padToWidth(truncateToWidth((cols.machineLabel?.(session.machine ?? '') ?? session.machine ?? '') || '-', machineColW - 1), machineColW))
1320
- : '';
1321
- const TICKET_W = 10;
1322
- const ticketCell = showTicket
1323
- ? chalk.blue(linkTicketCell(session, padToWidth(truncateToWidth(ticketLabel(session) || '-', TICKET_W), TICKET_W + 1)))
1324
- : '';
1325
- const { cell: statusCell, width: statusW } = liveStatusCell(live);
1326
- const glyphW = glyph ? 2 : 0;
1327
- const machineW = cols.showMachine ? machineColW : 0;
1328
- const ticketW = showTicket ? TICKET_W + 1 : 0;
1329
- const wtW = wt ? stringWidth(wt) + 1 : 0;
1330
- const width = terminalWidth();
1331
- const requestedModelW = cols.showModel ? (cols.modelWidth ?? PICKER_MODEL_MAX) : 0;
1332
- const bookmarkW = cols.showBookmark ? 2 : 0;
1333
- const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
1334
- const fixedW = bookmarkW + (10 + 9 + 8 + 16) + glyphW + statusW + machineW + ticketW + wtW + team.width + stringWidth(age.last) + 1;
1335
- const modelSlack = width - fixedW - MIN_TOPIC_W;
1336
- const modelW = requestedModelW <= modelSlack
1337
- ? requestedModelW
1338
- : modelSlack >= PICKER_MODEL_MIN ? modelSlack : 0;
1339
- const when = timeCell(age, width - fixedW - modelW);
1340
- const topicW = Math.max(MIN_TOPIC_W, width - fixedW - modelW - when.extraW);
1341
- return (bookmarkCell +
1342
- chalk.white(padToWidth(truncateToWidth(session.shortId, 9), 10)) +
1343
- agentColor(padToWidth(truncateToWidth(shown, 8), 9)) +
1344
- chalk.yellow(padToWidth(truncateToWidth(session.version || '-', 7), 8)) +
1345
- (modelW ? chalk.yellow(padToWidth(truncateToWidth(modelLabel(session.model), modelW - 1), modelW)) : '') +
1346
- machineCell +
1347
- chalk.cyan(linkCwdCell(session, padToWidth(truncateToWidth(project, 14), 16))) +
1348
- (glyph ? glyph + ' ' : '') +
1349
- statusCell +
1350
- teamSeg +
1351
- renderTopicCell(label, doing, '', topicW, topicW) +
1352
- ticketCell +
1353
- (wt ? wt + ' ' : '') +
1354
- when.text);
1355
- }
1356
- function treeSessionRow(session, live) {
1357
- const shown = sessionDisplayAgent(session);
1358
- const agentColor = colorAgent(shown);
1359
- const age = sessionAgeParts(session.timestamp, session.lastActivity);
1360
- const tag = originTag(session) || teamTag(session);
1361
- const label = session.label;
1362
- const { glyph, preview } = liveGlyphAndPreview(live);
1363
- const restingTodo = !live ? formatTodoCompact(session.todos) : '';
1364
- const topicBase = preview || (tag ? `${tag}${session.topic ?? ''}` : session.topic);
1365
- const topic = [restingTodo, topicBase].filter(Boolean).join(' · ') || '-';
1366
- const badges = signalBadges(metaSignals(session));
1367
- const badgeW = badges ? stringWidth(badges) + 1 : 0;
1368
- const team = teamBadge(session);
1369
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1370
- const head = label ? `${label} · ${topic}` : topic;
1371
- const { cell: statusCell, width: statusW } = liveStatusCell(live);
1372
- const glyphW = glyph ? 2 : 0;
1373
- const baseTopicW = terminalWidth() - (2 + 9 + 8) - glyphW - statusW - badgeW - team.width - stringWidth(age.last) - 1;
1374
- const when = timeCell(age, baseTopicW);
1375
- const topicW = Math.max(12, baseTopicW - when.extraW);
1376
- return (' ' +
1377
- chalk.dim(padToWidth(session.shortId, 9)) +
1378
- agentColor(padToWidth(truncateToWidth(shown, 7), 8)) +
1379
- (badges ? badges + ' ' : '') +
1380
- (glyph ? glyph + ' ' : '') +
1381
- statusCell +
1382
- teamSeg +
1383
- padToWidth(chalk.white(truncateToWidth(head, topicW)), topicW) +
1384
- ' ' + when.text);
1385
- }
1386
950
  export async function maybeLiveIndex(options) {
1387
951
  if (options.live === false || options.json)
1388
952
  return undefined;
@@ -1448,47 +1012,6 @@ function printSessionOverview(pool, hiddenCount, liveIndex, opts) {
1448
1012
  if (opts.hiddenUnmanaged)
1449
1013
  console.log(chalk.gray(formatUnmanagedHiddenFooter(opts.hiddenUnmanaged)));
1450
1014
  }
1451
- export function printSessionTable(sessions, hiddenCount = 0, tree = false, liveIndex) {
1452
- if (tree) {
1453
- const byDir = new Map();
1454
- for (const s of sessions) {
1455
- const key = s.cwd || s.project || 'unknown';
1456
- (byDir.get(key) ?? byDir.set(key, []).get(key)).push(s);
1457
- }
1458
- const keys = [...byDir.keys()].sort((a, b) => {
1459
- const d = byDir.get(b).length - byDir.get(a).length;
1460
- return d !== 0 ? d : a.localeCompare(b);
1461
- });
1462
- let first = true;
1463
- for (const key of keys) {
1464
- if (!first)
1465
- console.log();
1466
- first = false;
1467
- const group = byDir.get(key);
1468
- const cwd = group.find((s) => s.cwd && !s._remote)?.cwd;
1469
- const header = cwd ? linkPath(cwd, shortCwd(key)) : shortCwd(key);
1470
- console.log(`${chalk.cyan.bold(header)} ${chalk.gray(`(${group.length})`)}`);
1471
- for (const s of group)
1472
- console.log(treeSessionRow(s, liveIndex?.get(s.id)));
1473
- }
1474
- const dirWord = keys.length === 1 ? 'directory' : 'directories';
1475
- console.log(chalk.gray(`\n${sessions.length} session${sessions.length === 1 ? '' : 's'} across ${keys.length} ${dirWord}.`));
1476
- if (hiddenCount > 0)
1477
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1478
- return;
1479
- }
1480
- const showTicket = sessions.some((s) => ticketLabel(s) !== '');
1481
- const cols = pickerColumnsFor(sessions);
1482
- const bookmarks = listBookmarks();
1483
- for (const session of sessions) {
1484
- console.log(flatSessionRow(session, liveIndex?.get(session.id), showTicket, cols, bookmarks.has(session.id)));
1485
- }
1486
- const countLine = `${sessions.length} session${sessions.length === 1 ? '' : 's'}.`;
1487
- console.log(chalk.gray(`\n${countLine}`));
1488
- if (hiddenCount > 0) {
1489
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1490
- }
1491
- }
1492
1015
  const TEAM_MODE_W = 5;
1493
1016
  const TEAM_HANDLE_W = 16;
1494
1017
  function teamMemberRow(session, live) {
@@ -1575,354 +1098,6 @@ function printTeamsView(pool, liveIndex, hiddenUnmanaged = 0) {
1575
1098
  if (hiddenUnmanaged > 0)
1576
1099
  console.log(chalk.gray(formatUnmanagedHiddenFooter(hiddenUnmanaged)));
1577
1100
  }
1578
- function renderTopicCell(label, topic, query, visibleWidth, paddedWidth) {
1579
- const lbl = (label ?? '').trim();
1580
- const tpc = (topic ?? '').trim();
1581
- const sep = ' · ';
1582
- const raw = lbl && tpc ? `${lbl}${sep}${tpc}` : (lbl || tpc);
1583
- const visible = truncateToWidth(raw, visibleWidth);
1584
- const padding = ' '.repeat(Math.max(0, paddedWidth - stringWidth(visible)));
1585
- const labelEnd = lbl ? Math.min(lbl.length, visible.length) : 0;
1586
- let matchStart = -1, matchEnd = -1;
1587
- const q = query.trim().toLowerCase();
1588
- if (q) {
1589
- const lower = visible.toLowerCase();
1590
- for (const term of q.split(/\s+/).filter(Boolean)) {
1591
- const idx = lower.indexOf(term);
1592
- if (idx !== -1) {
1593
- matchStart = idx;
1594
- matchEnd = idx + term.length;
1595
- break;
1596
- }
1597
- }
1598
- }
1599
- const cuts = new Set([0, labelEnd, visible.length]);
1600
- if (matchStart >= 0) {
1601
- cuts.add(matchStart);
1602
- cuts.add(matchEnd);
1603
- }
1604
- const boundaries = [...cuts].sort((a, b) => a - b);
1605
- let out = '';
1606
- for (let i = 0; i < boundaries.length - 1; i++) {
1607
- const s = boundaries[i], e = boundaries[i + 1];
1608
- if (s >= e)
1609
- continue;
1610
- const text = visible.slice(s, e);
1611
- const isLabel = s < labelEnd;
1612
- const isMatch = matchStart >= 0 && s >= matchStart && e <= matchEnd;
1613
- out += (isMatch || isLabel) ? chalk.bold.white(text) : chalk.white(text);
1614
- }
1615
- return out + padding;
1616
- }
1617
- const PICKER_MACHINE_W = 11;
1618
- const PICKER_MACHINE_MIN = 8;
1619
- const PICKER_MACHINE_MAX = 18;
1620
- const PICKER_MODEL_MIN = 6;
1621
- const PICKER_MODEL_MAX = 13;
1622
- function machineColumnWidth(machines, label) {
1623
- const widest = machines.reduce((w, m) => Math.max(w, stringWidth(label(m))), 0);
1624
- return Math.min(PICKER_MACHINE_MAX, Math.max(PICKER_MACHINE_MIN, widest + 1));
1625
- }
1626
- function modelColumnWidth(sessions) {
1627
- const widest = sessions.reduce((width, session) => (Math.max(width, session.model ? stringWidth(modelLabel(session.model)) : 0)), 0);
1628
- return Math.min(PICKER_MODEL_MAX, Math.max(PICKER_MODEL_MIN, widest + 1));
1629
- }
1630
- export function machineLabeler(machines) {
1631
- const uniq = [...new Set(machines.filter(Boolean))];
1632
- if (uniq.length < 2)
1633
- return (m) => m;
1634
- const parts = uniq.map((m) => m.split('-'));
1635
- const min = Math.min(...parts.map((p) => p.length));
1636
- let shared = 0;
1637
- while (shared < min - 1 && parts.every((p) => p[shared] === parts[0][shared]))
1638
- shared++;
1639
- if (shared === 0)
1640
- return (m) => m;
1641
- return (m) => {
1642
- const p = m.split('-');
1643
- return p.length > shared ? p.slice(shared).join('-') : m;
1644
- };
1645
- }
1646
- export function pickerColumnsFor(sessions) {
1647
- const machines = sessions.map((s) => s.machine).filter((m) => !!m);
1648
- const distinct = [...new Set(machines)];
1649
- const machineLabel = machineLabeler(machines);
1650
- return {
1651
- showMachine: distinct.length > 1,
1652
- machineLabel,
1653
- machineWidth: machineColumnWidth(distinct, machineLabel),
1654
- showModel: sessions.some((s) => !!s.model),
1655
- modelWidth: modelColumnWidth(sessions),
1656
- showTicket: sessions.some((s) => ticketLabel(s) !== ''),
1657
- showBookmark: (() => {
1658
- const bookmarks = listBookmarks();
1659
- return bookmarks.size > 0 && sessions.some((s) => bookmarks.has(s.id));
1660
- })(),
1661
- };
1662
- }
1663
- const PICKER_HOST_W = 14;
1664
- export function liveHostLabel(a) {
1665
- if (!a?.host)
1666
- return '';
1667
- const viewer = a.viewingIn?.app;
1668
- return viewer && viewer !== a.host ? `${a.host}→${viewer}` : a.host;
1669
- }
1670
- export function formatPickerLabel(s, query, cols = {}, ssh, host = '', bookmarked = false, live) {
1671
- const shown = sessionDisplayAgent(s);
1672
- const agentColor = colorAgent(shown);
1673
- const age = sessionAgeParts(s.timestamp, s.lastActivity);
1674
- const project = s.project || '-';
1675
- const sshPlain = ssh ? (ssh.device ? `ssh←${ssh.device} ` : 'ssh ') : '';
1676
- const sshSeg = sshPlain ? chalk.red(sshPlain) : '';
1677
- const sshW = sshPlain ? stringWidth(sshPlain) : 0;
1678
- const team = teamBadge(s);
1679
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1680
- const tag = originTag(s) || teamTag(s);
1681
- const label = s.label;
1682
- const topic = tag ? `${tag}${s.topic ?? ''}` : s.topic;
1683
- const versionStr = s.version || '-';
1684
- const wt = s.worktreeSlug ? chalk.magenta(`wt:${s.worktreeSlug}`) : '';
1685
- const machineW = cols.machineWidth ?? PICKER_MACHINE_W;
1686
- const machineCell = cols.showMachine
1687
- ? chalk.gray(padRight(truncate((cols.machineLabel?.(s.machine ?? '') ?? s.machine ?? '') || '-', machineW - 1), machineW))
1688
- : '';
1689
- const TICKET_W = 10;
1690
- const ticketCell = cols.showTicket
1691
- ? chalk.blue(padRight(truncate(ticketLabel(s) || '-', TICKET_W), TICKET_W + 1))
1692
- : '';
1693
- const hostCell = cols.showHost
1694
- ? chalk.gray(padRight(truncate(host || '-', PICKER_HOST_W - 1), PICKER_HOST_W))
1695
- : '';
1696
- const gutter = cols.gutter ?? 2;
1697
- const machineColW = cols.showMachine ? machineW : 0;
1698
- const ticketW = cols.showTicket ? TICKET_W + 1 : 0;
1699
- const hostW = cols.showHost ? PICKER_HOST_W : 0;
1700
- const wtW = wt ? stringWidth(wt) + 1 : 0;
1701
- const bookmarkW = cols.showBookmark ? 2 : 0;
1702
- const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
1703
- const status = cols.showStatus ? liveStatusCell(live) : { cell: '', width: 0 };
1704
- const statusW = cols.showStatus ? LIVE_STATUS_W : 0;
1705
- const statusCell = cols.showStatus ? (status.cell || ' '.repeat(LIVE_STATUS_W)) : '';
1706
- const baseTopicW = terminalWidth() - gutter - bookmarkW - statusW - (10 + 9 + 8 + 16) - machineColW - hostW - ticketW - wtW - sshW - team.width - stringWidth(age.last) - 1;
1707
- const when = timeCell(age, baseTopicW);
1708
- const topicW = Math.max(MIN_TOPIC_W, baseTopicW - when.extraW);
1709
- return (bookmarkCell +
1710
- chalk.white(padRight(truncate(s.shortId, 9), 10)) +
1711
- agentColor(padRight(truncate(shown, 8), 9)) +
1712
- chalk.yellow(padRight(truncate(versionStr, 7), 8)) +
1713
- machineCell +
1714
- hostCell +
1715
- chalk.cyan(padRight(truncate(project, 14), 16)) +
1716
- statusCell +
1717
- sshSeg +
1718
- teamSeg +
1719
- renderTopicCell(label, topic, query, topicW, topicW) +
1720
- ticketCell +
1721
- (wt ? wt + ' ' : '') +
1722
- when.text);
1723
- }
1724
- const PICKER_TIPS = [
1725
- 'Tip: narrow with -a/--agent (e.g. -a codex), or --project <name> for another folder.',
1726
- "Tip: --all searches every directory; -D/--device <machine> folds in another box's sessions.",
1727
- 'Tip: just type to fuzzy-search prompts and responses; press space to preview a session.',
1728
- 'Tip: --since 2d / --until <date> bound the time window; pass a session id to open it directly.',
1729
- ];
1730
- export function formatPickerTip(sessions) {
1731
- return chalk.gray(PICKER_TIPS[sessions.length % PICKER_TIPS.length]);
1732
- }
1733
- export async function pickSessionInteractive(sessions, message = 'Search sessions:', initialSearch, hiddenCount = 0, enterHint, scope) {
1734
- let linesAbovePrompt = 0;
1735
- if (hiddenCount > 0) {
1736
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1737
- linesAbovePrompt += 1;
1738
- }
1739
- const cols = pickerColumnsFor(sessions);
1740
- try {
1741
- return await sessionPicker({
1742
- message,
1743
- subtitle: formatPickerTip(sessions),
1744
- sessions,
1745
- filter: (query) => {
1746
- if (!query.trim())
1747
- return sessions;
1748
- return filterSessionsByQuery(sessions, query, scope);
1749
- },
1750
- labelFor: (s, query) => formatPickerLabel(s, query, cols),
1751
- pageSize: PICKER_RECENT_COUNT,
1752
- initialSearch,
1753
- enterHint,
1754
- linesAbovePrompt,
1755
- });
1756
- }
1757
- catch (err) {
1758
- if (isPromptCancelled(err))
1759
- return null;
1760
- throw err;
1761
- }
1762
- }
1763
- function warnNoPeerTarget(machine, session) {
1764
- console.log(chalk.yellow(`Session ${session.shortId} lives on ${machine}, which isn't a reachable device right now.`));
1765
- console.log(chalk.gray(`Register/wake it (ag devices), or run there: agents ssh ${machine}`));
1766
- }
1767
- export const LIVE_ROW_PREFIX = 'live:';
1768
- function isIdlessLiveRow(s) {
1769
- return s.id.startsWith(LIVE_ROW_PREFIX);
1770
- }
1771
- export async function handlePickedSession(picked) {
1772
- if (isIdlessLiveRow(picked.session)) {
1773
- const where = picked.session.machine ? ` on ${picked.session.machine}` : '';
1774
- console.log(chalk.yellow(`This session hasn't reported a session id yet — nothing to open${where}.`));
1775
- console.log(chalk.gray(`Watch for it with: agents sessions --active${picked.session.machine ? ` --device ${picked.session.machine}` : ''}`));
1776
- return;
1777
- }
1778
- if (picked.action === 'view') {
1779
- const readFrom = transcriptOnPeerOf(picked.session);
1780
- if (readFrom) {
1781
- const rc = await runOnPeer(['sessions', picked.session.shortId, '--markdown'], readFrom);
1782
- if (rc === 'no-target')
1783
- warnNoPeerTarget(readFrom, picked.session);
1784
- return;
1785
- }
1786
- await renderSession(picked.session, 'summary', {});
1787
- return;
1788
- }
1789
- if (await resumeOnOwnerIfRemote(picked.session))
1790
- return;
1791
- await resumeSessionInPlace(picked.session);
1792
- }
1793
- async function resumeOnOwnerIfRemote(session) {
1794
- const owner = sessionOwnerDevice(session);
1795
- if (!owner)
1796
- return false;
1797
- console.log(chalk.gray(`Resuming ${session.shortId} on ${owner} over SSH...`));
1798
- const rc = await runOnPeer(['sessions', 'resume', session.id], owner, {
1799
- tty: true,
1800
- env: { [RESUME_PINNED_ENV]: '1' },
1801
- sessionId: session.id,
1802
- });
1803
- if (rc === 'no-target')
1804
- warnNoPeerTarget(owner, session);
1805
- return true;
1806
- }
1807
- export async function resumeSessionInPlace(session) {
1808
- const owner = sessionOwnerDevice(session);
1809
- if (owner) {
1810
- console.error(chalk.red(`Session ${session.shortId} belongs to ${owner} — it cannot resume on this machine.`));
1811
- console.error(chalk.gray(` Resume it there: agents sessions resume ${session.id}`));
1812
- process.exitCode = 1;
1813
- return;
1814
- }
1815
- const cwd = session.cwd && fs.existsSync(session.cwd)
1816
- ? session.cwd
1817
- : process.cwd();
1818
- const resume = buildSessionRecoveryCommand(session);
1819
- console.log(chalk.gray(`Resuming: ${resume.join(' ')} (cwd: ${cwd})`));
1820
- await spawnResumeCommand(resume, cwd);
1821
- }
1822
- export function buildSessionRecoveryCommand(session, portable = false) {
1823
- const args = sessionRecoveryRunArgs(session);
1824
- if (portable)
1825
- return ['agents', ...args];
1826
- const invocation = getAgentsInvocation(args);
1827
- return [invocation.command, ...invocation.args];
1828
- }
1829
- export function resumeSpawnInvocation(cmd, platform = process.platform) {
1830
- const shell = needsWindowsShell(cmd[0], platform);
1831
- if (shell) {
1832
- return {
1833
- command: composeWin32CommandLine(cmd[0], cmd.slice(1)),
1834
- args: [],
1835
- shell: true,
1836
- };
1837
- }
1838
- return { command: cmd[0], args: cmd.slice(1), shell: false };
1839
- }
1840
- function spawnResumeCommand(cmd, cwd) {
1841
- return new Promise((resolve) => {
1842
- let child;
1843
- try {
1844
- const { command, args, shell } = resumeSpawnInvocation(cmd);
1845
- child = spawn(command, args, {
1846
- cwd,
1847
- stdio: 'inherit',
1848
- shell,
1849
- });
1850
- }
1851
- catch (err) {
1852
- console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
1853
- resolve();
1854
- return;
1855
- }
1856
- child.on('error', (err) => {
1857
- console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
1858
- if (err.code === 'ENOENT') {
1859
- console.error(chalk.gray(`Make sure '${cmd[0]}' is on your PATH.`));
1860
- }
1861
- resolve();
1862
- });
1863
- child.on('close', () => resolve());
1864
- });
1865
- }
1866
- function resumeArgv(agent, id, launcher) {
1867
- switch (agent) {
1868
- case 'claude': return [launcher, '--resume', id];
1869
- case 'codex': return [launcher, 'resume', id];
1870
- case 'opencode': return [launcher, '--session', id];
1871
- case 'muse': return [launcher, 'resume', id];
1872
- default: return null;
1873
- }
1874
- }
1875
- function versionedAliasIfPresent(agent, version) {
1876
- const cli = AGENTS[agent]?.cliCommand ?? agent;
1877
- const base = path.join(getShimsDir(), `${cli}@${version}`);
1878
- if (process.platform === 'win32' && fs.existsSync(`${base}.cmd`))
1879
- return `${base}.cmd`;
1880
- if (fs.existsSync(base))
1881
- return base;
1882
- return null;
1883
- }
1884
- export function buildResumeCommand(session) {
1885
- if (!sessionAgentSupportsResume(session.agent))
1886
- return null;
1887
- switch (session.agent) {
1888
- case 'opencode':
1889
- return resumeArgv('opencode', session.id, 'opencode');
1890
- case 'claude':
1891
- case 'codex':
1892
- case 'muse': {
1893
- const cli = AGENTS[session.agent]?.cliCommand ?? session.agent;
1894
- if (session.version) {
1895
- const alias = versionedAliasIfPresent(session.agent, session.version);
1896
- return resumeArgv(session.agent, session.id, alias ?? `${cli}@${session.version}`);
1897
- }
1898
- return resumeArgv(session.agent, session.id, cli);
1899
- }
1900
- default:
1901
- return null;
1902
- }
1903
- }
1904
- export function resolveSessionAgentName(name) {
1905
- const normalized = name.toLowerCase();
1906
- if (SESSION_AGENTS.includes(normalized)) {
1907
- return normalized;
1908
- }
1909
- const resolved = resolveAgentName(normalized);
1910
- if (resolved && SESSION_AGENTS.includes(resolved)) {
1911
- return resolved;
1912
- }
1913
- return fuzzyMatch(normalized, SESSION_AGENTS, FUZZY_PRESETS.agents);
1914
- }
1915
- export function parseAgentFilter(agentName) {
1916
- if (!agentName)
1917
- return {};
1918
- const [name, version] = agentName.split('@', 2);
1919
- const agent = resolveSessionAgentName(name);
1920
- if (!agent) {
1921
- console.error(chalk.red(`Unknown agent: ${name}. Use: ${SESSION_AGENTS.join(', ')}`));
1922
- process.exit(1);
1923
- }
1924
- return { agent, version };
1925
- }
1926
1101
  function formatSearchMessage(options) {
1927
1102
  const filters = [];
1928
1103
  if (options.agent)
@@ -1933,18 +1108,6 @@ function formatSearchMessage(options) {
1933
1108
  return 'Search sessions:';
1934
1109
  return `Search sessions (${filters.join(', ')}):`;
1935
1110
  }
1936
- export function resolveSessionQuery(pool, query, options = {}) {
1937
- const normalized = query.trim();
1938
- const completeId = isCompleteSessionId(normalized);
1939
- const byIdMatches = resolveSessionById(pool, normalized);
1940
- if (byIdMatches.length > 0)
1941
- return { matches: byIdMatches, byId: true, completeId };
1942
- if (looksLikeSessionId(normalized)) {
1943
- const matches = options.indexFallback === false ? [] : findSessionsById(normalized);
1944
- return { matches, byId: true, completeId };
1945
- }
1946
- return { matches: filterSessionsByQuery(pool, normalized, options.scope), byId: false, completeId };
1947
- }
1948
1111
  function ambiguityHint(byId, completeId) {
1949
1112
  if (completeId)
1950
1113
  return 'That is already a complete id — these rows share it as a prefix.';
@@ -1952,9 +1115,6 @@ function ambiguityHint(byId, completeId) {
1952
1115
  ? 'Pass a longer ID to narrow it down.'
1953
1116
  : 'That matched on text, not an id. Pass a session id, or narrow the search.';
1954
1117
  }
1955
- function notFoundByIdMessage(query) {
1956
- return [chalk.red(`No session with id ${query.trim()} on this machine.`)];
1957
- }
1958
1118
  export function fleetNotFoundMessage(query, deviceCount, unreachable) {
1959
1119
  const id = query.trim();
1960
1120
  if (deviceCount === 0) {
@@ -1970,142 +1130,6 @@ export function fleetNotFoundMessage(query, deviceCount, unreachable) {
1970
1130
  }
1971
1131
  return lines;
1972
1132
  }
1973
- export function filterSessionsByQuery(sessions, query, scope) {
1974
- const trimmed = query?.trim().toLowerCase() || '';
1975
- if (!trimmed)
1976
- return sessions;
1977
- const installedAgentVersion = parseInstalledAgentVersionQuery(trimmed);
1978
- if (installedAgentVersion) {
1979
- const { agent, version } = parseAgentFilter(installedAgentVersion);
1980
- return sessions.filter((session) => session.agent === agent && session.version === version);
1981
- }
1982
- const terms = trimmed.split(/\s+/).filter(Boolean);
1983
- const contentIndex = scopedContentIndex(sessions, trimmed, scope);
1984
- const EXACT_LABEL_SCORE = 1_000_000;
1985
- const exactLabelHits = [...contentIndex.values()].filter(s => (s._bm25Score ?? 0) >= EXACT_LABEL_SCORE);
1986
- if (exactLabelHits.length > 0) {
1987
- return exactLabelHits.sort((a, b) => (b._bm25Score ?? 0) - (a._bm25Score ?? 0));
1988
- }
1989
- const poolById = new Map(sessions.map(s => [s.id, s]));
1990
- for (const [id, hit] of contentIndex) {
1991
- if (!poolById.has(id))
1992
- poolById.set(id, hit);
1993
- }
1994
- return [...poolById.values()]
1995
- .map(session => ({ session, score: scoreSessionQuery(session, terms) }))
1996
- .filter(entry => {
1997
- if (entry.score > 0)
1998
- return true;
1999
- const contentMatch = contentIndex.get(entry.session.id);
2000
- if (contentMatch && contentMatch._matchedTerms && contentMatch._matchedTerms.length > 0) {
2001
- return true;
2002
- }
2003
- return false;
2004
- })
2005
- .sort((a, b) => {
2006
- if (b.score !== a.score)
2007
- return b.score - a.score;
2008
- const cmA = contentIndex.get(a.session.id);
2009
- const cmB = contentIndex.get(b.session.id);
2010
- const bmA = cmA?._bm25Score ?? 0;
2011
- const bmB = cmB?._bm25Score ?? 0;
2012
- if (bmB !== bmA)
2013
- return bmB - bmA;
2014
- return new Date(b.session.timestamp).getTime() - new Date(a.session.timestamp).getTime();
2015
- })
2016
- .map(entry => {
2017
- const cm = contentIndex.get(entry.session.id);
2018
- if (cm && cm._matchedTerms) {
2019
- return { ...cm };
2020
- }
2021
- return entry.session;
2022
- });
2023
- }
2024
- function scoreSessionQuery(session, terms) {
2025
- let score = 0;
2026
- for (const term of terms) {
2027
- const exactId = session.id.toLowerCase() === term || session.shortId.toLowerCase() === term;
2028
- const prefixId = session.id.toLowerCase().startsWith(term) || session.shortId.toLowerCase().startsWith(term);
2029
- const topic = session.topic?.toLowerCase() || '';
2030
- const project = session.project?.toLowerCase() || '';
2031
- const account = session.account?.toLowerCase() || '';
2032
- const cwd = session.cwd?.toLowerCase() || '';
2033
- const agent = session.agent.toLowerCase();
2034
- const version = session.version?.toLowerCase() || '';
2035
- let termScore = 0;
2036
- if (exactId)
2037
- termScore = 1000;
2038
- else if (prefixId)
2039
- termScore = 900;
2040
- else if (topic.startsWith(term))
2041
- termScore = 700;
2042
- else if (project.startsWith(term))
2043
- termScore = 600;
2044
- else if (account.startsWith(term))
2045
- termScore = 550;
2046
- else if (agent.startsWith(term) || version.startsWith(term))
2047
- termScore = 500;
2048
- else if (topic.includes(term))
2049
- termScore = 400;
2050
- else if (project.includes(term))
2051
- termScore = 300;
2052
- else if (account.includes(term))
2053
- termScore = 250;
2054
- else if (cwd.includes(term))
2055
- termScore = 200;
2056
- else if (version.includes(term) || agent.includes(term))
2057
- termScore = 150;
2058
- else
2059
- return 0;
2060
- score += termScore;
2061
- }
2062
- return score;
2063
- }
2064
- export function applyScopeFilters(sessions, scope) {
2065
- let filtered = sessions;
2066
- if (scope.project) {
2067
- const projectQuery = scope.project.toLowerCase();
2068
- filtered = filtered.filter((s) => {
2069
- const project = (s.project || '').toLowerCase();
2070
- const cwd = (s.cwd || '').toLowerCase();
2071
- return project.includes(projectQuery) || cwd.includes(projectQuery);
2072
- });
2073
- }
2074
- if (scope.agent) {
2075
- const [wantAgent, rawVersion] = scope.agent.split('@');
2076
- const resolvedAgent = resolveAgentName(wantAgent);
2077
- const wantVersion = resolvedAgent ? resolveVersionAliasLoose(resolvedAgent, rawVersion) : rawVersion;
2078
- filtered = filtered.filter((s) => {
2079
- if (s.agent !== wantAgent)
2080
- return false;
2081
- if (wantVersion && s.version !== wantVersion)
2082
- return false;
2083
- return true;
2084
- });
2085
- }
2086
- if (scope.routine) {
2087
- filtered = filtered.filter((session) => session.origin === 'routine');
2088
- if (typeof scope.routine === 'string') {
2089
- const names = [...new Set(filtered.map((session) => session.routineName).filter((name) => !!name))];
2090
- const selected = resolveRoutineName(scope.routine, names);
2091
- filtered = selected
2092
- ? filtered.filter((session) => session.routineName === selected)
2093
- : [];
2094
- }
2095
- }
2096
- return filtered;
2097
- }
2098
- function scopedContentIndex(sessions, query, scope) {
2099
- const hits = searchContentIndex(sessions, query);
2100
- if (!scope || (!scope.agent && !scope.project && !scope.routine))
2101
- return hits;
2102
- const kept = new Map();
2103
- for (const [id, session] of hits) {
2104
- if (applyScopeFilters([session], scope).length > 0)
2105
- kept.set(id, session);
2106
- }
2107
- return kept;
2108
- }
2109
1133
  export function artifactLookupScope(agent, project, routine) {
2110
1134
  return { agent, project, routine };
2111
1135
  }
@@ -2305,181 +1329,6 @@ function modeFlag(mode) {
2305
1329
  return '--json';
2306
1330
  return undefined;
2307
1331
  }
2308
- const FULL_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2309
- const SHORT_SESSION_ID_RE = /^[0-9a-f]{8}$/i;
2310
- export function isDefinitiveMatch(session, selector) {
2311
- const trimmed = selector.trim();
2312
- if (FULL_SESSION_ID_RE.test(trimmed)) {
2313
- return session.id.toLowerCase() === trimmed.toLowerCase();
2314
- }
2315
- const shortId = shortIdFromName(trimmed) ?? (SHORT_SESSION_ID_RE.test(trimmed) ? trimmed : undefined);
2316
- return !!shortId && session.shortId.toLowerCase() === shortId.toLowerCase();
2317
- }
2318
- export function selectorAllowsEarlyExit(selector) {
2319
- const trimmed = selector.trim();
2320
- return FULL_SESSION_ID_RE.test(trimmed) || isAgentTmuxAlias(trimmed) || SHORT_SESSION_ID_RE.test(trimmed);
2321
- }
2322
- export function fleetCandidatesByQuery(rows, query, trustResolvedRows = false) {
2323
- const matched = !trustResolvedRows && looksLikeSessionId(query)
2324
- ? resolveSessionQuery(rows, query, { indexFallback: false }).matches
2325
- : rows;
2326
- const byId = new Map();
2327
- for (const session of matched) {
2328
- const machine = session.machine;
2329
- if (!machine)
2330
- continue;
2331
- const logicalId = session.id.toLowerCase();
2332
- let byMachine = byId.get(logicalId);
2333
- if (!byMachine) {
2334
- byMachine = new Map();
2335
- byId.set(logicalId, byMachine);
2336
- }
2337
- if (!byMachine.has(machine))
2338
- byMachine.set(machine, session);
2339
- }
2340
- return Array.from(byId.values()).map(byMachine => {
2341
- const hits = Array.from(byMachine.entries()).map(([machine, session]) => ({ machine, session }));
2342
- return { id: hits[0].session.id, hits };
2343
- });
2344
- }
2345
- function resolveIndexedMetadataRows(indexed, selector, scope) {
2346
- const alias = resolveSessionAlias(selector);
2347
- if (alias.kind === 'resolved') {
2348
- return resolveSessionQuery(indexed, alias.sessionId, { indexFallback: false, scope }).matches;
2349
- }
2350
- if (alias.kind === 'ambiguous') {
2351
- const ids = new Set(alias.sessionIds.map(id => id.toLowerCase()));
2352
- return indexed.filter(session => ids.has(session.id.toLowerCase()));
2353
- }
2354
- return resolveSessionQuery(indexed, selector, { indexFallback: false, scope }).matches;
2355
- }
2356
- function indexedRowsForSelector(selector, scope) {
2357
- const indexed = looksLikeSessionId(selector)
2358
- ? findSessionsById(selector)
2359
- : querySessions();
2360
- return applyScopeFilters(indexed, scope);
2361
- }
2362
- export function metadataResolveForwardedArgs(selector, scope) {
2363
- const args = ['sessions', '--resolve-safe-v1', selector, '--json', '--all', '--local'];
2364
- if (scope.agent)
2365
- args.push('--agent', scope.agent);
2366
- if (scope.project)
2367
- args.push('--project', scope.project);
2368
- return args;
2369
- }
2370
- const SHORT_SESSION_ID_WIDTH = 8;
2371
- export function isUniqueEnoughSelector(selector) {
2372
- const trimmed = selector.trim();
2373
- if (isCompleteSessionId(trimmed))
2374
- return true;
2375
- return /^[0-9a-f-]+$/i.test(trimmed)
2376
- && trimmed.replace(/-/g, '').length >= SHORT_SESSION_ID_WIDTH;
2377
- }
2378
- export function metadataResolveOutcome(localMatches, remote, selector) {
2379
- const candidates = fleetCandidatesByQuery([...localMatches, ...remote.sessions], selector, true);
2380
- if (isUniqueEnoughSelector(selector) && candidates.length === 1) {
2381
- return { kind: 'resolved', session: candidates[0].hits[0].session };
2382
- }
2383
- if (remote.unreachable.length > 0)
2384
- return { kind: 'partial', failedPeers: remote.unreachable };
2385
- if (candidates.length === 0)
2386
- return { kind: 'not-found' };
2387
- if (candidates.length > 1)
2388
- return { kind: 'ambiguous', candidates };
2389
- return { kind: 'resolved', session: candidates[0].hits[0].session };
2390
- }
2391
- export function isLocallyDefinitiveMatch(session, self) {
2392
- if (session.filePath)
2393
- return true;
2394
- return !!session.machine && session.machine !== self;
2395
- }
2396
- export function preferOwnerAttribution(localMatches, remoteSessions, self) {
2397
- if (remoteSessions.length === 0)
2398
- return localMatches;
2399
- const answeredByPeer = new Set(remoteSessions.map(session => session.id.toLowerCase()));
2400
- return localMatches.filter(session => isLocallyDefinitiveMatch(session, self) || !answeredByPeer.has(session.id.toLowerCase()));
2401
- }
2402
- export async function computeLocalMetadataMatches(selector, scope, deps = {}) {
2403
- const localMachine = machineId();
2404
- const includeLocal = !scope.hosts?.length || shouldIncludeLocal(scope.hosts, localMachine);
2405
- if (!includeLocal)
2406
- return [];
2407
- let indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
2408
- if (!looksLikeSessionId(selector)) {
2409
- return indexed.map(session => ({ ...session, machine: session.machine || localMachine }));
2410
- }
2411
- const { hydrateSessionTranscript, findLocalSessionTranscripts } = await import('../lib/session/discover.js');
2412
- if (indexed.length === 0) {
2413
- const disk = await findLocalSessionTranscripts(selector, scope.agent);
2414
- const live = disk.length ? [] : await liveMetadataMatches(selector, scope, localMachine, deps);
2415
- if (disk.length > 0)
2416
- indexed = resolveIndexedMetadataRows(disk, selector, scope);
2417
- else if (live.length > 0)
2418
- indexed = live;
2419
- else if (scope.agent !== 'claude' && scope.agent !== 'codex') {
2420
- const { scanSessionsIncremental, waitForScanToSettle } = await import('../lib/session/discover.js');
2421
- const { claimed } = await scanSessionsIncremental({ agent: scope.agent });
2422
- if (!claimed) {
2423
- if (!await waitForScanToSettle())
2424
- throw new Error('Session lookup is incomplete: another index scan is still running. Retry when it finishes.');
2425
- const retry = await scanSessionsIncremental({ agent: scope.agent });
2426
- if (!retry.claimed)
2427
- throw new Error('Session lookup is incomplete: the session index is busy. Retry when the scan finishes.');
2428
- }
2429
- indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
2430
- }
2431
- }
2432
- const hydrated = [];
2433
- for (const session of indexed) {
2434
- hydrated.push(await hydrateSessionTranscript({ ...session, machine: session.machine || localMachine }));
2435
- }
2436
- return hydrated;
2437
- }
2438
- export async function liveMetadataMatches(selector, scope, self, deps = {}) {
2439
- const load = deps.loadActive ?? loadLocalActiveSessions;
2440
- const loadFleet = deps.loadFleetActive ?? (() => readActiveSessionsCache('fleet')?.sessions ?? []);
2441
- let fleetExecMachine;
2442
- try {
2443
- fleetExecMachine = fleetExecutionMachineById(loadFleet());
2444
- }
2445
- catch {
2446
- fleetExecMachine = new Map();
2447
- }
2448
- const match = (metas) => resolveIndexedMetadataRows(applyScopeFilters(reconcileLiveMetaMachine(metas, fleetExecMachine, self), scope), selector, scope);
2449
- try {
2450
- const cached = liveSessionMetas((await load()).sessions, self, Date.now());
2451
- const hit = match(cached);
2452
- if (hit.length > 0)
2453
- return hit;
2454
- const fresh = liveSessionMetas((await load({ forceRefresh: true })).sessions, self, Date.now());
2455
- return match(fresh);
2456
- }
2457
- catch {
2458
- return [];
2459
- }
2460
- }
2461
- export async function resolveSessionMetadataValue(selector, scope = {}, deps = { gatherRemoteList }) {
2462
- const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
2463
- const localMachine = machineId();
2464
- if (FULL_SESSION_ID_RE.test(selector)) {
2465
- const localOutcome = metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
2466
- if (localOutcome.kind === 'resolved' && isLocallyDefinitiveMatch(localOutcome.session, localMachine)) {
2467
- return localOutcome;
2468
- }
2469
- }
2470
- if (scope.local === true)
2471
- return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
2472
- try {
2473
- const forwarded = metadataResolveForwardedArgs(selector, scope);
2474
- const remote = await deps.gatherRemoteList(forwarded, scope.hosts, selectorAllowsEarlyExit(selector)
2475
- ? { isDefinitive: (session) => isDefinitiveMatch(session, selector) }
2476
- : undefined);
2477
- return metadataResolveOutcome(preferOwnerAttribution(localMatches, remote.sessions, localMachine), remote, selector);
2478
- }
2479
- catch (error) {
2480
- return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [error?.message ?? 'fleet fan-out'] }, selector);
2481
- }
2482
- }
2483
1332
  export async function resolveSessionMetadata(selector, scope, deps = { gatherRemoteList }) {
2484
1333
  const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
2485
1334
  if (process.env[NO_FANOUT_ENV] === '1') {
@@ -2715,52 +1564,7 @@ export function registerSessionsCommands(program) {
2715
1564
  sessionsCmd.action(async (query, options, command) => {
2716
1565
  await sessionsAction(query, options, command.getOptionValueSource('limit'));
2717
1566
  });
2718
- const previewCmd = sessionsCmd
2719
- .command('preview')
2720
- .argument('<id>', 'Full session ID or displayed 8-character short ID')
2721
- .description('Show one rich session card without rendering the full transcript')
2722
- .option('-a, --agent <agent>', 'Narrow the ID to one agent type/version')
2723
- .option('-p, --project <name>', 'Narrow the ID to one project')
2724
- .option('--local', 'Only this machine; do not resolve the ID across the fleet')
2725
- .option('-D, --device <target...>', 'Resolve only on the named device(s)')
2726
- .option('--json', 'Output the session preview as JSON')
2727
- .option('--refresh', 'Bypass the durable remote-preview cache and negative backoff for one bounded fetch (full ID + single --device only)')
2728
- .option('--revision <cursor>', 'Opaque caller-owned activity cursor (any stable value YOU track, e.g. your own feed\'s lastActivityMs) -- passing the SAME value as your last call confirms nothing changed and serves the cache with zero SSH indefinitely; a different value fetches once, still subject to backoff unless --refresh is also set (full ID + single --device only)');
2729
- setHelpSections(previewCmd, {
2730
- examples: `
2731
- # Preview by the 8-character ID shown in agents sessions
2732
- agents sessions preview 407b8dd5
2733
-
2734
- # A full UUID resolves on the first device that owns it
2735
- agents sessions preview c70ecdea-6210-4039-9845-246a3a7a9942
2736
-
2737
- # Stay on this machine or restrict the authoritative lookup to one peer
2738
- agents sessions preview 407b8dd5 --local
2739
- agents sessions preview 407b8dd5 --device zion
2740
-
2741
- # Full ID + one --device: durable-cached fast path (PHNX-3999); force a fresh fetch
2742
- agents sessions preview c70ecdea-6210-4039-9845-246a3a7a9942 --device zion --json --refresh
2743
- `,
2744
- notes: `
2745
- - Full UUIDs are globally unique and may stop the fleet lookup at the first exact hit.
2746
- - Short IDs wait for every selected device so ambiguity is never hidden.
2747
- - Active status is refreshed through the bounded live-state TTL; transcript-derived details use the durable session index.
2748
- - 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.
2749
- `,
2750
- });
2751
- previewCmd.action(async (id) => {
2752
- const options = previewCmd.optsWithGlobals();
2753
- const hosts = [...(options.host ?? []), ...(options.device ?? [])];
2754
- await renderSessionPreview(id, {
2755
- agent: options.agent,
2756
- project: options.project,
2757
- local: options.local,
2758
- hosts: hosts.length > 0 ? hosts : undefined,
2759
- json: options.json,
2760
- refresh: options.refresh,
2761
- revision: options.revision,
2762
- });
2763
- });
1567
+ registerSessionPreviewCommand(sessionsCmd, 'sessions');
2764
1568
  registerSessionsResumeCommand(sessionsCmd);
2765
1569
  registerSessionsForkCommand(sessionsCmd);
2766
1570
  registerSessionsBookmarkCommand(sessionsCmd);
@@ -2796,10 +1600,6 @@ function formatUnmanagedHiddenFooter(hiddenCount) {
2796
1600
  const noun = hiddenCount === 1 ? 'session' : 'sessions';
2797
1601
  return `(${hiddenCount} ${noun} from your own unmanaged installs hidden — use --unmanaged to show)`;
2798
1602
  }
2799
- function formatTeamHiddenFooter(hiddenCount) {
2800
- const noun = hiddenCount === 1 ? 'team session' : 'team sessions';
2801
- return `(${hiddenCount} ${noun} hidden — use --teams to show, or \`agents teams status\`)`;
2802
- }
2803
1603
  function findClaudeHistoryEntry(idQuery) {
2804
1604
  const historyPath = path.join(os.homedir(), '.claude', 'history.jsonl');
2805
1605
  if (!fs.existsSync(historyPath))