@phnx-labs/agents-cli 1.22.127 → 1.23.1

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 (119) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +15 -16
  3. package/dist/bootstrap.js +4 -3
  4. package/dist/commands/browser.js +4 -19
  5. package/dist/commands/cloud-transcripts.js +1 -2
  6. package/dist/commands/computer.d.ts +2 -6
  7. package/dist/commands/computer.js +12 -18
  8. package/dist/commands/daemon.js +70 -11
  9. package/dist/commands/exec.js +1 -1
  10. package/dist/commands/feed.js +1 -2
  11. package/dist/commands/focus.js +4 -1
  12. package/dist/commands/go.js +3 -2
  13. package/dist/commands/logs.js +3 -7
  14. package/dist/commands/menubar.js +55 -3
  15. package/dist/commands/projects.js +103 -40
  16. package/dist/commands/ps-roster.d.ts +0 -11
  17. package/dist/commands/ps-roster.js +3 -116
  18. package/dist/commands/ps.d.ts +10 -0
  19. package/dist/commands/ps.js +182 -1
  20. package/dist/commands/resume.js +1 -1
  21. package/dist/commands/sessions-browser.d.ts +0 -1
  22. package/dist/commands/sessions-browser.js +6 -23
  23. package/dist/commands/sessions-export.js +1 -1
  24. package/dist/commands/sessions-migrate.js +1 -1
  25. package/dist/commands/sessions-picker.d.ts +6 -32
  26. package/dist/commands/sessions-picker.js +81 -8
  27. package/dist/commands/sessions-render.js +1 -1
  28. package/dist/commands/sessions-resume.js +2 -2
  29. package/dist/commands/sessions-share.js +1 -1
  30. package/dist/commands/sessions-trace.js +1 -1
  31. package/dist/commands/sessions.d.ts +2 -176
  32. package/dist/commands/sessions.js +44 -1577
  33. package/dist/index.js +10 -11
  34. package/dist/lib/browser-client.d.ts +0 -21
  35. package/dist/lib/browser-client.js +1 -44
  36. package/dist/lib/computer/record.d.ts +1 -0
  37. package/dist/lib/computer/record.js +2 -16
  38. package/dist/lib/config-keys.d.ts +2 -2
  39. package/dist/lib/config-keys.js +8 -2
  40. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  41. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  42. package/dist/lib/daemon/attention-notify-service.js +8 -4
  43. package/dist/lib/daemon/daemon.d.ts +5 -1
  44. package/dist/lib/daemon/daemon.js +54 -14
  45. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  46. package/dist/lib/daemon/diagnostics.js +185 -0
  47. package/dist/lib/daemon/runner.js +3 -2
  48. package/dist/lib/daemon/service.d.ts +1 -1
  49. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  50. package/dist/lib/daemon/session-state-service.js +2 -2
  51. package/dist/lib/daemon/supervisor.d.ts +8 -0
  52. package/dist/lib/daemon/supervisor.js +47 -6
  53. package/dist/lib/daemon-services.d.ts +4 -1
  54. package/dist/lib/daemon-services.js +36 -5
  55. package/dist/lib/daemon-ticks.d.ts +3 -1
  56. package/dist/lib/daemon-ticks.js +18 -12
  57. package/dist/lib/device-config.d.ts +1 -1
  58. package/dist/lib/device-config.js +48 -7
  59. package/dist/lib/feed/tool-activity.d.ts +22 -10
  60. package/dist/lib/feed/tool-activity.js +168 -32
  61. package/dist/lib/feed/tools.d.ts +55 -2
  62. package/dist/lib/feed/tools.js +22 -28
  63. package/dist/lib/feed/watch.js +12 -8
  64. package/dist/lib/github/open-prs.d.ts +41 -0
  65. package/dist/lib/github/open-prs.js +157 -0
  66. package/dist/lib/github/project-prs.d.ts +20 -1
  67. package/dist/lib/github/project-prs.js +8 -7
  68. package/dist/lib/helper-versions.js +1 -1
  69. package/dist/lib/menubar/install-menubar.d.ts +23 -7
  70. package/dist/lib/menubar/install-menubar.js +179 -30
  71. package/dist/lib/menubar/resolve-version.d.ts +1 -0
  72. package/dist/lib/menubar/resolve-version.js +4 -2
  73. package/dist/lib/menubar/snapshot.d.ts +2 -0
  74. package/dist/lib/menubar/snapshot.js +2 -0
  75. package/dist/lib/menubar/update-state.d.ts +15 -0
  76. package/dist/lib/menubar/update-state.js +36 -0
  77. package/dist/lib/owner-notify.d.ts +0 -12
  78. package/dist/lib/owner-notify.js +1 -10
  79. package/dist/lib/self-heal/checks/menubar-helper.js +1 -0
  80. package/dist/lib/session/active.js +18 -14
  81. package/dist/lib/session/cloud.d.ts +0 -1
  82. package/dist/lib/session/cloud.js +0 -5
  83. package/dist/lib/session/db.d.ts +0 -64
  84. package/dist/lib/session/db.js +0 -116
  85. package/dist/lib/session/pid-registry.js +9 -6
  86. package/dist/lib/session/presentation.d.ts +107 -1
  87. package/dist/lib/session/presentation.js +543 -4
  88. package/dist/lib/session/remote/remote-list.d.ts +5 -36
  89. package/dist/lib/session/remote/remote-list.js +16 -320
  90. package/dist/lib/session/resume-command.d.ts +9 -0
  91. package/dist/lib/session/resume-command.js +107 -0
  92. package/dist/lib/session/selection.d.ts +102 -0
  93. package/dist/lib/session/selection.js +443 -0
  94. package/dist/lib/session/tool-index.d.ts +0 -62
  95. package/dist/lib/session/tool-index.js +1 -537
  96. package/dist/lib/sessions-client.d.ts +1 -0
  97. package/dist/lib/sessions-client.js +17 -1
  98. package/dist/lib/standalone-tools.js +2 -2
  99. package/dist/lib/testdata/owner-notify-api.d.ts +0 -13
  100. package/dist/lib/testdata/owner-notify-api.js +3 -23
  101. package/package.json +1 -1
  102. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  103. package/dist/commands/browser-sessions-picker.js +0 -136
  104. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  105. package/dist/commands/computer-sessions-picker.js +0 -90
  106. package/dist/commands/sessions-tail.d.ts +0 -13
  107. package/dist/commands/sessions-tail.js +0 -222
  108. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  109. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  110. package/dist/lib/browser/paths.d.ts +0 -9
  111. package/dist/lib/browser/paths.js +0 -31
  112. package/dist/lib/browser/record.d.ts +0 -4
  113. package/dist/lib/browser/record.js +0 -19
  114. package/dist/lib/browser/sessions-list.d.ts +0 -79
  115. package/dist/lib/browser/sessions-list.js +0 -415
  116. package/dist/lib/computer/sessions-list.d.ts +0 -78
  117. package/dist/lib/computer/sessions-list.js +0 -372
  118. package/dist/lib/daemon/owner-device-delivery-service.d.ts +0 -10
  119. package/dist/lib/daemon/owner-device-delivery-service.js +0 -28
@@ -1,60 +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, gatherRemoteToolProgramCounts, gatherRemoteToolSearch, runOnPeer } from '../lib/session/remote-list.js';
23
- import { gatherRemoteAgentsJson } from '../lib/remote-agents-json.js';
19
+ import { gatherRemoteList, runOnPeer, shouldIncludeLocal } from '../lib/session/remote-list.js';
24
20
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
25
- import { discoverSessions, queryIndexedSessions, countSessionsInScope, resolveSessionById, isCompleteSessionId, looksLikeSessionId, searchContentIndex, getSessionRoots, scopeToManaged } from '../lib/session/discover.js';
26
- import { findSessionsById, querySessions, readSessionTimelineAny } from '../lib/session/db.js';
27
- import { foldTimeline, emptyTimelineState, projectTimeline, projectSessionFiles } from '@phnx-labs/sessions-cli/reader';
28
- import { readSessionTail } from '@phnx-labs/sessions-cli/reader';
29
- import { liveSessionMetas, fleetExecutionMachineById, reconcileLiveMetaMachine } from '../lib/session/live-metadata.js';
21
+ import { discoverSessions, countSessionsInScope, resolveSessionById, looksLikeSessionId, getSessionRoots } from '../lib/session/discover.js';
30
22
  import { sessionHeadline } from '../lib/session/title.js';
31
23
  import { filterTeamSessions, shouldShowTeamSessions, safeTeamText, groupSessionsByTeam, NO_TEAM_GROUP_KEY, } from '@phnx-labs/sessions-cli/reader';
32
24
  import { runRemoteSessions, buildForwardedArgs, ensureWholeIndex } from '../lib/session/remote.js';
33
25
  import { formatRelativeTime, sessionAgeParts } from '../lib/session/relative-time.js';
34
- import { linkPath, linkUrl, shortenModel, formatTokenCount } from '@phnx-labs/sessions-cli/reader';
35
- import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
36
- import { sessionOwnerDevice, RESUME_PINNED_ENV } from '../lib/session/resume-owner.js';
37
- import { AGENTS, colorAgent, resolveAgentName } from '../lib/agents.js';
38
- import { getShimsDir } from '../lib/state.js';
26
+ import { shortenModel, formatTokenCount } from '@phnx-labs/sessions-cli/reader';
27
+ import { colorAgent } from '../lib/agents.js';
39
28
  import { listJobs, listJobsWithRuns, listRuns, getRunDir } from '../lib/scheduling/routines.js';
40
29
  import { formatUsd } from '../lib/pricing/cost.js';
41
- import { fuzzyMatch, FUZZY_PRESETS } from '../lib/fuzzy.js';
42
30
  import { itemPicker } from '../lib/picker.js';
43
- import { resolveSessionAlias } from '../lib/session/actor-sidecar.js';
44
- import { listInstalledVersions, resolveVersionAliasLoose } from '../lib/installations/versions.js';
45
- import { getAgentsInvocation } from '../lib/daemon/daemon.js';
46
- import { sessionAgentSupportsResume, sessionRecoveryRunArgs } from '../lib/session/recovery.js';
47
31
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
48
- import { sessionPicker, buildPreview, loadSessionPreviewDigest, transcriptOnPeerOf, formatTodoCompact, } from './sessions-picker.js';
32
+ import { transcriptOnPeerOf, handlePickedSession, pickSessionInteractive, } from './sessions-picker.js';
49
33
  import { setHelpSections } from '../lib/help.js';
50
- import { cleanPreview, gatherActiveSessions, indexActiveBySessionId, isAwaitingUser, liveGlyphAndPreview, liveStatusWord, remoteHostsToDial, requestedLiveStatuses, resolveRoutineName, runLiveRoster, shouldIncludeLocal, statusColor, } from './ps-roster.js';
51
- 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';
52
37
  export { buildFilterOptions, renderSession, renderSessionLog, renderSessionLogJson, resolveViewMode, } from '../lib/session/presentation.js';
53
- import { registerSessionsTailCommand } from './sessions-tail.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';
54
40
  import { registerSessionsResumeCommand } from './sessions-resume.js';
55
41
  import { registerSessionsForkCommand } from './fork.js';
56
42
  import { registerSessionsBookmarkCommand } from './sessions-bookmark.js';
57
- import { isBookmarked, listBookmarks } from '../lib/session/bookmarks.js';
43
+ import { listBookmarks } from '../lib/session/bookmarks.js';
58
44
  import { registerFocusCommand } from './focus.js';
59
45
  import { registerDetachCommand } from './detach.js';
60
46
  import { registerSessionsStopCommand } from './sessions-stop.js';
@@ -71,10 +57,6 @@ import { registerSessionsStatsCommand } from './sessions-stats.js';
71
57
  import { registerSessionsInsightsCommand } from './insights.js';
72
58
  import { registerSessionsOptimizeCommand } from './sessions-optimize.js';
73
59
  import { registerSessionsWatchCommand } from './sessions-watch.js';
74
- import { runBrowserSessionsCommand } from './browser-sessions-picker.js';
75
- import { runComputerSessionsCommand } from './computer-sessions-picker.js';
76
- import { buildComputerSessionRows } from '../lib/computer/sessions-list.js';
77
- import { countToolProgramOccurrences, parseToolProgramCountClause, readToolIndexCoverage, searchToolCalls, TOOL_QUERY_MAX_CLAUSE_BYTES, TOOL_QUERY_MAX_CLAUSES, TOOL_QUERY_MAX_RESULT_SESSIONS, serializeToolSearchEnvelope, toolSearchRemoteReceiveBudget, } from '../lib/session/tool-index.js';
78
60
  const SESSION_AGENT_FILTER_HELP = `Filter by agent, e.g. claude, codex, claude@2.0.65`;
79
61
  function collectQueryClause(value, previous) {
80
62
  return [...previous, value];
@@ -87,20 +69,6 @@ function applyAgentShorthands(options) {
87
69
  if (hit)
88
70
  options.agent = hit;
89
71
  }
90
- export function parseInstalledAgentVersionQuery(query, installedVersions = (agent) => (agent in AGENTS ? listInstalledVersions(agent) : [])) {
91
- const trimmed = query?.trim();
92
- if (!trimmed)
93
- return undefined;
94
- const at = trimmed.indexOf('@');
95
- if (at <= 0 || at !== trimmed.lastIndexOf('@') || at === trimmed.length - 1)
96
- return undefined;
97
- const agentName = trimmed.slice(0, at).toLowerCase();
98
- if (!SESSION_AGENTS.includes(agentName))
99
- return undefined;
100
- const agent = agentName;
101
- const version = trimmed.slice(at + 1);
102
- return installedVersions(agent).includes(version) ? `${agent}@${version}` : undefined;
103
- }
104
72
  function applyVersionFilters(query, options) {
105
73
  const explicitVersion = options.version ?? options.sessionVersion;
106
74
  if (explicitVersion) {
@@ -159,7 +127,6 @@ function createScanProgressTracker(verbs, suffix, spinner) {
159
127
  },
160
128
  };
161
129
  }
162
- const PICKER_RECENT_COUNT = 15;
163
130
  const DEFAULT_LIMIT = '50';
164
131
  const WHOLE_TEAM_POOL_LIMIT = 5000;
165
132
  const OVERVIEW_ROWS_PER_PROJECT = 5;
@@ -220,44 +187,11 @@ function contextColor(context) {
220
187
  case 'headless': return chalk.gray;
221
188
  }
222
189
  }
223
- function shortCwd(cwd) {
224
- if (!cwd)
225
- return '-';
226
- const home = homeDir();
227
- return toComparablePath(cwd).startsWith(toComparablePath(home))
228
- ? '~' + cwd.slice(home.length)
229
- : cwd;
230
- }
231
190
  function formatStartedAt(startedAtMs) {
232
191
  if (!startedAtMs)
233
192
  return '-';
234
193
  return formatRelativeTime(new Date(startedAtMs).toISOString());
235
194
  }
236
- const LIVE_STATUS_W = 8;
237
- function liveStatusCell(live) {
238
- const word = liveStatusWord(live);
239
- if (!word || !live)
240
- return { cell: '', width: 0 };
241
- return { cell: statusColor(live.status)(padToWidth(word, LIVE_STATUS_W)), width: LIVE_STATUS_W };
242
- }
243
- export function ticketLabel(s) {
244
- return s.ticketId ?? (s.prNumber ? `PR#${s.prNumber}` : '');
245
- }
246
- function ticketUrl(s) {
247
- if (s.ticketId)
248
- return linearIssueUrl(s.ticketId);
249
- return s.prNumber ? s.prUrl : undefined;
250
- }
251
- export function linkTicketCell(s, label) {
252
- const url = ticketUrl(s);
253
- return url && label.trim() !== '-' ? linkUrl(url, label) : label;
254
- }
255
- export function linkCwdCell(s, label) {
256
- return s.cwd && !s._remote ? linkPath(s.cwd, label) : label;
257
- }
258
- function modelLabel(model) {
259
- return model ? shortenModel(model) : '-';
260
- }
261
195
  export function serializeSessionPickerRows(sessions, liveSessions, self = machineId()) {
262
196
  const liveById = new Map(liveSessions.filter((row) => row.sessionId).map((row) => [row.sessionId, row]));
263
197
  return sessions.map((session) => {
@@ -280,50 +214,6 @@ export function serializeSessionPickerRows(sessions, liveSessions, self = machin
280
214
  };
281
215
  });
282
216
  }
283
- export function mergeLocalFirst(sessions, localMachine) {
284
- const byMachine = new Map();
285
- const seen = new Set();
286
- for (const s of sessions) {
287
- const machine = s.machine || localMachine;
288
- if (s.id) {
289
- const dedupeKey = `${machine}:${s.id}`;
290
- if (seen.has(dedupeKey))
291
- continue;
292
- seen.add(dedupeKey);
293
- }
294
- (byMachine.get(machine) ?? byMachine.set(machine, []).get(machine)).push(s);
295
- }
296
- const keys = Array.from(byMachine.keys()).sort((a, b) => {
297
- if (a === localMachine)
298
- return -1;
299
- if (b === localMachine)
300
- return 1;
301
- const ac = byMachine.get(a).length, bc = byMachine.get(b).length;
302
- if (ac !== bc)
303
- return bc - ac;
304
- return a.localeCompare(b);
305
- });
306
- return keys.flatMap((k) => byMachine.get(k));
307
- }
308
- // Peer resolution exposes launch identity only; paths, plans, costs, and content stay local.
309
- export function serializeResolvedSessionsJson(sessions) {
310
- const safe = sessions.map((session) => ({
311
- id: session.id,
312
- shortId: session.shortId,
313
- agent: session.agent,
314
- harness: session.harness,
315
- origin: session.origin,
316
- timestamp: session.timestamp,
317
- lastActivity: session.lastActivity,
318
- project: session.project,
319
- version: session.version,
320
- mode: session.mode,
321
- label: session.label,
322
- topic: session.topic,
323
- machine: session.machine,
324
- }));
325
- return JSON.stringify(safe, null, 2) + '\n';
326
- }
327
217
  async function runRemoteSessionsJson(hosts) {
328
218
  const forwarded = ensureWholeIndex(buildForwardedArgs(process.argv, new Set(hosts)));
329
219
  if (!forwarded.includes('--json'))
@@ -331,35 +221,6 @@ async function runRemoteSessionsJson(hosts) {
331
221
  const { sessions } = await gatherRemoteList(forwarded, hosts);
332
222
  process.stdout.write(serializeSessionsJson(sessions));
333
223
  }
334
- export function parseRemoteComputerSessionRows(stdout, machine) {
335
- try {
336
- const value = JSON.parse(stdout);
337
- if (!Array.isArray(value))
338
- return { items: [], valid: false };
339
- const items = value
340
- .filter((row) => Boolean(row && typeof row === 'object' && !Array.isArray(row)))
341
- .map((row) => ({ ...row, machine: row.machine || machine }));
342
- return { items, valid: true };
343
- }
344
- catch {
345
- return { items: [], valid: false };
346
- }
347
- }
348
- async function gatherRemoteComputerSessionRows(hosts) {
349
- const hostSet = new Set(hosts ?? []);
350
- const forwarded = buildForwardedArgs(process.argv, hostSet);
351
- if (!forwarded.includes('--json'))
352
- forwarded.push('--json');
353
- if (!forwarded.includes('--no-interactive'))
354
- forwarded.push('--no-interactive');
355
- const result = await gatherRemoteAgentsJson({
356
- args: forwarded,
357
- noFanoutEnv: NO_FANOUT_ENV,
358
- hosts,
359
- parse: parseRemoteComputerSessionRows,
360
- });
361
- return result.items;
362
- }
363
224
  function useInteractiveBrowser(options) {
364
225
  return options.interactive !== false && !options.json && isInteractiveTerminal();
365
226
  }
@@ -710,384 +571,24 @@ function canonicalSessionsCommand(query, options) {
710
571
  a.push(JSON.stringify(q));
711
572
  return 'ag ' + a.join(' ');
712
573
  }
713
- const SESSION_DETAIL_MAX_MESSAGES = 8;
714
- const SESSION_DETAIL_MESSAGE_MAX_CHARS = 4_000;
715
- function sessionTranscriptStamp(session) {
716
- try {
717
- if (!session.filePath)
718
- return undefined;
719
- const stat = fs.statSync(session.filePath);
720
- return { fileMtimeMs: stat.mtimeMs, fileSize: stat.size };
721
- }
722
- catch {
723
- return undefined;
724
- }
725
- }
726
- export function buildSessionDetailBlock(session, digest, events, sourceStamp) {
727
- const bound = (text) => redactSecrets(sanitizeForTerminal(text)).slice(0, SESSION_DETAIL_MESSAGE_MAX_CHARS);
728
- const stamp = sourceStamp ?? sessionTranscriptStamp(session);
729
- const canDateEvents = sourceStamp !== undefined || events.length === 0;
730
- const daemonProjection = stamp ? readSessionTimelineAny(session.id, stamp) : undefined;
731
- let foldEvents = events;
732
- if (foldEvents.length === 0 && session.filePath) {
733
- foldEvents = readSessionTail(session.filePath, session.agent);
734
- }
735
- let projection = daemonProjection;
736
- let onDemand = false;
737
- if (!projection && foldEvents.length > 0) {
738
- const state = foldTimeline(foldEvents, emptyTimelineState());
739
- projection = {
740
- request: state.request,
741
- timeline: projectTimeline(state, undefined),
742
- files: projectSessionFiles(state),
743
- };
744
- onDemand = true;
745
- }
746
- let messages;
747
- if (foldEvents.length > 0) {
748
- messages = foldEvents
749
- .filter((e) => e.type === 'message' && !e._synthetic && Boolean(e.content) && (e.role === 'user' || e.role === 'assistant'))
750
- .slice(-SESSION_DETAIL_MAX_MESSAGES)
751
- .map(e => ({ role: e.role, text: bound(e.content), at: e.timestamp ?? null }));
752
- }
753
- else {
754
- messages = [];
755
- if (digest?.firstUser)
756
- messages.push({ role: 'user', text: bound(digest.firstUser), at: session.timestamp ?? null });
757
- if (digest?.lastAssistant)
758
- messages.push({ role: 'assistant', text: bound(digest.lastAssistant), at: session.lastActivity ?? null });
759
- }
760
- const endStamp = sessionTranscriptStamp(session);
761
- const unchanged = canDateEvents && stamp !== undefined && endStamp !== undefined
762
- && stamp.fileMtimeMs === endStamp.fileMtimeMs && stamp.fileSize === endStamp.fileSize;
763
- const partial = Boolean(digest?.partial) || !daemonProjection || !unchanged;
764
- const reason = digest?.partialReason
765
- ?? (onDemand
766
- ? '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'
767
- : (!projection ? 'no transcript available to fold request/timeline/files for this session' : null));
768
- return {
769
- request: projection?.request ?? null,
770
- timeline: projection?.timeline ?? null,
771
- files: projection?.files ?? null,
772
- messages,
773
- sourceRevision: unchanged ? new Date(stamp.fileMtimeMs).toISOString() : null,
774
- partial,
775
- reason,
776
- };
777
- }
778
- export async function renderSessionPreview(query, scope) {
779
- if (scope.json && !scope.local && scope.hosts?.length === 1
780
- && scope.hosts[0] !== machineId() && isCompleteSessionId(query.trim())) {
781
- const { getRemoteSessionPreview } = await import('../lib/session/remote-preview-cache.js');
782
- const result = await getRemoteSessionPreview(query.trim(), scope.hosts[0], {
783
- refresh: scope.refresh,
784
- revision: scope.revision,
785
- });
786
- const envelope = result.envelope;
787
- console.log(JSON.stringify({
788
- schemaVersion: 1,
789
- session: envelope?.session ?? null,
790
- active: result.cache.source === 'live' ? (envelope?.active ?? null) : null,
791
- preview: envelope?.preview ?? null,
792
- error: envelope?.error ?? (envelope ? null : result.cache.reason),
793
- details: envelope?.details ?? null,
794
- cache: result.cache,
795
- }));
796
- return;
797
- }
798
- let outcome = await resolveSessionMetadataValue(query, scope);
799
- if (outcome.kind !== 'resolved'
800
- && (!scope.hosts?.length || shouldIncludeLocal(scope.hosts, machineId()))) {
801
- const discovered = applyScopeFilters(await discoverSessions({ all: true, cwd: process.cwd(), limit: 5000, waitForScan: true }), scope);
802
- const localMatches = resolveSessionQuery(discovered, query, { indexFallback: false, scope }).matches
803
- .map(session => ({ ...session, machine: session.machine || machineId() }));
804
- const exact = localMatches.find(session => selectorAllowsEarlyExit(query)
805
- && session.id.toLowerCase() === query.trim().toLowerCase());
806
- if (exact)
807
- outcome = { kind: 'resolved', session: exact };
808
- else if (outcome.kind === 'not-found' && localMatches.length > 0) {
809
- outcome = metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, query);
810
- }
811
- }
812
- if (outcome.kind === 'partial') {
813
- const offline = outcome.failedPeers;
814
- console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
815
- console.error(chalk.red(`No session matching "${query}" on any reachable device (${offline.length} unreachable, not checked).`));
816
- console.error(chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'));
817
- process.exitCode = 1;
818
- return;
819
- }
820
- if (outcome.kind === 'not-found') {
821
- notFoundByIdMessage(query).forEach(l => console.error(l));
822
- process.exitCode = 1;
823
- return;
824
- }
825
- if (outcome.kind === 'ambiguous') {
826
- console.error(chalk.red(`Multiple sessions match "${query}" across the fleet:`));
827
- for (const candidate of outcome.candidates) {
828
- const match = candidate.hits[0].session;
829
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
830
- console.error(chalk.cyan(` ${match.shortId} ${match.id}`) + chalk.gray(` ${machines} ${match.agent}${match.version ? ` ${match.version}` : ''}`));
831
- }
832
- console.error(chalk.gray('Pass the full session ID to narrow it down.'));
833
- process.exitCode = 1;
834
- return;
835
- }
836
- const session = outcome.session;
837
- const transcriptPeer = transcriptOnPeerOf(session);
838
- if (transcriptPeer) {
839
- const args = ['sessions', 'preview', session.id, '--local'];
840
- if (scope.json)
841
- args.push('--json');
842
- const rendered = await runOnPeer(args, transcriptPeer);
843
- if (rendered === 'no-target') {
844
- console.error(chalk.red(`Session ${session.id} is on ${transcriptPeer}, but that device is not reachable.`));
845
- process.exitCode = 1;
846
- }
847
- return;
848
- }
849
- let live;
850
- try {
851
- const loaded = await loadLocalActiveSessions();
852
- live = indexActiveBySessionId(loaded.sessions).get(session.id);
853
- }
854
- catch { }
855
- if (scope.json) {
856
- const sourceStamp = sessionTranscriptStamp(session);
857
- const { digest, error, events } = loadSessionPreviewDigest(session);
858
- console.log(JSON.stringify({
859
- schemaVersion: 1,
860
- session: {
861
- id: session.id,
862
- shortId: session.shortId,
863
- agent: session.agent,
864
- version: session.version,
865
- model: session.model,
866
- account: session.account,
867
- machine: session.machine ?? machineId(),
868
- cwd: session.cwd,
869
- project: session.project,
870
- gitBranch: session.gitBranch,
871
- createdAt: session.timestamp,
872
- lastActivity: session.lastActivity,
873
- durationMs: session.durationMs,
874
- messageCount: session.messageCount,
875
- tokenCount: session.tokenCount,
876
- costUsd: session.costUsd,
877
- label: session.label,
878
- topic: session.topic,
879
- ticketId: session.ticketId,
880
- prUrl: session.prUrl,
881
- },
882
- active: live ? {
883
- status: live.status,
884
- activity: live.activity,
885
- awaitingReason: live.awaitingReason,
886
- lastActivityMs: live.lastActivityMs,
887
- startedAtMs: live.startedAtMs,
888
- pid: live.pid,
889
- host: live.host,
890
- } : null,
891
- preview: digest ?? null,
892
- error: error ?? null,
893
- details: buildSessionDetailBlock(session, digest, events, sourceStamp),
894
- }));
895
- return;
896
- }
897
- const headline = formatLiveStatusHeadline(live, isBookmarked(session.id));
898
- if (headline)
899
- console.log(headline);
900
- console.log(buildPreview(session));
901
- }
902
- export function formatLiveStatusHeadline(live, bookmarked = false) {
903
- const star = bookmarked ? chalk.yellow('★ ') : '';
904
- if (!live)
905
- return bookmarked ? chalk.yellow('★ bookmarked') : '';
906
- const { glyph } = liveGlyphAndPreview(live);
907
- const word = liveStatusWord(live) || live.status;
908
- const needsYou = isAwaitingUser(live);
909
- const reason = live.awaitingReason ? ` (${live.awaitingReason.replace('_', ' ')})` : '';
910
- let suffix = needsYou ? chalk.yellow(` ← needs you${reason}`) : '';
911
- if (live.status === 'crashed') {
912
- suffix = chalk.redBright(' ← the host app or connection went away and took the agent with it');
913
- }
914
- else if (live.status === 'orphaned') {
915
- suffix = needsYou
916
- ? chalk.yellow(` ← waiting on you${reason}, and no client is attached to answer it`)
917
- : chalk.yellow(' ← still running, but no client is attached — nothing is showing it');
918
- }
919
- return `${star}${glyph} ${statusColor(live.status)(word)}${suffix}`;
920
- }
921
- export function mergeToolSearchEnvelopes(local, remotes) {
922
- const all = [local, ...remotes];
923
- const sessions = new Map();
924
- for (const envelope of all) {
925
- for (const session of envelope.sessions) {
926
- sessions.set(`${session.machine ?? 'local'}\0${session.id}`, session);
927
- }
928
- }
929
- return {
930
- schemaVersion: 1,
931
- generatedAt: new Date().toISOString(),
932
- query: local.query,
933
- coverage: {
934
- indexedFiles: all.reduce((n, envelope) => n + envelope.coverage.indexedFiles, 0),
935
- indexedCalls: all.reduce((n, envelope) => n + envelope.coverage.indexedCalls, 0),
936
- skippedFiles: all.reduce((n, envelope) => n + envelope.coverage.skippedFiles, 0),
937
- limitedFiles: all.reduce((n, envelope) => n + envelope.coverage.limitedFiles, 0),
938
- remainingFiles: all.reduce((n, envelope) => n + envelope.coverage.remainingFiles, 0),
939
- complete: all.every((envelope) => envelope.coverage.complete),
940
- },
941
- sessions: [...sessions.values()].sort((a, b) => b.timestamp.localeCompare(a.timestamp)),
942
- };
943
- }
944
- export function mergeToolProgramCountEnvelopes(local, remotes) {
945
- const all = [local, ...remotes];
946
- return {
947
- schemaVersion: 1,
948
- kind: 'tool-program-count',
949
- generatedAt: new Date().toISOString(),
950
- query: local.query,
951
- coverage: {
952
- indexedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.indexedFiles, 0),
953
- indexedCalls: all.reduce((sum, envelope) => sum + envelope.coverage.indexedCalls, 0),
954
- skippedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.skippedFiles, 0),
955
- limitedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.limitedFiles, 0),
956
- remainingFiles: all.reduce((sum, envelope) => sum + envelope.coverage.remainingFiles, 0),
957
- complete: all.every((envelope) => envelope.coverage.complete),
958
- },
959
- totals: {
960
- occurrences: all.reduce((sum, envelope) => sum + envelope.totals.occurrences, 0),
961
- toolCalls: all.reduce((sum, envelope) => sum + envelope.totals.toolCalls, 0),
962
- sessions: all.reduce((sum, envelope) => sum + envelope.totals.sessions, 0),
963
- },
964
- machines: all.flatMap((envelope) => envelope.machines),
965
- };
966
- }
967
- export function toolOriginSessions(sessions, machine, originOnly) {
968
- return originOnly
969
- ? sessions.filter((session) => (session.machine ?? machine) === machine)
970
- : sessions;
971
- }
972
- function printToolProgramCount(envelope) {
973
- const { totals } = envelope;
974
- const qualifier = envelope.coverage.complete ? '' : 'at least ';
975
- console.log(`${envelope.query.program}: ${qualifier}${totals.occurrences.toLocaleString()} static occurrence${totals.occurrences === 1 ? '' : 's'} `
976
- + `in ${totals.toolCalls.toLocaleString()} tool call${totals.toolCalls === 1 ? '' : 's'} `
977
- + `across ${totals.sessions.toLocaleString()} session${totals.sessions === 1 ? '' : 's'}.`);
978
- if (!envelope.coverage.complete) {
979
- console.log(chalk.yellow(`Partial tool index: ${envelope.coverage.remainingFiles.toLocaleString()} transcript${envelope.coverage.remainingFiles === 1 ? '' : 's'} still need `
980
- + '`agents sessions backfill tools`.'));
981
- }
982
- }
983
- export function toolSearchFleetSortError(sort, spansDevices) {
984
- if (!spansDevices || !sort || sort === 'recent')
985
- return undefined;
986
- return 'Tool search across devices supports only --sort recent; cost and duration are local-only.';
987
- }
988
- function printToolSearch(envelope) {
989
- for (const session of envelope.sessions) {
990
- const machineName = session.machine
991
- ? truncate(sanitizeForTerminal(session.machine).replace(/\s+/g, ' '), 80)
992
- : '';
993
- const machine = machineName ? ` @ ${machineName}` : '';
994
- const rawHeading = sessionHeadline(session) || session.project || session.shortId;
995
- const heading = truncate(sanitizeForTerminal(rawHeading).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 20));
996
- console.log(`${chalk.cyan(session.shortId)}${chalk.gray(machine)} ${heading}`);
997
- for (const call of session.calls) {
998
- const tool = truncate(sanitizeForTerminal(call.tool).replace(/\s+/g, ' '), 80);
999
- const safePrograms = call.programs.map((program) => truncate(sanitizeForTerminal(program).replace(/\s+/g, ' '), 80));
1000
- const programs = safePrograms.length > 0 ? ` [${safePrograms.join(', ')}]` : '';
1001
- const status = call.outcome === 'unknown' ? '' : ` ${call.outcome}`;
1002
- const input = truncate(sanitizeForTerminal(call.input).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 26));
1003
- console.log(` ${chalk.gray(`#${call.ordinal + 1}`)} ${tool}${programs}${status} ${input}`);
1004
- const snippet = call.error || call.output;
1005
- if (snippet) {
1006
- console.log(` ${chalk.gray(truncate(sanitizeForTerminal(snippet).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 8)))}`);
1007
- }
1008
- }
1009
- console.log();
1010
- }
1011
- const count = envelope.sessions.length;
1012
- console.log(chalk.gray(`${count} matching session${count === 1 ? '' : 's'}.`));
1013
- if (!envelope.coverage.complete) {
1014
- const skipped = envelope.coverage.skippedFiles > 0
1015
- ? ` ${envelope.coverage.skippedFiles} transcript${envelope.coverage.skippedFiles === 1 ? ' was' : 's were'} skipped.`
1016
- : '';
1017
- const limited = envelope.coverage.limitedFiles > 0
1018
- ? ` ${envelope.coverage.limitedFiles} transcript${envelope.coverage.limitedFiles === 1 ? ' has' : 's have'} incomplete evidence because a safety limit was reached.`
1019
- : '';
1020
- const retry = envelope.coverage.remainingFiles > 0
1021
- ? ' Run `agents sessions backfill tools` to index historical transcripts.'
1022
- : '';
1023
- console.log(chalk.yellow(`Tool index coverage is partial: ${envelope.coverage.remainingFiles} transcript${envelope.coverage.remainingFiles === 1 ? '' : 's'} remain.${skipped}${limited}${retry}`));
1024
- }
1025
- }
1026
574
  async function sessionsAction(query, options, limitSource) {
1027
- const queryClauses = options.query ?? [];
1028
575
  const liveStatuses = requestedLiveStatuses(options);
1029
576
  const liveOnly = options.active === true || liveStatuses.length > 0;
1030
- const toolOnly = options.include?.split(',').map((role) => role.trim()).filter(Boolean).join(',') === 'tools';
1031
- const toolEvidenceMode = toolOnly;
1032
- if (options.count && !toolOnly) {
1033
- console.error(chalk.red('--count requires --include tools.'));
1034
- process.exitCode = 1;
1035
- return;
1036
- }
1037
- if (!toolEvidenceMode) {
1038
- if (queryClauses.length > 1) {
1039
- console.error(chalk.red('Repeated --query clauses require --include tools.'));
1040
- process.exitCode = 1;
1041
- return;
1042
- }
1043
- query = query ?? queryClauses[0];
1044
- }
1045
- if (options.fleet && !toolEvidenceMode) {
1046
- console.error(chalk.red('--fleet applies to tool-call queries: add --include tools.'));
1047
- process.exitCode = 1;
1048
- return;
1049
- }
1050
- if (toolEvidenceMode && (options.markdown || options.redact === false)) {
1051
- const incompatible = [
1052
- options.markdown ? '--markdown' : undefined,
1053
- options.redact === false ? '--no-redact' : undefined,
1054
- ].filter((flag) => flag !== undefined);
1055
- console.error(chalk.red(`${incompatible.join(' and ')} cannot be used with --include tools.`));
1056
- console.error(chalk.gray('Tool evidence is always redacted and byte-bounded; drop the conflicting render flag.'));
1057
- process.exitCode = 1;
1058
- return;
1059
- }
1060
- if (toolEvidenceMode && queryClauses.length > TOOL_QUERY_MAX_CLAUSES) {
1061
- console.error(chalk.red(`Tool search accepts at most ${TOOL_QUERY_MAX_CLAUSES} --query clauses.`));
1062
- process.exitCode = 1;
577
+ const includesOnlyTools = options.include?.split(',').map((role) => role.trim()).filter(Boolean).join(',') === 'tools';
578
+ const readsOneSession = query !== undefined && looksLikeSessionId(query) && (options.query ?? []).length === 0;
579
+ if (includesOnlyTools && !readsOneSession) {
580
+ console.error(chalk.red('Tool-call search lives in the standalone sessions CLI:'));
581
+ console.error(chalk.gray(" sessions --include tools --query 'program:git' [--count] [--host <device>] [--json]"));
582
+ process.exitCode = 2;
1063
583
  return;
1064
584
  }
1065
- if (toolEvidenceMode && queryClauses.some((clause) => Buffer.byteLength(clause) > TOOL_QUERY_MAX_CLAUSE_BYTES)) {
1066
- console.error(chalk.red(`Each tool --query clause is limited to ${TOOL_QUERY_MAX_CLAUSE_BYTES} bytes.`));
1067
- process.exitCode = 1;
1068
- return;
1069
- }
1070
- if (options.count && (queryClauses.length !== 1 || query !== undefined)) {
1071
- console.error(chalk.red('--count requires exactly one --query program:<name> clause and no positional query.'));
1072
- process.exitCode = 1;
1073
- return;
1074
- }
1075
- if (options.count && (limitSource === 'cli' || limitSource === 'env')) {
1076
- console.error(chalk.red('--count covers the complete filtered scope and cannot be combined with --limit.'));
585
+ const queryClauses = options.query ?? [];
586
+ if (queryClauses.length > 1) {
587
+ console.error(chalk.red('Pass --query once.'));
1077
588
  process.exitCode = 1;
1078
589
  return;
1079
590
  }
1080
- let countProgram;
1081
- if (options.count) {
1082
- try {
1083
- countProgram = parseToolProgramCountClause(queryClauses[0]);
1084
- }
1085
- catch (error) {
1086
- console.error(chalk.red(error instanceof Error ? error.message : String(error)));
1087
- process.exitCode = 1;
1088
- return;
1089
- }
1090
- }
591
+ query = query ?? queryClauses[0];
1091
592
  applyAgentShorthands(options);
1092
593
  try {
1093
594
  query = applyVersionFilters(query, options);
@@ -1153,13 +654,7 @@ async function sessionsAction(query, options, limitSource) {
1153
654
  });
1154
655
  return;
1155
656
  }
1156
- if (toolEvidenceMode && options.local === true
1157
- && options.host && !shouldIncludeLocal(options.host, machineId())) {
1158
- console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
1159
- console.error(chalk.gray('Drop one — `--device <box>` to read that machine, `--local` to stay on this one.'));
1160
- process.exit(1);
1161
- }
1162
- if (options.host && options.host.length > 0 && !liveOnly && !toolEvidenceMode) {
657
+ if (options.host && options.host.length > 0 && !liveOnly) {
1163
658
  if (options.local === true && !shouldIncludeLocal(options.host, machineId())) {
1164
659
  console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
1165
660
  console.error(chalk.gray('Drop one — `--device <box>` to read that machine, `--local` to stay on this one.'));
@@ -1244,12 +739,12 @@ async function sessionsAction(query, options, limitSource) {
1244
739
  process.exit(1);
1245
740
  }
1246
741
  const mode = resolveViewMode(options, filterOpts);
1247
- const wantsRender = !toolEvidenceMode && (mode === 'markdown' || hasAnyFilter(filterOpts));
742
+ const wantsRender = mode === 'markdown' || hasAnyFilter(filterOpts);
1248
743
  if ((options.artifacts || options.artifact !== undefined) && searchQuery) {
1249
744
  await renderArtifactsGlobal(searchQuery, options.artifacts ?? false, options.artifact, artifactLookupScope(options.agent, options.project, options.routine));
1250
745
  return;
1251
746
  }
1252
- if (!toolEvidenceMode && searchQuery && looksLikeSessionId(searchQuery)) {
747
+ if (searchQuery && looksLikeSessionId(searchQuery)) {
1253
748
  await renderOneSession(searchQuery, mode, { agent: options.agent, project: options.project, routine: options.routine, filter: filterOpts, redact: options.redact, local: options.local, hosts: options.host });
1254
749
  return;
1255
750
  }
@@ -1265,22 +760,9 @@ async function sessionsAction(query, options, limitSource) {
1265
760
  const limit = wantsOverview
1266
761
  ? OVERVIEW_POOL_LIMIT
1267
762
  : parseInt(userSetLimit ? options.limit : wantsWholeTeam || wantsWholeRoutine ? String(WHOLE_TEAM_POOL_LIMIT) : DEFAULT_LIMIT, 10);
1268
- if (toolEvidenceMode && (!Number.isSafeInteger(limit) || limit < 1 || limit > TOOL_QUERY_MAX_RESULT_SESSIONS)) {
1269
- console.error(chalk.red(`Tool search --limit must be from 1 to ${TOOL_QUERY_MAX_RESULT_SESSIONS}.`));
1270
- process.exitCode = 1;
1271
- return;
1272
- }
1273
763
  const since = wantsOverview
1274
764
  ? options.since
1275
765
  : (options.since ?? (isInteractive && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? '30d' : undefined));
1276
- const toolSpansDevices = toolEvidenceMode
1277
- && (options.fleet || (options.host?.length ?? 0) > 0);
1278
- const toolSortError = toolSearchFleetSortError(options.sort, toolSpansDevices);
1279
- if (toolSortError) {
1280
- console.error(chalk.red(toolSortError));
1281
- process.exitCode = 1;
1282
- return;
1283
- }
1284
766
  const spinner = options.json ? null : ora().start();
1285
767
  const tracker = createScanProgressTracker(LOAD_VERBS, 'sessions', spinner);
1286
768
  try {
@@ -1288,50 +770,26 @@ async function sessionsAction(query, options, limitSource) {
1288
770
  const scope = {
1289
771
  agent,
1290
772
  version,
1291
- all: pathFilter ? undefined : options.all || wantsWholeTeam || wantsWholeRoutine || toolSpansDevices,
773
+ all: pathFilter ? undefined : options.all || wantsWholeTeam || wantsWholeRoutine,
1292
774
  cwd: process.cwd(),
1293
- cwdPrefix: pathFilter ?? (wantsOverview && !options.all && !wantsWholeTeam && !wantsWholeRoutine && !toolSpansDevices ? process.cwd() : undefined),
775
+ cwdPrefix: pathFilter ?? (wantsOverview && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? process.cwd() : undefined),
1294
776
  project: options.project,
1295
777
  since,
1296
778
  until: options.until,
1297
779
  sortBy,
1298
780
  origin: options.routine ? 'routine' : undefined,
1299
- skipExistenceCheck: toolEvidenceMode,
1300
- unbounded: toolEvidenceMode,
1301
781
  skill: options.skill,
1302
782
  plugin: options.plugin,
1303
783
  };
1304
784
  let hiddenUnmanaged = 0;
1305
- const toolSelf = toolEvidenceMode ? machineId() : undefined;
1306
- const toolIncludesLocal = !toolEvidenceMode
1307
- || process.env[NO_FANOUT_ENV] === '1'
1308
- || shouldIncludeLocal(options.host, toolSelf);
1309
- const indexedIdMatches = toolIncludesLocal && toolEvidenceMode && searchQuery && looksLikeSessionId(searchQuery)
1310
- ? scopeToManaged(findSessionsById(searchQuery, { agent, version, project: options.project }), agent ? [agent] : SESSION_AGENTS, { agent, includeUnmanaged: options.unmanaged })
1311
- : [];
1312
- let sessions;
1313
- if (!toolIncludesLocal) {
1314
- sessions = [];
1315
- }
1316
- else if (indexedIdMatches.length > 0) {
1317
- sessions = indexedIdMatches.map((session) => ({
1318
- ...session,
1319
- machine: session.machine ?? toolSelf,
1320
- }));
1321
- }
1322
- else {
1323
- const readOptions = {
1324
- ...scope,
1325
- limit,
1326
- excludeTeamOrigin: !shouldShowTeamSessions(options),
1327
- onProgress: tracker.onProgress,
1328
- includeUnmanaged: options.unmanaged,
1329
- onHiddenUnmanaged: (n) => { hiddenUnmanaged = n; },
1330
- };
1331
- sessions = toolEvidenceMode
1332
- ? await queryIndexedSessions(readOptions, { resolveLinear: false })
1333
- : await discoverSessions(readOptions);
1334
- }
785
+ let sessions = await discoverSessions({
786
+ ...scope,
787
+ limit,
788
+ excludeTeamOrigin: !shouldShowTeamSessions(options),
789
+ onProgress: tracker.onProgress,
790
+ includeUnmanaged: options.unmanaged,
791
+ onHiddenUnmanaged: (n) => { hiddenUnmanaged = n; },
792
+ });
1335
793
  tracker.stop();
1336
794
  spinner?.stop();
1337
795
  const { visible: visibleSessions } = filterTeamSessions(sessions, shouldShowTeamSessions(options));
@@ -1342,62 +800,6 @@ async function sessionsAction(query, options, limitSource) {
1342
800
  const bookmarks = listBookmarks();
1343
801
  sessions = sessions.filter((s) => bookmarks.has(s.id));
1344
802
  }
1345
- if (toolEvidenceMode) {
1346
- const self = toolSelf;
1347
- const selectedSessions = searchQuery
1348
- ? filterSessionsByQuery(sessions, searchQuery, {
1349
- agent: options.agent,
1350
- project: options.project,
1351
- routine: options.routine,
1352
- })
1353
- : sessions;
1354
- const localSessions = selectedSessions;
1355
- const mayFanOut = options.local !== true && process.env[NO_FANOUT_ENV] !== '1';
1356
- const hosts = remoteHostsToDial(options.host, self);
1357
- const originOnly = process.env[NO_FANOUT_ENV] === '1'
1358
- || (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0));
1359
- const querySessions = toolOriginSessions(localSessions, self, originOnly);
1360
- if (countProgram) {
1361
- const countCoverage = readToolIndexCoverage(querySessions);
1362
- let countEnvelope = countToolProgramOccurrences(querySessions, countProgram, countCoverage, self);
1363
- if (!toolIncludesLocal)
1364
- countEnvelope.machines = [];
1365
- if (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0)
1366
- && (!options.host?.length || (hosts && hosts.length > 0))) {
1367
- const stripped = toolSearchForwardedArgs(process.argv, options.host ?? []);
1368
- const remote = await gatherRemoteToolProgramCounts(stripped, options.host?.length ? hosts : undefined, countProgram);
1369
- countEnvelope = mergeToolProgramCountEnvelopes(countEnvelope, remote.envelopes.map((item) => item.envelope));
1370
- if (remote.unreachable.length > 0)
1371
- countEnvelope.coverage.complete = false;
1372
- }
1373
- if (options.json)
1374
- process.stdout.write(JSON.stringify(countEnvelope, null, 2) + '\n');
1375
- else
1376
- printToolProgramCount(countEnvelope);
1377
- return;
1378
- }
1379
- const coverage = readToolIndexCoverage(querySessions);
1380
- let envelope = searchToolCalls(querySessions, queryClauses, coverage, limit);
1381
- if (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0)) {
1382
- if (!options.host?.length || (hosts && hosts.length > 0)) {
1383
- const stripped = toolSearchForwardedArgs(process.argv, options.host ?? []);
1384
- const remote = await gatherRemoteToolSearch(stripped, options.host?.length ? hosts : undefined, toolSearchRemoteReceiveBudget(envelope), queryClauses);
1385
- envelope = mergeToolSearchEnvelopes(envelope, remote.envelopes.map((item) => item.envelope));
1386
- if (remote.truncated.length > 0 || remote.unreachable.length > 0) {
1387
- envelope.coverage.complete = false;
1388
- }
1389
- }
1390
- }
1391
- envelope.sessions = envelope.sessions.slice(0, limit);
1392
- const serializedEnvelope = serializeToolSearchEnvelope(envelope);
1393
- if (options.json) {
1394
- process.stdout.write(serializedEnvelope);
1395
- }
1396
- else {
1397
- printToolSearch(envelope);
1398
- }
1399
- return;
1400
- }
1401
803
  const hiddenCount = shouldShowTeamSessions(options) || options.inTeam
1402
804
  ? 0
1403
805
  : countSessionsInScope({ ...scope, onlyTeamOrigin: true });
@@ -1545,130 +947,6 @@ async function sessionsAction(query, options, limitSource) {
1545
947
  process.exit(1);
1546
948
  }
1547
949
  }
1548
- function teamTag(session) {
1549
- const origin = session.teamOrigin;
1550
- if (!origin)
1551
- return '';
1552
- const handle = safeTeamText(origin.handle);
1553
- const team = safeTeamText(origin.team);
1554
- if (team)
1555
- return `[${team}${handle ? `/${handle}` : ''}] `;
1556
- return handle ? `[${handle}] ` : '[team] ';
1557
- }
1558
- export function matchesTeam(session, team) {
1559
- const want = safeTeamText(team)?.trim().toLowerCase();
1560
- if (!want)
1561
- return true;
1562
- return (safeTeamText(session.spawnedTeam)?.toLowerCase() === want ||
1563
- safeTeamText(session.teamOrigin?.team)?.toLowerCase() === want);
1564
- }
1565
- const TEAM_BADGE_MAX = 10;
1566
- export function teamBadge(session) {
1567
- const team = safeTeamText(session.spawnedTeam);
1568
- if (!team)
1569
- return { plain: '', width: 0 };
1570
- const plain = `team:${truncate(team, TEAM_BADGE_MAX)} `;
1571
- return { plain, width: stringWidth(plain) };
1572
- }
1573
- function originTag(session) {
1574
- if (session.origin !== 'routine')
1575
- return '';
1576
- return `[routine${session.routineName ? ` · ${session.routineName}` : ''}] `;
1577
- }
1578
- const MIN_TOPIC_W = 16;
1579
- function timeCell(age, topicSlack) {
1580
- const lastOnly = { plain: age.last, text: chalk.gray(age.last), extraW: 0 };
1581
- if (!age.created)
1582
- return lastOnly;
1583
- const prefix = `${age.created} → `;
1584
- const extraW = stringWidth(prefix);
1585
- if (topicSlack - extraW < MIN_TOPIC_W)
1586
- return lastOnly;
1587
- return { plain: prefix + age.last, text: chalk.dim(prefix) + chalk.gray(age.last), extraW };
1588
- }
1589
- export function flatSessionRow(session, live, showTicket = false, cols = {}, bookmarked = false) {
1590
- const shown = sessionDisplayAgent(session);
1591
- const agentColor = colorAgent(shown);
1592
- const age = sessionAgeParts(session.timestamp, session.lastActivity);
1593
- const project = session.project || '-';
1594
- const tag = originTag(session) || teamTag(session);
1595
- const label = session.label;
1596
- const { glyph, preview } = liveGlyphAndPreview(live);
1597
- const restingTodo = !live ? formatTodoCompact(session.todos) : '';
1598
- const topicBase = tag ? `${tag}${session.topic ?? ''}` : session.topic;
1599
- const doing = [restingTodo, preview || topicBase].filter(Boolean).join(' · ') || undefined;
1600
- const wt = session.worktreeSlug ? chalk.magenta(`wt:${session.worktreeSlug}`) : '';
1601
- const team = teamBadge(session);
1602
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1603
- const machineColW = cols.machineWidth ?? PICKER_MACHINE_W;
1604
- const machineCell = cols.showMachine
1605
- ? chalk.gray(padToWidth(truncateToWidth((cols.machineLabel?.(session.machine ?? '') ?? session.machine ?? '') || '-', machineColW - 1), machineColW))
1606
- : '';
1607
- const TICKET_W = 10;
1608
- const ticketCell = showTicket
1609
- ? chalk.blue(linkTicketCell(session, padToWidth(truncateToWidth(ticketLabel(session) || '-', TICKET_W), TICKET_W + 1)))
1610
- : '';
1611
- const { cell: statusCell, width: statusW } = liveStatusCell(live);
1612
- const glyphW = glyph ? 2 : 0;
1613
- const machineW = cols.showMachine ? machineColW : 0;
1614
- const ticketW = showTicket ? TICKET_W + 1 : 0;
1615
- const wtW = wt ? stringWidth(wt) + 1 : 0;
1616
- const width = terminalWidth();
1617
- const requestedModelW = cols.showModel ? (cols.modelWidth ?? PICKER_MODEL_MAX) : 0;
1618
- const bookmarkW = cols.showBookmark ? 2 : 0;
1619
- const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
1620
- const fixedW = bookmarkW + (10 + 9 + 8 + 16) + glyphW + statusW + machineW + ticketW + wtW + team.width + stringWidth(age.last) + 1;
1621
- const modelSlack = width - fixedW - MIN_TOPIC_W;
1622
- const modelW = requestedModelW <= modelSlack
1623
- ? requestedModelW
1624
- : modelSlack >= PICKER_MODEL_MIN ? modelSlack : 0;
1625
- const when = timeCell(age, width - fixedW - modelW);
1626
- const topicW = Math.max(MIN_TOPIC_W, width - fixedW - modelW - when.extraW);
1627
- return (bookmarkCell +
1628
- chalk.white(padToWidth(truncateToWidth(session.shortId, 9), 10)) +
1629
- agentColor(padToWidth(truncateToWidth(shown, 8), 9)) +
1630
- chalk.yellow(padToWidth(truncateToWidth(session.version || '-', 7), 8)) +
1631
- (modelW ? chalk.yellow(padToWidth(truncateToWidth(modelLabel(session.model), modelW - 1), modelW)) : '') +
1632
- machineCell +
1633
- chalk.cyan(linkCwdCell(session, padToWidth(truncateToWidth(project, 14), 16))) +
1634
- (glyph ? glyph + ' ' : '') +
1635
- statusCell +
1636
- teamSeg +
1637
- renderTopicCell(label, doing, '', topicW, topicW) +
1638
- ticketCell +
1639
- (wt ? wt + ' ' : '') +
1640
- when.text);
1641
- }
1642
- function treeSessionRow(session, live) {
1643
- const shown = sessionDisplayAgent(session);
1644
- const agentColor = colorAgent(shown);
1645
- const age = sessionAgeParts(session.timestamp, session.lastActivity);
1646
- const tag = originTag(session) || teamTag(session);
1647
- const label = session.label;
1648
- const { glyph, preview } = liveGlyphAndPreview(live);
1649
- const restingTodo = !live ? formatTodoCompact(session.todos) : '';
1650
- const topicBase = preview || (tag ? `${tag}${session.topic ?? ''}` : session.topic);
1651
- const topic = [restingTodo, topicBase].filter(Boolean).join(' · ') || '-';
1652
- const badges = signalBadges(metaSignals(session));
1653
- const badgeW = badges ? stringWidth(badges) + 1 : 0;
1654
- const team = teamBadge(session);
1655
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1656
- const head = label ? `${label} · ${topic}` : topic;
1657
- const { cell: statusCell, width: statusW } = liveStatusCell(live);
1658
- const glyphW = glyph ? 2 : 0;
1659
- const baseTopicW = terminalWidth() - (2 + 9 + 8) - glyphW - statusW - badgeW - team.width - stringWidth(age.last) - 1;
1660
- const when = timeCell(age, baseTopicW);
1661
- const topicW = Math.max(12, baseTopicW - when.extraW);
1662
- return (' ' +
1663
- chalk.dim(padToWidth(session.shortId, 9)) +
1664
- agentColor(padToWidth(truncateToWidth(shown, 7), 8)) +
1665
- (badges ? badges + ' ' : '') +
1666
- (glyph ? glyph + ' ' : '') +
1667
- statusCell +
1668
- teamSeg +
1669
- padToWidth(chalk.white(truncateToWidth(head, topicW)), topicW) +
1670
- ' ' + when.text);
1671
- }
1672
950
  export async function maybeLiveIndex(options) {
1673
951
  if (options.live === false || options.json)
1674
952
  return undefined;
@@ -1734,47 +1012,6 @@ function printSessionOverview(pool, hiddenCount, liveIndex, opts) {
1734
1012
  if (opts.hiddenUnmanaged)
1735
1013
  console.log(chalk.gray(formatUnmanagedHiddenFooter(opts.hiddenUnmanaged)));
1736
1014
  }
1737
- export function printSessionTable(sessions, hiddenCount = 0, tree = false, liveIndex) {
1738
- if (tree) {
1739
- const byDir = new Map();
1740
- for (const s of sessions) {
1741
- const key = s.cwd || s.project || 'unknown';
1742
- (byDir.get(key) ?? byDir.set(key, []).get(key)).push(s);
1743
- }
1744
- const keys = [...byDir.keys()].sort((a, b) => {
1745
- const d = byDir.get(b).length - byDir.get(a).length;
1746
- return d !== 0 ? d : a.localeCompare(b);
1747
- });
1748
- let first = true;
1749
- for (const key of keys) {
1750
- if (!first)
1751
- console.log();
1752
- first = false;
1753
- const group = byDir.get(key);
1754
- const cwd = group.find((s) => s.cwd && !s._remote)?.cwd;
1755
- const header = cwd ? linkPath(cwd, shortCwd(key)) : shortCwd(key);
1756
- console.log(`${chalk.cyan.bold(header)} ${chalk.gray(`(${group.length})`)}`);
1757
- for (const s of group)
1758
- console.log(treeSessionRow(s, liveIndex?.get(s.id)));
1759
- }
1760
- const dirWord = keys.length === 1 ? 'directory' : 'directories';
1761
- console.log(chalk.gray(`\n${sessions.length} session${sessions.length === 1 ? '' : 's'} across ${keys.length} ${dirWord}.`));
1762
- if (hiddenCount > 0)
1763
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1764
- return;
1765
- }
1766
- const showTicket = sessions.some((s) => ticketLabel(s) !== '');
1767
- const cols = pickerColumnsFor(sessions);
1768
- const bookmarks = listBookmarks();
1769
- for (const session of sessions) {
1770
- console.log(flatSessionRow(session, liveIndex?.get(session.id), showTicket, cols, bookmarks.has(session.id)));
1771
- }
1772
- const countLine = `${sessions.length} session${sessions.length === 1 ? '' : 's'}.`;
1773
- console.log(chalk.gray(`\n${countLine}`));
1774
- if (hiddenCount > 0) {
1775
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1776
- }
1777
- }
1778
1015
  const TEAM_MODE_W = 5;
1779
1016
  const TEAM_HANDLE_W = 16;
1780
1017
  function teamMemberRow(session, live) {
@@ -1861,354 +1098,6 @@ function printTeamsView(pool, liveIndex, hiddenUnmanaged = 0) {
1861
1098
  if (hiddenUnmanaged > 0)
1862
1099
  console.log(chalk.gray(formatUnmanagedHiddenFooter(hiddenUnmanaged)));
1863
1100
  }
1864
- function renderTopicCell(label, topic, query, visibleWidth, paddedWidth) {
1865
- const lbl = (label ?? '').trim();
1866
- const tpc = (topic ?? '').trim();
1867
- const sep = ' · ';
1868
- const raw = lbl && tpc ? `${lbl}${sep}${tpc}` : (lbl || tpc);
1869
- const visible = truncateToWidth(raw, visibleWidth);
1870
- const padding = ' '.repeat(Math.max(0, paddedWidth - stringWidth(visible)));
1871
- const labelEnd = lbl ? Math.min(lbl.length, visible.length) : 0;
1872
- let matchStart = -1, matchEnd = -1;
1873
- const q = query.trim().toLowerCase();
1874
- if (q) {
1875
- const lower = visible.toLowerCase();
1876
- for (const term of q.split(/\s+/).filter(Boolean)) {
1877
- const idx = lower.indexOf(term);
1878
- if (idx !== -1) {
1879
- matchStart = idx;
1880
- matchEnd = idx + term.length;
1881
- break;
1882
- }
1883
- }
1884
- }
1885
- const cuts = new Set([0, labelEnd, visible.length]);
1886
- if (matchStart >= 0) {
1887
- cuts.add(matchStart);
1888
- cuts.add(matchEnd);
1889
- }
1890
- const boundaries = [...cuts].sort((a, b) => a - b);
1891
- let out = '';
1892
- for (let i = 0; i < boundaries.length - 1; i++) {
1893
- const s = boundaries[i], e = boundaries[i + 1];
1894
- if (s >= e)
1895
- continue;
1896
- const text = visible.slice(s, e);
1897
- const isLabel = s < labelEnd;
1898
- const isMatch = matchStart >= 0 && s >= matchStart && e <= matchEnd;
1899
- out += (isMatch || isLabel) ? chalk.bold.white(text) : chalk.white(text);
1900
- }
1901
- return out + padding;
1902
- }
1903
- const PICKER_MACHINE_W = 11;
1904
- const PICKER_MACHINE_MIN = 8;
1905
- const PICKER_MACHINE_MAX = 18;
1906
- const PICKER_MODEL_MIN = 6;
1907
- const PICKER_MODEL_MAX = 13;
1908
- function machineColumnWidth(machines, label) {
1909
- const widest = machines.reduce((w, m) => Math.max(w, stringWidth(label(m))), 0);
1910
- return Math.min(PICKER_MACHINE_MAX, Math.max(PICKER_MACHINE_MIN, widest + 1));
1911
- }
1912
- function modelColumnWidth(sessions) {
1913
- const widest = sessions.reduce((width, session) => (Math.max(width, session.model ? stringWidth(modelLabel(session.model)) : 0)), 0);
1914
- return Math.min(PICKER_MODEL_MAX, Math.max(PICKER_MODEL_MIN, widest + 1));
1915
- }
1916
- export function machineLabeler(machines) {
1917
- const uniq = [...new Set(machines.filter(Boolean))];
1918
- if (uniq.length < 2)
1919
- return (m) => m;
1920
- const parts = uniq.map((m) => m.split('-'));
1921
- const min = Math.min(...parts.map((p) => p.length));
1922
- let shared = 0;
1923
- while (shared < min - 1 && parts.every((p) => p[shared] === parts[0][shared]))
1924
- shared++;
1925
- if (shared === 0)
1926
- return (m) => m;
1927
- return (m) => {
1928
- const p = m.split('-');
1929
- return p.length > shared ? p.slice(shared).join('-') : m;
1930
- };
1931
- }
1932
- export function pickerColumnsFor(sessions) {
1933
- const machines = sessions.map((s) => s.machine).filter((m) => !!m);
1934
- const distinct = [...new Set(machines)];
1935
- const machineLabel = machineLabeler(machines);
1936
- return {
1937
- showMachine: distinct.length > 1,
1938
- machineLabel,
1939
- machineWidth: machineColumnWidth(distinct, machineLabel),
1940
- showModel: sessions.some((s) => !!s.model),
1941
- modelWidth: modelColumnWidth(sessions),
1942
- showTicket: sessions.some((s) => ticketLabel(s) !== ''),
1943
- showBookmark: (() => {
1944
- const bookmarks = listBookmarks();
1945
- return bookmarks.size > 0 && sessions.some((s) => bookmarks.has(s.id));
1946
- })(),
1947
- };
1948
- }
1949
- const PICKER_HOST_W = 14;
1950
- export function liveHostLabel(a) {
1951
- if (!a?.host)
1952
- return '';
1953
- const viewer = a.viewingIn?.app;
1954
- return viewer && viewer !== a.host ? `${a.host}→${viewer}` : a.host;
1955
- }
1956
- export function formatPickerLabel(s, query, cols = {}, ssh, host = '', bookmarked = false, live) {
1957
- const shown = sessionDisplayAgent(s);
1958
- const agentColor = colorAgent(shown);
1959
- const age = sessionAgeParts(s.timestamp, s.lastActivity);
1960
- const project = s.project || '-';
1961
- const sshPlain = ssh ? (ssh.device ? `ssh←${ssh.device} ` : 'ssh ') : '';
1962
- const sshSeg = sshPlain ? chalk.red(sshPlain) : '';
1963
- const sshW = sshPlain ? stringWidth(sshPlain) : 0;
1964
- const team = teamBadge(s);
1965
- const teamSeg = team.plain ? chalk.green(team.plain) : '';
1966
- const tag = originTag(s) || teamTag(s);
1967
- const label = s.label;
1968
- const topic = tag ? `${tag}${s.topic ?? ''}` : s.topic;
1969
- const versionStr = s.version || '-';
1970
- const wt = s.worktreeSlug ? chalk.magenta(`wt:${s.worktreeSlug}`) : '';
1971
- const machineW = cols.machineWidth ?? PICKER_MACHINE_W;
1972
- const machineCell = cols.showMachine
1973
- ? chalk.gray(padRight(truncate((cols.machineLabel?.(s.machine ?? '') ?? s.machine ?? '') || '-', machineW - 1), machineW))
1974
- : '';
1975
- const TICKET_W = 10;
1976
- const ticketCell = cols.showTicket
1977
- ? chalk.blue(padRight(truncate(ticketLabel(s) || '-', TICKET_W), TICKET_W + 1))
1978
- : '';
1979
- const hostCell = cols.showHost
1980
- ? chalk.gray(padRight(truncate(host || '-', PICKER_HOST_W - 1), PICKER_HOST_W))
1981
- : '';
1982
- const gutter = cols.gutter ?? 2;
1983
- const machineColW = cols.showMachine ? machineW : 0;
1984
- const ticketW = cols.showTicket ? TICKET_W + 1 : 0;
1985
- const hostW = cols.showHost ? PICKER_HOST_W : 0;
1986
- const wtW = wt ? stringWidth(wt) + 1 : 0;
1987
- const bookmarkW = cols.showBookmark ? 2 : 0;
1988
- const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
1989
- const status = cols.showStatus ? liveStatusCell(live) : { cell: '', width: 0 };
1990
- const statusW = cols.showStatus ? LIVE_STATUS_W : 0;
1991
- const statusCell = cols.showStatus ? (status.cell || ' '.repeat(LIVE_STATUS_W)) : '';
1992
- const baseTopicW = terminalWidth() - gutter - bookmarkW - statusW - (10 + 9 + 8 + 16) - machineColW - hostW - ticketW - wtW - sshW - team.width - stringWidth(age.last) - 1;
1993
- const when = timeCell(age, baseTopicW);
1994
- const topicW = Math.max(MIN_TOPIC_W, baseTopicW - when.extraW);
1995
- return (bookmarkCell +
1996
- chalk.white(padRight(truncate(s.shortId, 9), 10)) +
1997
- agentColor(padRight(truncate(shown, 8), 9)) +
1998
- chalk.yellow(padRight(truncate(versionStr, 7), 8)) +
1999
- machineCell +
2000
- hostCell +
2001
- chalk.cyan(padRight(truncate(project, 14), 16)) +
2002
- statusCell +
2003
- sshSeg +
2004
- teamSeg +
2005
- renderTopicCell(label, topic, query, topicW, topicW) +
2006
- ticketCell +
2007
- (wt ? wt + ' ' : '') +
2008
- when.text);
2009
- }
2010
- const PICKER_TIPS = [
2011
- 'Tip: narrow with -a/--agent (e.g. -a codex), or --project <name> for another folder.',
2012
- "Tip: --all searches every directory; -D/--device <machine> folds in another box's sessions.",
2013
- 'Tip: just type to fuzzy-search prompts and responses; press space to preview a session.',
2014
- 'Tip: --since 2d / --until <date> bound the time window; pass a session id to open it directly.',
2015
- ];
2016
- export function formatPickerTip(sessions) {
2017
- return chalk.gray(PICKER_TIPS[sessions.length % PICKER_TIPS.length]);
2018
- }
2019
- export async function pickSessionInteractive(sessions, message = 'Search sessions:', initialSearch, hiddenCount = 0, enterHint, scope) {
2020
- let linesAbovePrompt = 0;
2021
- if (hiddenCount > 0) {
2022
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
2023
- linesAbovePrompt += 1;
2024
- }
2025
- const cols = pickerColumnsFor(sessions);
2026
- try {
2027
- return await sessionPicker({
2028
- message,
2029
- subtitle: formatPickerTip(sessions),
2030
- sessions,
2031
- filter: (query) => {
2032
- if (!query.trim())
2033
- return sessions;
2034
- return filterSessionsByQuery(sessions, query, scope);
2035
- },
2036
- labelFor: (s, query) => formatPickerLabel(s, query, cols),
2037
- pageSize: PICKER_RECENT_COUNT,
2038
- initialSearch,
2039
- enterHint,
2040
- linesAbovePrompt,
2041
- });
2042
- }
2043
- catch (err) {
2044
- if (isPromptCancelled(err))
2045
- return null;
2046
- throw err;
2047
- }
2048
- }
2049
- function warnNoPeerTarget(machine, session) {
2050
- console.log(chalk.yellow(`Session ${session.shortId} lives on ${machine}, which isn't a reachable device right now.`));
2051
- console.log(chalk.gray(`Register/wake it (ag devices), or run there: agents ssh ${machine}`));
2052
- }
2053
- export const LIVE_ROW_PREFIX = 'live:';
2054
- function isIdlessLiveRow(s) {
2055
- return s.id.startsWith(LIVE_ROW_PREFIX);
2056
- }
2057
- export async function handlePickedSession(picked) {
2058
- if (isIdlessLiveRow(picked.session)) {
2059
- const where = picked.session.machine ? ` on ${picked.session.machine}` : '';
2060
- console.log(chalk.yellow(`This session hasn't reported a session id yet — nothing to open${where}.`));
2061
- console.log(chalk.gray(`Watch for it with: agents sessions --active${picked.session.machine ? ` --device ${picked.session.machine}` : ''}`));
2062
- return;
2063
- }
2064
- if (picked.action === 'view') {
2065
- const readFrom = transcriptOnPeerOf(picked.session);
2066
- if (readFrom) {
2067
- const rc = await runOnPeer(['sessions', picked.session.shortId, '--markdown'], readFrom);
2068
- if (rc === 'no-target')
2069
- warnNoPeerTarget(readFrom, picked.session);
2070
- return;
2071
- }
2072
- await renderSession(picked.session, 'summary', {});
2073
- return;
2074
- }
2075
- if (await resumeOnOwnerIfRemote(picked.session))
2076
- return;
2077
- await resumeSessionInPlace(picked.session);
2078
- }
2079
- async function resumeOnOwnerIfRemote(session) {
2080
- const owner = sessionOwnerDevice(session);
2081
- if (!owner)
2082
- return false;
2083
- console.log(chalk.gray(`Resuming ${session.shortId} on ${owner} over SSH...`));
2084
- const rc = await runOnPeer(['sessions', 'resume', session.id], owner, {
2085
- tty: true,
2086
- env: { [RESUME_PINNED_ENV]: '1' },
2087
- sessionId: session.id,
2088
- });
2089
- if (rc === 'no-target')
2090
- warnNoPeerTarget(owner, session);
2091
- return true;
2092
- }
2093
- export async function resumeSessionInPlace(session) {
2094
- const owner = sessionOwnerDevice(session);
2095
- if (owner) {
2096
- console.error(chalk.red(`Session ${session.shortId} belongs to ${owner} — it cannot resume on this machine.`));
2097
- console.error(chalk.gray(` Resume it there: agents sessions resume ${session.id}`));
2098
- process.exitCode = 1;
2099
- return;
2100
- }
2101
- const cwd = session.cwd && fs.existsSync(session.cwd)
2102
- ? session.cwd
2103
- : process.cwd();
2104
- const resume = buildSessionRecoveryCommand(session);
2105
- console.log(chalk.gray(`Resuming: ${resume.join(' ')} (cwd: ${cwd})`));
2106
- await spawnResumeCommand(resume, cwd);
2107
- }
2108
- export function buildSessionRecoveryCommand(session, portable = false) {
2109
- const args = sessionRecoveryRunArgs(session);
2110
- if (portable)
2111
- return ['agents', ...args];
2112
- const invocation = getAgentsInvocation(args);
2113
- return [invocation.command, ...invocation.args];
2114
- }
2115
- export function resumeSpawnInvocation(cmd, platform = process.platform) {
2116
- const shell = needsWindowsShell(cmd[0], platform);
2117
- if (shell) {
2118
- return {
2119
- command: composeWin32CommandLine(cmd[0], cmd.slice(1)),
2120
- args: [],
2121
- shell: true,
2122
- };
2123
- }
2124
- return { command: cmd[0], args: cmd.slice(1), shell: false };
2125
- }
2126
- function spawnResumeCommand(cmd, cwd) {
2127
- return new Promise((resolve) => {
2128
- let child;
2129
- try {
2130
- const { command, args, shell } = resumeSpawnInvocation(cmd);
2131
- child = spawn(command, args, {
2132
- cwd,
2133
- stdio: 'inherit',
2134
- shell,
2135
- });
2136
- }
2137
- catch (err) {
2138
- console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
2139
- resolve();
2140
- return;
2141
- }
2142
- child.on('error', (err) => {
2143
- console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
2144
- if (err.code === 'ENOENT') {
2145
- console.error(chalk.gray(`Make sure '${cmd[0]}' is on your PATH.`));
2146
- }
2147
- resolve();
2148
- });
2149
- child.on('close', () => resolve());
2150
- });
2151
- }
2152
- function resumeArgv(agent, id, launcher) {
2153
- switch (agent) {
2154
- case 'claude': return [launcher, '--resume', id];
2155
- case 'codex': return [launcher, 'resume', id];
2156
- case 'opencode': return [launcher, '--session', id];
2157
- case 'muse': return [launcher, 'resume', id];
2158
- default: return null;
2159
- }
2160
- }
2161
- function versionedAliasIfPresent(agent, version) {
2162
- const cli = AGENTS[agent]?.cliCommand ?? agent;
2163
- const base = path.join(getShimsDir(), `${cli}@${version}`);
2164
- if (process.platform === 'win32' && fs.existsSync(`${base}.cmd`))
2165
- return `${base}.cmd`;
2166
- if (fs.existsSync(base))
2167
- return base;
2168
- return null;
2169
- }
2170
- export function buildResumeCommand(session) {
2171
- if (!sessionAgentSupportsResume(session.agent))
2172
- return null;
2173
- switch (session.agent) {
2174
- case 'opencode':
2175
- return resumeArgv('opencode', session.id, 'opencode');
2176
- case 'claude':
2177
- case 'codex':
2178
- case 'muse': {
2179
- const cli = AGENTS[session.agent]?.cliCommand ?? session.agent;
2180
- if (session.version) {
2181
- const alias = versionedAliasIfPresent(session.agent, session.version);
2182
- return resumeArgv(session.agent, session.id, alias ?? `${cli}@${session.version}`);
2183
- }
2184
- return resumeArgv(session.agent, session.id, cli);
2185
- }
2186
- default:
2187
- return null;
2188
- }
2189
- }
2190
- export function resolveSessionAgentName(name) {
2191
- const normalized = name.toLowerCase();
2192
- if (SESSION_AGENTS.includes(normalized)) {
2193
- return normalized;
2194
- }
2195
- const resolved = resolveAgentName(normalized);
2196
- if (resolved && SESSION_AGENTS.includes(resolved)) {
2197
- return resolved;
2198
- }
2199
- return fuzzyMatch(normalized, SESSION_AGENTS, FUZZY_PRESETS.agents);
2200
- }
2201
- export function parseAgentFilter(agentName) {
2202
- if (!agentName)
2203
- return {};
2204
- const [name, version] = agentName.split('@', 2);
2205
- const agent = resolveSessionAgentName(name);
2206
- if (!agent) {
2207
- console.error(chalk.red(`Unknown agent: ${name}. Use: ${SESSION_AGENTS.join(', ')}`));
2208
- process.exit(1);
2209
- }
2210
- return { agent, version };
2211
- }
2212
1101
  function formatSearchMessage(options) {
2213
1102
  const filters = [];
2214
1103
  if (options.agent)
@@ -2219,18 +1108,6 @@ function formatSearchMessage(options) {
2219
1108
  return 'Search sessions:';
2220
1109
  return `Search sessions (${filters.join(', ')}):`;
2221
1110
  }
2222
- export function resolveSessionQuery(pool, query, options = {}) {
2223
- const normalized = query.trim();
2224
- const completeId = isCompleteSessionId(normalized);
2225
- const byIdMatches = resolveSessionById(pool, normalized);
2226
- if (byIdMatches.length > 0)
2227
- return { matches: byIdMatches, byId: true, completeId };
2228
- if (looksLikeSessionId(normalized)) {
2229
- const matches = options.indexFallback === false ? [] : findSessionsById(normalized);
2230
- return { matches, byId: true, completeId };
2231
- }
2232
- return { matches: filterSessionsByQuery(pool, normalized, options.scope), byId: false, completeId };
2233
- }
2234
1111
  function ambiguityHint(byId, completeId) {
2235
1112
  if (completeId)
2236
1113
  return 'That is already a complete id — these rows share it as a prefix.';
@@ -2238,9 +1115,6 @@ function ambiguityHint(byId, completeId) {
2238
1115
  ? 'Pass a longer ID to narrow it down.'
2239
1116
  : 'That matched on text, not an id. Pass a session id, or narrow the search.';
2240
1117
  }
2241
- function notFoundByIdMessage(query) {
2242
- return [chalk.red(`No session with id ${query.trim()} on this machine.`)];
2243
- }
2244
1118
  export function fleetNotFoundMessage(query, deviceCount, unreachable) {
2245
1119
  const id = query.trim();
2246
1120
  if (deviceCount === 0) {
@@ -2256,142 +1130,6 @@ export function fleetNotFoundMessage(query, deviceCount, unreachable) {
2256
1130
  }
2257
1131
  return lines;
2258
1132
  }
2259
- export function filterSessionsByQuery(sessions, query, scope) {
2260
- const trimmed = query?.trim().toLowerCase() || '';
2261
- if (!trimmed)
2262
- return sessions;
2263
- const installedAgentVersion = parseInstalledAgentVersionQuery(trimmed);
2264
- if (installedAgentVersion) {
2265
- const { agent, version } = parseAgentFilter(installedAgentVersion);
2266
- return sessions.filter((session) => session.agent === agent && session.version === version);
2267
- }
2268
- const terms = trimmed.split(/\s+/).filter(Boolean);
2269
- const contentIndex = scopedContentIndex(sessions, trimmed, scope);
2270
- const EXACT_LABEL_SCORE = 1_000_000;
2271
- const exactLabelHits = [...contentIndex.values()].filter(s => (s._bm25Score ?? 0) >= EXACT_LABEL_SCORE);
2272
- if (exactLabelHits.length > 0) {
2273
- return exactLabelHits.sort((a, b) => (b._bm25Score ?? 0) - (a._bm25Score ?? 0));
2274
- }
2275
- const poolById = new Map(sessions.map(s => [s.id, s]));
2276
- for (const [id, hit] of contentIndex) {
2277
- if (!poolById.has(id))
2278
- poolById.set(id, hit);
2279
- }
2280
- return [...poolById.values()]
2281
- .map(session => ({ session, score: scoreSessionQuery(session, terms) }))
2282
- .filter(entry => {
2283
- if (entry.score > 0)
2284
- return true;
2285
- const contentMatch = contentIndex.get(entry.session.id);
2286
- if (contentMatch && contentMatch._matchedTerms && contentMatch._matchedTerms.length > 0) {
2287
- return true;
2288
- }
2289
- return false;
2290
- })
2291
- .sort((a, b) => {
2292
- if (b.score !== a.score)
2293
- return b.score - a.score;
2294
- const cmA = contentIndex.get(a.session.id);
2295
- const cmB = contentIndex.get(b.session.id);
2296
- const bmA = cmA?._bm25Score ?? 0;
2297
- const bmB = cmB?._bm25Score ?? 0;
2298
- if (bmB !== bmA)
2299
- return bmB - bmA;
2300
- return new Date(b.session.timestamp).getTime() - new Date(a.session.timestamp).getTime();
2301
- })
2302
- .map(entry => {
2303
- const cm = contentIndex.get(entry.session.id);
2304
- if (cm && cm._matchedTerms) {
2305
- return { ...cm };
2306
- }
2307
- return entry.session;
2308
- });
2309
- }
2310
- function scoreSessionQuery(session, terms) {
2311
- let score = 0;
2312
- for (const term of terms) {
2313
- const exactId = session.id.toLowerCase() === term || session.shortId.toLowerCase() === term;
2314
- const prefixId = session.id.toLowerCase().startsWith(term) || session.shortId.toLowerCase().startsWith(term);
2315
- const topic = session.topic?.toLowerCase() || '';
2316
- const project = session.project?.toLowerCase() || '';
2317
- const account = session.account?.toLowerCase() || '';
2318
- const cwd = session.cwd?.toLowerCase() || '';
2319
- const agent = session.agent.toLowerCase();
2320
- const version = session.version?.toLowerCase() || '';
2321
- let termScore = 0;
2322
- if (exactId)
2323
- termScore = 1000;
2324
- else if (prefixId)
2325
- termScore = 900;
2326
- else if (topic.startsWith(term))
2327
- termScore = 700;
2328
- else if (project.startsWith(term))
2329
- termScore = 600;
2330
- else if (account.startsWith(term))
2331
- termScore = 550;
2332
- else if (agent.startsWith(term) || version.startsWith(term))
2333
- termScore = 500;
2334
- else if (topic.includes(term))
2335
- termScore = 400;
2336
- else if (project.includes(term))
2337
- termScore = 300;
2338
- else if (account.includes(term))
2339
- termScore = 250;
2340
- else if (cwd.includes(term))
2341
- termScore = 200;
2342
- else if (version.includes(term) || agent.includes(term))
2343
- termScore = 150;
2344
- else
2345
- return 0;
2346
- score += termScore;
2347
- }
2348
- return score;
2349
- }
2350
- export function applyScopeFilters(sessions, scope) {
2351
- let filtered = sessions;
2352
- if (scope.project) {
2353
- const projectQuery = scope.project.toLowerCase();
2354
- filtered = filtered.filter((s) => {
2355
- const project = (s.project || '').toLowerCase();
2356
- const cwd = (s.cwd || '').toLowerCase();
2357
- return project.includes(projectQuery) || cwd.includes(projectQuery);
2358
- });
2359
- }
2360
- if (scope.agent) {
2361
- const [wantAgent, rawVersion] = scope.agent.split('@');
2362
- const resolvedAgent = resolveAgentName(wantAgent);
2363
- const wantVersion = resolvedAgent ? resolveVersionAliasLoose(resolvedAgent, rawVersion) : rawVersion;
2364
- filtered = filtered.filter((s) => {
2365
- if (s.agent !== wantAgent)
2366
- return false;
2367
- if (wantVersion && s.version !== wantVersion)
2368
- return false;
2369
- return true;
2370
- });
2371
- }
2372
- if (scope.routine) {
2373
- filtered = filtered.filter((session) => session.origin === 'routine');
2374
- if (typeof scope.routine === 'string') {
2375
- const names = [...new Set(filtered.map((session) => session.routineName).filter((name) => !!name))];
2376
- const selected = resolveRoutineName(scope.routine, names);
2377
- filtered = selected
2378
- ? filtered.filter((session) => session.routineName === selected)
2379
- : [];
2380
- }
2381
- }
2382
- return filtered;
2383
- }
2384
- function scopedContentIndex(sessions, query, scope) {
2385
- const hits = searchContentIndex(sessions, query);
2386
- if (!scope || (!scope.agent && !scope.project && !scope.routine))
2387
- return hits;
2388
- const kept = new Map();
2389
- for (const [id, session] of hits) {
2390
- if (applyScopeFilters([session], scope).length > 0)
2391
- kept.set(id, session);
2392
- }
2393
- return kept;
2394
- }
2395
1133
  export function artifactLookupScope(agent, project, routine) {
2396
1134
  return { agent, project, routine };
2397
1135
  }
@@ -2591,189 +1329,6 @@ function modeFlag(mode) {
2591
1329
  return '--json';
2592
1330
  return undefined;
2593
1331
  }
2594
- 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;
2595
- const SHORT_SESSION_ID_RE = /^[0-9a-f]{8}$/i;
2596
- export function isDefinitiveMatch(session, selector) {
2597
- const trimmed = selector.trim();
2598
- if (FULL_SESSION_ID_RE.test(trimmed)) {
2599
- return session.id.toLowerCase() === trimmed.toLowerCase();
2600
- }
2601
- const shortId = shortIdFromName(trimmed) ?? (SHORT_SESSION_ID_RE.test(trimmed) ? trimmed : undefined);
2602
- return !!shortId && session.shortId.toLowerCase() === shortId.toLowerCase();
2603
- }
2604
- export function selectorAllowsEarlyExit(selector) {
2605
- const trimmed = selector.trim();
2606
- return FULL_SESSION_ID_RE.test(trimmed) || isAgentTmuxAlias(trimmed) || SHORT_SESSION_ID_RE.test(trimmed);
2607
- }
2608
- export function fleetCandidatesByQuery(rows, query, trustResolvedRows = false) {
2609
- const matched = !trustResolvedRows && looksLikeSessionId(query)
2610
- ? resolveSessionQuery(rows, query, { indexFallback: false }).matches
2611
- : rows;
2612
- const byId = new Map();
2613
- for (const session of matched) {
2614
- const machine = session.machine;
2615
- if (!machine)
2616
- continue;
2617
- const logicalId = session.id.toLowerCase();
2618
- let byMachine = byId.get(logicalId);
2619
- if (!byMachine) {
2620
- byMachine = new Map();
2621
- byId.set(logicalId, byMachine);
2622
- }
2623
- if (!byMachine.has(machine))
2624
- byMachine.set(machine, session);
2625
- }
2626
- return Array.from(byId.values()).map(byMachine => {
2627
- const hits = Array.from(byMachine.entries()).map(([machine, session]) => ({ machine, session }));
2628
- return { id: hits[0].session.id, hits };
2629
- });
2630
- }
2631
- function resolveIndexedMetadataRows(indexed, selector, scope) {
2632
- const alias = resolveSessionAlias(selector);
2633
- if (alias.kind === 'resolved') {
2634
- return resolveSessionQuery(indexed, alias.sessionId, { indexFallback: false, scope }).matches;
2635
- }
2636
- if (alias.kind === 'ambiguous') {
2637
- const ids = new Set(alias.sessionIds.map(id => id.toLowerCase()));
2638
- return indexed.filter(session => ids.has(session.id.toLowerCase()));
2639
- }
2640
- return resolveSessionQuery(indexed, selector, { indexFallback: false, scope }).matches;
2641
- }
2642
- function indexedRowsForSelector(selector, scope) {
2643
- const indexed = looksLikeSessionId(selector)
2644
- ? findSessionsById(selector)
2645
- : querySessions();
2646
- return applyScopeFilters(indexed, scope);
2647
- }
2648
- export function metadataResolveForwardedArgs(selector, scope) {
2649
- const args = ['sessions', '--resolve-safe-v1', selector, '--json', '--all', '--local'];
2650
- if (scope.agent)
2651
- args.push('--agent', scope.agent);
2652
- if (scope.project)
2653
- args.push('--project', scope.project);
2654
- return args;
2655
- }
2656
- export function toolSearchForwardedArgs(argv, hosts) {
2657
- const args = ensureWholeIndex(buildForwardedArgs(argv, new Set(hosts)).filter((arg) => arg !== '--fleet'));
2658
- if (!args.includes('--json'))
2659
- args.push('--json');
2660
- if (!args.includes('--local'))
2661
- args.push('--local');
2662
- return args;
2663
- }
2664
- const SHORT_SESSION_ID_WIDTH = 8;
2665
- export function isUniqueEnoughSelector(selector) {
2666
- const trimmed = selector.trim();
2667
- if (isCompleteSessionId(trimmed))
2668
- return true;
2669
- return /^[0-9a-f-]+$/i.test(trimmed)
2670
- && trimmed.replace(/-/g, '').length >= SHORT_SESSION_ID_WIDTH;
2671
- }
2672
- export function metadataResolveOutcome(localMatches, remote, selector) {
2673
- const candidates = fleetCandidatesByQuery([...localMatches, ...remote.sessions], selector, true);
2674
- if (isUniqueEnoughSelector(selector) && candidates.length === 1) {
2675
- return { kind: 'resolved', session: candidates[0].hits[0].session };
2676
- }
2677
- if (remote.unreachable.length > 0)
2678
- return { kind: 'partial', failedPeers: remote.unreachable };
2679
- if (candidates.length === 0)
2680
- return { kind: 'not-found' };
2681
- if (candidates.length > 1)
2682
- return { kind: 'ambiguous', candidates };
2683
- return { kind: 'resolved', session: candidates[0].hits[0].session };
2684
- }
2685
- export function isLocallyDefinitiveMatch(session, self) {
2686
- if (session.filePath)
2687
- return true;
2688
- return !!session.machine && session.machine !== self;
2689
- }
2690
- export function preferOwnerAttribution(localMatches, remoteSessions, self) {
2691
- if (remoteSessions.length === 0)
2692
- return localMatches;
2693
- const answeredByPeer = new Set(remoteSessions.map(session => session.id.toLowerCase()));
2694
- return localMatches.filter(session => isLocallyDefinitiveMatch(session, self) || !answeredByPeer.has(session.id.toLowerCase()));
2695
- }
2696
- export async function computeLocalMetadataMatches(selector, scope, deps = {}) {
2697
- const localMachine = machineId();
2698
- const includeLocal = !scope.hosts?.length || shouldIncludeLocal(scope.hosts, localMachine);
2699
- if (!includeLocal)
2700
- return [];
2701
- let indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
2702
- if (!looksLikeSessionId(selector)) {
2703
- return indexed.map(session => ({ ...session, machine: session.machine || localMachine }));
2704
- }
2705
- const { hydrateSessionTranscript, findLocalSessionTranscripts } = await import('../lib/session/discover.js');
2706
- if (indexed.length === 0) {
2707
- const disk = await findLocalSessionTranscripts(selector, scope.agent);
2708
- const live = disk.length ? [] : await liveMetadataMatches(selector, scope, localMachine, deps);
2709
- if (disk.length > 0)
2710
- indexed = resolveIndexedMetadataRows(disk, selector, scope);
2711
- else if (live.length > 0)
2712
- indexed = live;
2713
- else if (scope.agent !== 'claude' && scope.agent !== 'codex') {
2714
- const { scanSessionsIncremental, waitForScanToSettle } = await import('../lib/session/discover.js');
2715
- const { claimed } = await scanSessionsIncremental({ agent: scope.agent });
2716
- if (!claimed) {
2717
- if (!await waitForScanToSettle())
2718
- throw new Error('Session lookup is incomplete: another index scan is still running. Retry when it finishes.');
2719
- const retry = await scanSessionsIncremental({ agent: scope.agent });
2720
- if (!retry.claimed)
2721
- throw new Error('Session lookup is incomplete: the session index is busy. Retry when the scan finishes.');
2722
- }
2723
- indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
2724
- }
2725
- }
2726
- const hydrated = [];
2727
- for (const session of indexed) {
2728
- hydrated.push(await hydrateSessionTranscript({ ...session, machine: session.machine || localMachine }));
2729
- }
2730
- return hydrated;
2731
- }
2732
- export async function liveMetadataMatches(selector, scope, self, deps = {}) {
2733
- const load = deps.loadActive ?? loadLocalActiveSessions;
2734
- const loadFleet = deps.loadFleetActive ?? (() => readActiveSessionsCache('fleet')?.sessions ?? []);
2735
- let fleetExecMachine;
2736
- try {
2737
- fleetExecMachine = fleetExecutionMachineById(loadFleet());
2738
- }
2739
- catch {
2740
- fleetExecMachine = new Map();
2741
- }
2742
- const match = (metas) => resolveIndexedMetadataRows(applyScopeFilters(reconcileLiveMetaMachine(metas, fleetExecMachine, self), scope), selector, scope);
2743
- try {
2744
- const cached = liveSessionMetas((await load()).sessions, self, Date.now());
2745
- const hit = match(cached);
2746
- if (hit.length > 0)
2747
- return hit;
2748
- const fresh = liveSessionMetas((await load({ forceRefresh: true })).sessions, self, Date.now());
2749
- return match(fresh);
2750
- }
2751
- catch {
2752
- return [];
2753
- }
2754
- }
2755
- export async function resolveSessionMetadataValue(selector, scope = {}, deps = { gatherRemoteList }) {
2756
- const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
2757
- const localMachine = machineId();
2758
- if (FULL_SESSION_ID_RE.test(selector)) {
2759
- const localOutcome = metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
2760
- if (localOutcome.kind === 'resolved' && isLocallyDefinitiveMatch(localOutcome.session, localMachine)) {
2761
- return localOutcome;
2762
- }
2763
- }
2764
- if (scope.local === true)
2765
- return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
2766
- try {
2767
- const forwarded = metadataResolveForwardedArgs(selector, scope);
2768
- const remote = await deps.gatherRemoteList(forwarded, scope.hosts, selectorAllowsEarlyExit(selector)
2769
- ? { isDefinitive: (session) => isDefinitiveMatch(session, selector) }
2770
- : undefined);
2771
- return metadataResolveOutcome(preferOwnerAttribution(localMatches, remote.sessions, localMachine), remote, selector);
2772
- }
2773
- catch (error) {
2774
- return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [error?.message ?? 'fleet fan-out'] }, selector);
2775
- }
2776
- }
2777
1332
  export async function resolveSessionMetadata(selector, scope, deps = { gatherRemoteList }) {
2778
1333
  const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
2779
1334
  if (process.env[NO_FANOUT_ENV] === '1') {
@@ -2855,7 +1410,7 @@ export function registerSessionsCommands(program) {
2855
1410
  const sessionsCmd = program
2856
1411
  .command('sessions')
2857
1412
  .argument('[query]', 'Session ID, search query, or path (., ../, /path) to filter by project')
2858
- .option('--query <clause>', 'Search text; repeat with --include tools to require distinct matching calls', collectQueryClause, [])
1413
+ .option('--query <text>', 'Search text (same as the positional query)', collectQueryClause, [])
2859
1414
  .option('--resolve <selector>', 'Resolve one full ID, unique prefix, or keyword query to safe session metadata (requires --json; searches the fleet unless --local)')
2860
1415
  .addOption(new Option('--resolve-safe-v1 <selector>').hideHelp())
2861
1416
  .addOption(new Option('--resolve-launch-id <id>').hideHelp())
@@ -2885,7 +1440,7 @@ export function registerSessionsCommands(program) {
2885
1440
  .option('--markdown', 'Render the session as markdown (user, assistant, thinking, tool calls)')
2886
1441
  .option('--no-redact', 'Disable default secret redaction in rendered session output (--markdown and --json)')
2887
1442
  .option('--json', 'Output JSON (session list when browsing, event array when rendering one session)')
2888
- .option('--include <roles>', 'Only include these roles (comma-separated): user, assistant, thinking, tools. "user" is genuine user turns only, not harness-injected scaffolding (bash-input, system-reminder)')
1443
+ .option('--include <roles>', 'Only include these roles (comma-separated): user, assistant, thinking, tools. "user" is genuine user turns only, not harness-injected scaffolding (bash-input, system-reminder). Tool-call search across sessions is `sessions --include tools`')
2889
1444
  .option('--exclude <roles>', 'Exclude these roles (comma-separated): user, assistant, thinking, tools')
2890
1445
  .option('--first <n>', 'Keep only the first N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
2891
1446
  .option('--last <n>', 'Keep only the last N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
@@ -2910,10 +1465,6 @@ export function registerSessionsCommands(program) {
2910
1465
  .option('--cloud', 'Source sessions from Rush Cloud (captured runs) instead of local disk')
2911
1466
  .option('-D, --device <target...>', 'Run this query on remote machine(s) over SSH (device alias from `agents devices`, user@host, or `all` to search the whole fleet; repeatable)')
2912
1467
  .addOption(new Option('--devices <target...>', 'Plural alias for --device (accepts `all`/`fleet`).').hideHelp())
2913
- .option('--fleet', 'With --include tools: query every registered online compute device and merge compact matches')
2914
- .option('--count', 'With one program:<name> tool query: count static occurrences, containing calls, and sessions')
2915
- .option('--browser', 'List browser-profile captures (screenshots, PDFs, recordings, downloads) instead of agent transcripts — alias of `agents browser sessions`')
2916
- .option('--computer', 'List computer-driving history, grouped by run, instead of agent transcripts — alias of `agents computer sessions`')
2917
1468
  .option('--no-interactive', 'Print the listing instead of opening the interactive browser (default on a TTY for the bare listing and --active)')
2918
1469
  .option('--print-cmd', 'Print the canonical `ag sessions …` command for the given flags and exit (the twin of the browser’s `y` hotkey)')
2919
1470
  .option('--preview', 'With a session id/query: print a compact preview and exit (no pager)');
@@ -2977,16 +1528,8 @@ export function registerSessionsCommands(program) {
2977
1528
  # Export for analysis
2978
1529
  agents sessions --since 30d --limit 200 --json > sessions.json
2979
1530
 
2980
- # List indexed tool calls in recent Codex sessions on one device
2981
- agents sessions --include tools --agent codex --device mac-mini --since 7d
2982
-
2983
- # Each repeated clause must match a different call in the same session
2984
- agents sessions --include tools --query 'program:git input:merge' --query 'program:gh output:CONFLICT' --fleet --json
2985
-
2986
- # Count every pre-indexed static git site without reparsing transcripts
2987
- agents sessions --include tools --query 'program:git' --count --fleet --json
2988
-
2989
- # Explicitly populate historical tool rows once on every device
1531
+ # Populate historical tool rows once on every device (search them with
1532
+ # the standalone CLI: sessions --include tools --query 'program:git')
2990
1533
  agents sessions backfill tools --fleet
2991
1534
 
2992
1535
  # Resolve one historical selector to metadata only, across the fleet
@@ -3010,11 +1553,7 @@ export function registerSessionsCommands(program) {
3010
1553
  - --device runs the query on the remote's own index over SSH (host alias or user@host); repeat or pass several to fan out. SSH access is the only auth.
3011
1554
  - --in-team matches both ends of the lineage: the session that ran 'agents teams create/add', and (with --teams) that team's teammates. In the interactive list, 't' cycles the same filter over the teams in view.
3012
1555
  - --include and --exclude are mutually exclusive.
3013
- - With --include tools, repeat --query for same-session AND across distinct calls. Fields: tool, program, input, output, status, exit, error.
3014
- - --count accepts exactly one program:<name> clause and reports static source occurrences, containing tool calls, and sessions.
3015
- - Tool queries read SQLite only. Run 'agents sessions backfill tools' once for historical transcripts; normal scans index new and changed sessions.
3016
- - Tool evidence is redacted and bounded before it reaches SQLite. --markdown and --no-redact conflict with --include tools.
3017
- - Tool queries accept 32 clauses (4 KiB each), --limit 1–1,000, and at most 8 MiB of materialized evidence.
1556
+ - Tool-call search and --count run in the standalone \`sessions\` CLI (\`sessions --include tools --query <clause>\`). agents indexes the calls: run 'agents sessions backfill tools' once for historical transcripts; normal scans index new and changed sessions.
3018
1557
  - --first and --last are mutually exclusive.
3019
1558
  - A filter flag (--include/--exclude/--first/--last) without --markdown/--json defaults to --markdown output.
3020
1559
  - --cloud sources from Rush Cloud captured runs instead of local disk.
@@ -3023,77 +1562,9 @@ export function registerSessionsCommands(program) {
3023
1562
  `,
3024
1563
  });
3025
1564
  sessionsCmd.action(async (query, options, command) => {
3026
- if (options.browser) {
3027
- await runBrowserSessionsCommand({ profile: query, json: options.json, interactive: options.interactive });
3028
- return;
3029
- }
3030
- if (options.computer) {
3031
- const limit = options.limit === undefined ? undefined : Number.parseInt(options.limit, 10);
3032
- const deviceArgs = [...(options.device ?? []), ...(options.devices ?? [])];
3033
- const allFleet = deviceArgs.some((host) => ['all', 'fleet'].includes(host.toLowerCase()));
3034
- const hosts = [...(options.host ?? []), ...deviceArgs]
3035
- .filter((host) => !['all', 'fleet'].includes(host.toLowerCase()));
3036
- if (hosts.length > 0 || allFleet) {
3037
- const remoteRows = await gatherRemoteComputerSessionRows(allFleet ? undefined : hosts);
3038
- const rows = allFleet
3039
- ? [...buildComputerSessionRows({ machine: query }), ...remoteRows]
3040
- : remoteRows;
3041
- rows.sort((a, b) => b.endMs - a.endMs);
3042
- await runComputerSessionsCommand({ rows, machine: query, limit, json: options.json, interactive: options.interactive });
3043
- return;
3044
- }
3045
- await runComputerSessionsCommand({ machine: query, limit, json: options.json, interactive: options.interactive });
3046
- return;
3047
- }
3048
1565
  await sessionsAction(query, options, command.getOptionValueSource('limit'));
3049
1566
  });
3050
- const previewCmd = sessionsCmd
3051
- .command('preview')
3052
- .argument('<id>', 'Full session ID or displayed 8-character short ID')
3053
- .description('Show one rich session card without rendering the full transcript')
3054
- .option('-a, --agent <agent>', 'Narrow the ID to one agent type/version')
3055
- .option('-p, --project <name>', 'Narrow the ID to one project')
3056
- .option('--local', 'Only this machine; do not resolve the ID across the fleet')
3057
- .option('-D, --device <target...>', 'Resolve only on the named device(s)')
3058
- .option('--json', 'Output the session preview as JSON')
3059
- .option('--refresh', 'Bypass the durable remote-preview cache and negative backoff for one bounded fetch (full ID + single --device only)')
3060
- .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)');
3061
- setHelpSections(previewCmd, {
3062
- examples: `
3063
- # Preview by the 8-character ID shown in agents sessions
3064
- agents sessions preview 407b8dd5
3065
-
3066
- # A full UUID resolves on the first device that owns it
3067
- agents sessions preview c70ecdea-6210-4039-9845-246a3a7a9942
3068
-
3069
- # Stay on this machine or restrict the authoritative lookup to one peer
3070
- agents sessions preview 407b8dd5 --local
3071
- agents sessions preview 407b8dd5 --device zion
3072
-
3073
- # Full ID + one --device: durable-cached fast path (PHNX-3999); force a fresh fetch
3074
- agents sessions preview c70ecdea-6210-4039-9845-246a3a7a9942 --device zion --json --refresh
3075
- `,
3076
- notes: `
3077
- - Full UUIDs are globally unique and may stop the fleet lookup at the first exact hit.
3078
- - Short IDs wait for every selected device so ambiguity is never hidden.
3079
- - Active status is refreshed through the bounded live-state TTL; transcript-derived details use the durable session index.
3080
- - 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.
3081
- `,
3082
- });
3083
- previewCmd.action(async (id) => {
3084
- const options = previewCmd.optsWithGlobals();
3085
- const hosts = [...(options.host ?? []), ...(options.device ?? [])];
3086
- await renderSessionPreview(id, {
3087
- agent: options.agent,
3088
- project: options.project,
3089
- local: options.local,
3090
- hosts: hosts.length > 0 ? hosts : undefined,
3091
- json: options.json,
3092
- refresh: options.refresh,
3093
- revision: options.revision,
3094
- });
3095
- });
3096
- registerSessionsTailCommand(sessionsCmd);
1567
+ registerSessionPreviewCommand(sessionsCmd, 'sessions');
3097
1568
  registerSessionsResumeCommand(sessionsCmd);
3098
1569
  registerSessionsForkCommand(sessionsCmd);
3099
1570
  registerSessionsBookmarkCommand(sessionsCmd);
@@ -3129,10 +1600,6 @@ function formatUnmanagedHiddenFooter(hiddenCount) {
3129
1600
  const noun = hiddenCount === 1 ? 'session' : 'sessions';
3130
1601
  return `(${hiddenCount} ${noun} from your own unmanaged installs hidden — use --unmanaged to show)`;
3131
1602
  }
3132
- function formatTeamHiddenFooter(hiddenCount) {
3133
- const noun = hiddenCount === 1 ? 'team session' : 'team sessions';
3134
- return `(${hiddenCount} ${noun} hidden — use --teams to show, or \`agents teams status\`)`;
3135
- }
3136
1603
  function findClaudeHistoryEntry(idQuery) {
3137
1604
  const historyPath = path.join(os.homedir(), '.claude', 'history.jsonl');
3138
1605
  if (!fs.existsSync(historyPath))