@phnx-labs/agents-cli 1.23.17 → 1.23.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +140 -165
  3. package/dist/bootstrap.js +11 -17
  4. package/dist/cli/command-registry.d.ts +1 -2
  5. package/dist/cli/command-registry.js +1 -10
  6. package/dist/commands/accounts.js +7 -7
  7. package/dist/commands/cloud-transcripts.d.ts +0 -1
  8. package/dist/commands/cloud-transcripts.js +2 -2
  9. package/dist/commands/cloud.js +2 -2
  10. package/dist/commands/config.js +1 -5
  11. package/dist/commands/cost.js +1 -1
  12. package/dist/commands/daemon-index.js +0 -1
  13. package/dist/commands/detach.d.ts +1 -1
  14. package/dist/commands/detach.js +10 -6
  15. package/dist/commands/doctor.js +11 -7
  16. package/dist/commands/exec.d.ts +0 -17
  17. package/dist/commands/exec.js +26 -72
  18. package/dist/commands/feed.d.ts +1 -1
  19. package/dist/commands/feed.js +3 -3
  20. package/dist/commands/focus.d.ts +11 -6
  21. package/dist/commands/focus.js +91 -31
  22. package/dist/commands/fork.d.ts +0 -1
  23. package/dist/commands/fork.js +7 -16
  24. package/dist/commands/harness-wizard.js +1 -1
  25. package/dist/commands/harness.js +1 -1
  26. package/dist/commands/insights.d.ts +0 -1
  27. package/dist/commands/insights.js +3 -7
  28. package/dist/commands/open.js +1 -1
  29. package/dist/commands/output.js +1 -1
  30. package/dist/commands/profiles.d.ts +1 -1
  31. package/dist/commands/profiles.js +2 -2
  32. package/dist/commands/projects-todo.js +10 -5
  33. package/dist/commands/projects.js +1 -1
  34. package/dist/commands/prune.js +1 -1
  35. package/dist/commands/ps.d.ts +8 -3
  36. package/dist/commands/ps.js +238 -110
  37. package/dist/commands/routines.js +1 -1
  38. package/dist/commands/send.js +1 -1
  39. package/dist/commands/sessions-backfill.d.ts +0 -1
  40. package/dist/commands/sessions-backfill.js +3 -6
  41. package/dist/commands/sessions-browser.d.ts +0 -10
  42. package/dist/commands/sessions-browser.js +19 -25
  43. package/dist/commands/sessions-migrate.d.ts +2 -2
  44. package/dist/commands/sessions-migrate.js +13 -13
  45. package/dist/commands/sessions-optimize.d.ts +0 -1
  46. package/dist/commands/sessions-optimize.js +0 -3
  47. package/dist/commands/sessions-picker.d.ts +0 -7
  48. package/dist/commands/sessions-picker.js +16 -310
  49. package/dist/commands/sessions-resume.d.ts +16 -15
  50. package/dist/commands/sessions-resume.js +101 -269
  51. package/dist/commands/sessions-stats.d.ts +0 -1
  52. package/dist/commands/sessions-stats.js +5 -8
  53. package/dist/commands/sessions-stop.d.ts +1 -1
  54. package/dist/commands/sessions-stop.js +8 -8
  55. package/dist/commands/sessions-trace.d.ts +1 -1
  56. package/dist/commands/sessions-trace.js +40 -17
  57. package/dist/commands/sessions-watch.js +2 -2
  58. package/dist/commands/sessions.test-fixture.d.ts +1 -0
  59. package/dist/commands/sessions.test-fixture.js +14 -0
  60. package/dist/commands/setup-browser.js +4 -4
  61. package/dist/commands/setup-computer.js +4 -4
  62. package/dist/commands/setup-fleet.js +1 -1
  63. package/dist/commands/setup-preferences.js +1 -1
  64. package/dist/commands/{sessions-backup-setup.d.ts → setup-session-backup.d.ts} +2 -2
  65. package/dist/commands/{sessions-backup-setup.js → setup-session-backup.js} +8 -8
  66. package/dist/commands/setup.js +3 -1
  67. package/dist/commands/ssh.js +4 -5
  68. package/dist/commands/sync.js +1 -1
  69. package/dist/commands/teams.js +2 -2
  70. package/dist/commands/utils.d.ts +0 -1
  71. package/dist/commands/utils.js +0 -10
  72. package/dist/index.js +0 -71
  73. package/dist/lib/account-registry.d.ts +3 -0
  74. package/dist/lib/account-registry.js +40 -0
  75. package/dist/lib/accounting/usage-sync.d.ts +1 -0
  76. package/dist/lib/accounting/usage-sync.js +20 -3
  77. package/dist/lib/accounting/usage.d.ts +4 -1
  78. package/dist/lib/accounting/usage.js +38 -6
  79. package/dist/lib/agent-spec/agents.js +12 -11
  80. package/dist/lib/analytics/mix-commands.js +1 -1
  81. package/dist/lib/auth-mint.js +2 -2
  82. package/dist/lib/browser-client.d.ts +0 -1
  83. package/dist/lib/browser-client.js +0 -3
  84. package/dist/lib/cloud/antigravity.js +1 -1
  85. package/dist/lib/cloud/cursor.js +3 -3
  86. package/dist/lib/cloud/store.d.ts +5 -1
  87. package/dist/lib/cloud/store.js +10 -3
  88. package/dist/lib/cloudflare/creds.js +2 -2
  89. package/dist/lib/computer/context.d.ts +4 -21
  90. package/dist/lib/computer/context.js +3 -24
  91. package/dist/lib/computer/policy.d.ts +0 -10
  92. package/dist/lib/computer/policy.js +0 -28
  93. package/dist/lib/computer-client.d.ts +0 -44
  94. package/dist/lib/computer-client.js +17 -121
  95. package/dist/lib/config-keys.d.ts +2 -2
  96. package/dist/lib/config-keys.js +1 -3
  97. package/dist/lib/crabbox/cli.js +1 -1
  98. package/dist/lib/daemon/account-state-daemon-service.js +9 -2
  99. package/dist/lib/daemon/self-update-service.js +1 -1
  100. package/dist/lib/device-config.d.ts +2 -1
  101. package/dist/lib/device-config.js +26 -39
  102. package/dist/lib/devices/connect.d.ts +1 -1
  103. package/dist/lib/devices/connect.js +3 -6
  104. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  105. package/dist/lib/devices/doctor-findings.js +4 -4
  106. package/dist/lib/devices/health.d.ts +6 -0
  107. package/dist/lib/devices/health.js +11 -4
  108. package/dist/lib/exec.js +1 -1
  109. package/dist/lib/feed/activity.js +1 -1
  110. package/dist/lib/feed/watch.js +2 -1
  111. package/dist/lib/fleet/apply.d.ts +1 -1
  112. package/dist/lib/fleet/apply.js +6 -3
  113. package/dist/lib/fleet-shared-state.d.ts +2 -0
  114. package/dist/lib/fleet-shared-state.js +3 -1
  115. package/dist/lib/github/project-prs.js +14 -1
  116. package/dist/lib/help.d.ts +0 -1
  117. package/dist/lib/help.js +2 -10
  118. package/dist/lib/helper-versions.js +1 -1
  119. package/dist/lib/hosts/option.js +1 -1
  120. package/dist/lib/hosts/passthrough.d.ts +0 -1
  121. package/dist/lib/hosts/passthrough.js +2 -26
  122. package/dist/lib/hosts/reconnect.js +5 -5
  123. package/dist/lib/hosts/remote-cmd.d.ts +3 -5
  124. package/dist/lib/hosts/remote-cmd.js +15 -20
  125. package/dist/lib/hosts/remote-session-id.js +1 -1
  126. package/dist/lib/installations/active-check.js +1 -1
  127. package/dist/lib/installations/migrate.js +4 -15
  128. package/dist/lib/installations/versions.js +5 -4
  129. package/dist/lib/launch-log.js +3 -6
  130. package/dist/lib/owner-notify.d.ts +1 -6
  131. package/dist/lib/owner-notify.js +0 -2
  132. package/dist/lib/paths.d.ts +0 -1
  133. package/dist/lib/paths.js +0 -8
  134. package/dist/lib/permissions.js +1 -1
  135. package/dist/lib/project-root.d.ts +1 -0
  136. package/dist/lib/project-root.js +11 -3
  137. package/dist/lib/projects.js +2 -2
  138. package/dist/lib/quick-todo.d.ts +5 -1
  139. package/dist/lib/quick-todo.js +14 -1
  140. package/dist/lib/redact.d.ts +0 -1
  141. package/dist/lib/redact.js +0 -4
  142. package/dist/lib/remote-agents-json.d.ts +3 -1
  143. package/dist/lib/remote-agents-json.js +12 -8
  144. package/dist/lib/reserved-stores.js +1 -1
  145. package/dist/lib/scheduling/routines.d.ts +0 -1
  146. package/dist/lib/scheduling/routines.js +1 -1
  147. package/dist/lib/self-update.d.ts +1 -1
  148. package/dist/lib/self-update.js +59 -2
  149. package/dist/lib/session/active.d.ts +1 -1
  150. package/dist/lib/session/db.js +4 -4
  151. package/dist/lib/session/detached.d.ts +0 -1
  152. package/dist/lib/session/detached.js +0 -23
  153. package/dist/lib/session/discover.d.ts +2 -2
  154. package/dist/lib/session/glance-files.d.ts +21 -0
  155. package/dist/lib/session/glance-files.js +123 -0
  156. package/dist/lib/session/presentation.d.ts +3 -7
  157. package/dist/lib/session/presentation.js +4 -4
  158. package/dist/lib/session/preview-digest.d.ts +13 -0
  159. package/dist/lib/session/preview-digest.js +328 -0
  160. package/dist/lib/session/projection.js +1 -1
  161. package/dist/lib/session/remote/remote-list.d.ts +5 -2
  162. package/dist/lib/session/remote/remote-list.js +15 -8
  163. package/dist/lib/session/remote/watch.d.ts +2 -0
  164. package/dist/lib/session/remote/watch.js +90 -10
  165. package/dist/lib/session/remote-active.js +1 -1
  166. package/dist/lib/session/resume-command.d.ts +0 -1
  167. package/dist/lib/session/resume-command.js +1 -4
  168. package/dist/lib/session/resume-owner.d.ts +0 -2
  169. package/dist/lib/session/resume-owner.js +0 -6
  170. package/dist/lib/session/selection.d.ts +4 -5
  171. package/dist/lib/session/selection.js +2 -2
  172. package/dist/lib/session/sync/config.d.ts +0 -25
  173. package/dist/lib/session/sync/config.js +0 -62
  174. package/dist/lib/session/sync/managed-config.d.ts +0 -1
  175. package/dist/lib/session/sync/managed-config.js +0 -3
  176. package/dist/lib/session/sync/worker-template.js +1 -1
  177. package/dist/lib/sessions-client.d.ts +0 -16
  178. package/dist/lib/sessions-client.js +1 -187
  179. package/dist/lib/smart-launch.js +6 -1
  180. package/dist/lib/startup/command-registry.d.ts +2 -0
  181. package/dist/lib/startup/command-registry.js +36 -3
  182. package/dist/lib/startup/root-command.d.ts +0 -1
  183. package/dist/lib/startup/root-command.js +0 -21
  184. package/dist/lib/sync-umbrella.js +1 -1
  185. package/dist/lib/teams/placement-probe.d.ts +2 -0
  186. package/dist/lib/teams/placement-probe.js +8 -3
  187. package/dist/lib/terminal/engine.d.ts +2 -0
  188. package/dist/lib/terminal/engine.js +5 -3
  189. package/dist/lib/terminal/index.d.ts +1 -1
  190. package/dist/lib/terminal/index.js +1 -1
  191. package/dist/lib/terminal/resolve.js +1 -1
  192. package/dist/lib/terminal/run-surface.d.ts +1 -0
  193. package/dist/lib/terminal/run-surface.js +9 -0
  194. package/dist/lib/watchdog/rotate.js +1 -1
  195. package/dist/lib/watchdog/watchdog.d.ts +1 -1
  196. package/dist/lib/watchdog/watchdog.js +2 -2
  197. package/package.json +1 -1
  198. package/dist/commands/browser.d.ts +0 -7
  199. package/dist/commands/browser.js +0 -139
  200. package/dist/commands/computer.d.ts +0 -48
  201. package/dist/commands/computer.js +0 -244
  202. package/dist/commands/resume.d.ts +0 -23
  203. package/dist/commands/resume.js +0 -158
  204. package/dist/commands/secrets-passthrough.d.ts +0 -3
  205. package/dist/commands/secrets-passthrough.js +0 -52
  206. package/dist/commands/sessions-bookmark.d.ts +0 -2
  207. package/dist/commands/sessions-bookmark.js +0 -92
  208. package/dist/commands/sessions-export.d.ts +0 -31
  209. package/dist/commands/sessions-export.js +0 -409
  210. package/dist/commands/sessions-import.d.ts +0 -6
  211. package/dist/commands/sessions-import.js +0 -343
  212. package/dist/commands/sessions-inject.d.ts +0 -14
  213. package/dist/commands/sessions-inject.js +0 -143
  214. package/dist/commands/sessions-picker-factory.d.ts +0 -24
  215. package/dist/commands/sessions-picker-factory.js +0 -59
  216. package/dist/commands/sessions-render.d.ts +0 -11
  217. package/dist/commands/sessions-render.js +0 -119
  218. package/dist/commands/sessions-share.d.ts +0 -15
  219. package/dist/commands/sessions-share.js +0 -171
  220. package/dist/commands/sessions.d.ts +0 -122
  221. package/dist/commands/sessions.js +0 -1760
  222. package/dist/lib/address.d.ts +0 -39
  223. package/dist/lib/address.js +0 -128
  224. package/dist/lib/computer/record.d.ts +0 -6
  225. package/dist/lib/computer/record.js +0 -25
  226. package/dist/lib/onepassword.d.ts +0 -57
  227. package/dist/lib/onepassword.js +0 -140
  228. package/dist/lib/openclaw-keychain.d.ts +0 -43
  229. package/dist/lib/openclaw-keychain.js +0 -227
  230. package/dist/lib/session/bundle.d.ts +0 -76
  231. package/dist/lib/session/bundle.js +0 -146
  232. package/dist/lib/session/remote/remote-bundle.d.ts +0 -7
  233. package/dist/lib/session/remote/remote-bundle.js +0 -40
  234. package/dist/lib/session/remote/remote.d.ts +0 -35
  235. package/dist/lib/session/remote/remote.js +0 -198
  236. package/dist/lib/session/remote-bundle.d.ts +0 -1
  237. package/dist/lib/session/remote-bundle.js +0 -1
  238. package/dist/lib/session/remote.d.ts +0 -1
  239. package/dist/lib/session/remote.js +0 -1
  240. package/dist/lib/session/sync/agents.d.ts +0 -24
  241. package/dist/lib/session/sync/agents.js +0 -0
  242. package/dist/lib/session/sync/backend.d.ts +0 -22
  243. package/dist/lib/session/sync/backend.js +0 -44
  244. package/dist/lib/session/sync/managed-key.d.ts +0 -5
  245. package/dist/lib/session/sync/managed-key.js +0 -87
  246. package/dist/lib/session/sync/net-client.d.ts +0 -29
  247. package/dist/lib/session/sync/net-client.js +0 -87
  248. package/dist/lib/session/sync/r2.d.ts +0 -20
  249. package/dist/lib/session/sync/r2.js +0 -103
  250. package/dist/lib/session/sync/transcript-crypto.d.ts +0 -41
  251. package/dist/lib/session/sync/transcript-crypto.js +0 -115
@@ -1,1760 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as os from 'os';
3
- import * as path from 'path';
4
- import { Option } from 'commander';
5
- import chalk from 'chalk';
6
- import { padRight, humanDuration, formatBytes } from '../lib/format.js';
7
- import { resolveProjectKey } from '../lib/project-key.js';
8
- import { listProjectDefs, resolveProjectNameForCwd } from '../lib/projects.js';
9
- import ora from 'ora';
10
- import { interruptibleSpinner } from '../lib/spinner.js';
11
- import { SESSION_AGENTS, sessionDisplayAgent } from '@phnx-labs/sessions-cli/reader';
12
- import { discoverArtifacts, readArtifact, resolveArtifact } from '@phnx-labs/sessions-cli/reader';
13
- import { looksLikePath, toComparablePath } from '../lib/platform/index.js';
14
- import { getActiveSessions, serializeSessionsJson } from '../lib/session/active.js';
15
- export { activeSessionProjectKey, backfillActiveRowsFromIndex, backfillActiveRowsFromMeta, isRunningLiveSession, serializeActiveSessionsForJson, serializeSessionsJson } from '../lib/session/active.js';
16
- import { viewingInLabel } from '../lib/session/viewing-in.js';
17
- import { machineId } from '../lib/session/sync/config.js';
18
- import { NO_FANOUT_ENV } from '../lib/session/remote-active.js';
19
- import { gatherRemoteList, runOnPeer, shouldIncludeLocal } from '../lib/session/remote-list.js';
20
- import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
21
- import { discoverSessions, countSessionsInScope, resolveSessionById, looksLikeSessionId, getSessionRoots } from '../lib/session/discover.js';
22
- import { sessionHeadline } from '../lib/session/title.js';
23
- import { filterTeamSessions, shouldShowTeamSessions, safeTeamText, groupSessionsByTeam, NO_TEAM_GROUP_KEY, } from '@phnx-labs/sessions-cli/reader';
24
- import { runRemoteSessions, buildForwardedArgs, ensureWholeIndex } from '../lib/session/remote.js';
25
- import { formatRelativeTime, sessionAgeParts } from '../lib/session/relative-time.js';
26
- import { shortenModel, formatTokenCount } from '@phnx-labs/sessions-cli/reader';
27
- import { colorAgent } from '../lib/agents.js';
28
- import { listJobs, listJobsWithRuns, listRuns, getRunDir } from '../lib/scheduling/routines.js';
29
- import { formatUsd } from '../lib/pricing/cost.js';
30
- import { itemPicker } from '../lib/picker.js';
31
- import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
32
- import { transcriptOnPeerOf, handlePickedSession, pickSessionInteractive, } from './sessions-picker.js';
33
- import { setHelpSections } from '../lib/help.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';
37
- export { buildFilterOptions, renderSession, renderSessionLog, renderSessionLogJson, resolveViewMode, } from '../lib/session/presentation.js';
38
- import { applyScopeFilters, computeLocalMetadataMatches, filterSessionsByQuery, fleetCandidatesByQuery, isDefinitiveMatch, matchesTeam, mergeLocalFirst, parseAgentFilter, parseInstalledAgentVersionQuery, resolveSessionMetadataValue, resolveSessionQuery, scopedContentIndex, selectorAllowsEarlyExit, serializeResolvedSessionsJson, } from '../lib/session/selection.js';
39
- import { registerSessionPreviewCommand, renderSessionPreview } from './ps.js';
40
- import { registerSessionsResumeCommand } from './sessions-resume.js';
41
- import { registerSessionsForkCommand } from './fork.js';
42
- import { registerSessionsBookmarkCommand } from './sessions-bookmark.js';
43
- import { listBookmarks } from '../lib/session/bookmarks.js';
44
- import { registerFocusCommand } from './focus.js';
45
- import { registerDetachCommand } from './detach.js';
46
- import { registerSessionsStopCommand } from './sessions-stop.js';
47
- import { registerSessionsInjectCommand } from './sessions-inject.js';
48
- import { registerSessionsExportCommand } from './sessions-export.js';
49
- import { registerSessionsRenderCommand } from './sessions-render.js';
50
- import { registerSessionsTraceCommand } from './sessions-trace.js';
51
- import { registerSessionsShareCommand } from './sessions-share.js';
52
- import { registerSessionsImportCommand } from './sessions-import.js';
53
- import { registerSessionsBackupSetupCommand } from './sessions-backup-setup.js';
54
- import { registerSessionsMigrateCommand, registerSessionsMigrationsCommand } from './sessions-migrate.js';
55
- import { registerSessionsBackfillCommand } from './sessions-backfill.js';
56
- import { registerSessionsStatsCommand } from './sessions-stats.js';
57
- import { registerSessionsInsightsCommand } from './insights.js';
58
- import { registerSessionsOptimizeCommand } from './sessions-optimize.js';
59
- import { registerSessionsWatchCommand } from './sessions-watch.js';
60
- const SESSION_AGENT_FILTER_HELP = `Filter by agent, e.g. claude, codex, claude@2.0.65`;
61
- function collectQueryClause(value, previous) {
62
- return [...previous, value];
63
- }
64
- const AGENT_SHORTHANDS = ['claude', 'codex', 'kimi', 'antigravity', 'grok', 'opencode'];
65
- function applyAgentShorthands(options) {
66
- if (options.agent)
67
- return;
68
- const hit = AGENT_SHORTHANDS.find((name) => options[name] === true);
69
- if (hit)
70
- options.agent = hit;
71
- }
72
- function applyVersionFilters(query, options) {
73
- const explicitVersion = options.version ?? options.sessionVersion;
74
- if (explicitVersion) {
75
- if (!options.agent) {
76
- throw new Error('--version requires --agent (for example: --agent claude --version 2.1.181).');
77
- }
78
- if (options.agent.includes('@')) {
79
- throw new Error('Pass the version either in --agent <agent@version> or with --version, not both.');
80
- }
81
- options.agent = `${options.agent}@${explicitVersion}`;
82
- }
83
- if (!options.agent) {
84
- const positionalFilter = parseInstalledAgentVersionQuery(query);
85
- if (positionalFilter) {
86
- options.agent = positionalFilter;
87
- return undefined;
88
- }
89
- }
90
- return query;
91
- }
92
- const CLAUDE_RESUME_MATCH_WINDOW_MS = 10 * 60_000;
93
- const LOAD_VERBS = ['Loading', 'Scanning', 'Gathering', 'Indexing', 'Reading'];
94
- const FIND_VERBS = ['Finding', 'Searching', 'Locating', 'Matching'];
95
- function createScanProgressTracker(verbs, suffix, spinner) {
96
- const counts = new Map();
97
- let verbIndex = 0;
98
- const render = () => {
99
- if (!spinner)
100
- return;
101
- const verb = verbs[verbIndex % verbs.length];
102
- const parts = [];
103
- for (const agent of SESSION_AGENTS) {
104
- const c = counts.get(agent);
105
- if (!c || c.total === 0)
106
- continue;
107
- parts.push(`${agent} ${c.parsed}/${c.total}`);
108
- }
109
- const base = `${verb} ${suffix}...`;
110
- spinner.text = parts.length > 0 ? `${base} (${parts.join(' · ')})` : base;
111
- };
112
- const interval = spinner
113
- ? setInterval(() => {
114
- verbIndex++;
115
- render();
116
- }, 900)
117
- : null;
118
- render();
119
- return {
120
- onProgress: (progress) => {
121
- counts.set(progress.agent, { parsed: progress.parsed, total: progress.total });
122
- render();
123
- },
124
- stop: () => {
125
- if (interval)
126
- clearInterval(interval);
127
- },
128
- };
129
- }
130
- const DEFAULT_LIMIT = '50';
131
- const WHOLE_TEAM_POOL_LIMIT = 5000;
132
- const OVERVIEW_ROWS_PER_PROJECT = 5;
133
- const OVERVIEW_POOL_LIMIT = 1000;
134
- const OVERVIEW_MAX_PROJECTS = 12;
135
- function resolvePathFilter(query) {
136
- const expanded = query.startsWith('~')
137
- ? path.join(os.homedir(), query.slice(1))
138
- : query;
139
- return path.resolve(expanded);
140
- }
141
- async function renderArtifactsForSession(session, listAll, name) {
142
- const artifacts = discoverArtifacts(session);
143
- if (name !== undefined) {
144
- const artifact = resolveArtifact(artifacts, name);
145
- if (!artifact) {
146
- console.error(chalk.red(`No artifact matching "${name}" in session ${session.shortId}.`));
147
- if (artifacts.length > 0) {
148
- console.error(chalk.gray('Available artifacts:'));
149
- for (const a of artifacts) {
150
- console.error(chalk.gray(` ${a.path}`));
151
- }
152
- }
153
- process.exit(1);
154
- }
155
- if (!artifact.exists) {
156
- console.error(chalk.red(`Artifact exists in session history but the file is no longer on disk: ${artifact.path}`));
157
- process.exit(1);
158
- }
159
- process.stdout.write(readArtifact(artifact));
160
- return;
161
- }
162
- if (artifacts.length === 0) {
163
- console.log(chalk.gray('No file-write artifacts found in this session.'));
164
- return;
165
- }
166
- const shown = sessionDisplayAgent(session);
167
- const agentColor = colorAgent(shown);
168
- console.log('');
169
- console.log(agentColor(shown) +
170
- chalk.gray(` · ${session.shortId} · ${formatRelativeTime(session.timestamp)}`));
171
- console.log(chalk.gray('─'.repeat(72)));
172
- for (const a of artifacts) {
173
- const exists = a.exists ? chalk.green('yes') : chalk.red('no');
174
- const size = a.exists && a.sizeBytes !== undefined ? chalk.cyan(formatBytes(a.sizeBytes)) : chalk.gray('-');
175
- const tool = chalk.yellow(padRight(a.tool, 10));
176
- const when = chalk.gray(formatRelativeTime(a.timestamp));
177
- const p = chalk.white(a.path);
178
- console.log(` ${exists} ${size.padEnd(10)} ${tool} ${when.padEnd(16)} ${p}`);
179
- }
180
- console.log(chalk.gray(`\n${artifacts.length} artifact${artifacts.length !== 1 ? 's' : ''}.`));
181
- }
182
- function contextColor(context) {
183
- switch (context) {
184
- case 'terminal': return chalk.magenta;
185
- case 'teams': return chalk.cyan;
186
- case 'cloud': return chalk.blue;
187
- case 'headless': return chalk.gray;
188
- }
189
- }
190
- function formatStartedAt(startedAtMs) {
191
- if (!startedAtMs)
192
- return '-';
193
- return formatRelativeTime(new Date(startedAtMs).toISOString());
194
- }
195
- export function serializeSessionPickerRows(sessions, liveSessions, self = machineId()) {
196
- const liveById = new Map(liveSessions.filter((row) => row.sessionId).map((row) => [row.sessionId, row]));
197
- return sessions.map((session) => {
198
- const live = liveById.get(session.id);
199
- const sourceDevice = live?.machine ?? session.machine ?? self;
200
- const viewingIn = live ? viewingInLabel(live) ?? null : null;
201
- const resumable = buildResumeCommand(session) !== null;
202
- return {
203
- ...session,
204
- state: live?.status ?? 'inactive',
205
- resumable,
206
- unwatched: !viewingIn,
207
- viewingIn,
208
- sourceDevice,
209
- lastActivityMs: live?.lastActivityMs ?? Date.parse(session.lastActivity ?? session.timestamp),
210
- pid: live?.pid ?? null,
211
- recovery: resumable
212
- ? { command: 'agents', args: ['sessions', 'resume', session.id, '--device', sourceDevice], ...(session.cwd ? { cwd: session.cwd } : {}) }
213
- : null,
214
- };
215
- });
216
- }
217
- async function runRemoteSessionsJson(hosts) {
218
- const forwarded = ensureWholeIndex(buildForwardedArgs(process.argv, new Set(hosts)));
219
- if (!forwarded.includes('--json'))
220
- forwarded.push('--json');
221
- const { sessions } = await gatherRemoteList(forwarded, hosts);
222
- process.stdout.write(serializeSessionsJson(sessions));
223
- }
224
- function useInteractiveBrowser(options) {
225
- return options.interactive !== false && !options.json && isInteractiveTerminal();
226
- }
227
- function isBareBrowserListing(options, query) {
228
- return (useInteractiveBrowser(options) &&
229
- process.env.AGENTS_SESSIONS_LOCAL !== '1' &&
230
- hasNoBrowserDisqualifyingFlags(options, query));
231
- }
232
- export function hasNoBrowserDisqualifyingFlags(options, query) {
233
- return (!query &&
234
- (!options.teams || !!options.inTeam) &&
235
- !options.flat &&
236
- !options.tree &&
237
- !options.markdown &&
238
- !options.until &&
239
- !options.project &&
240
- !options.skill &&
241
- !options.plugin &&
242
- !options.sort &&
243
- !options.routine &&
244
- !options.artifacts &&
245
- options.artifact === undefined &&
246
- !options.cloud &&
247
- (options.host?.length ?? 0) <= 1);
248
- }
249
- export function buildRoutineRunGroups(sessions) {
250
- const byRun = new Map();
251
- for (const session of sessions) {
252
- const runId = session.routineRunId ?? session.timestamp;
253
- (byRun.get(runId) ?? byRun.set(runId, []).get(runId)).push(session);
254
- }
255
- return [...byRun.entries()]
256
- .map(([runId, rows]) => ({
257
- runId,
258
- timestamp: rows.reduce((latest, row) => (row.lastActivity ?? row.timestamp) > latest ? (row.lastActivity ?? row.timestamp) : latest, rows[0].lastActivity ?? rows[0].timestamp),
259
- sessions: rows.sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1)),
260
- }))
261
- .sort((a, b) => (a.timestamp < b.timestamp ? 1 : a.timestamp > b.timestamp ? -1 : a.runId.localeCompare(b.runId)));
262
- }
263
- export function buildRoutineChoices(sessions, runOnlyNames = []) {
264
- const byName = new Map();
265
- for (const session of sessions) {
266
- if (!session.routineName)
267
- continue;
268
- (byName.get(session.routineName) ?? byName.set(session.routineName, []).get(session.routineName)).push(session);
269
- }
270
- const choices = [...byName.entries()]
271
- .map(([name, rows]) => {
272
- const runs = buildRoutineRunGroups(rows);
273
- return {
274
- name,
275
- lastRunAt: runs[0].timestamp,
276
- runCount: runs.length,
277
- latestRunSessionCount: runs[0].sessions.length,
278
- };
279
- });
280
- const seen = new Set(choices.map((c) => c.name));
281
- for (const name of runOnlyNames) {
282
- if (seen.has(name))
283
- continue;
284
- const runs = listRuns(name);
285
- const latest = runs[runs.length - 1];
286
- choices.push({
287
- name,
288
- lastRunAt: latest?.startedAt ?? '',
289
- runCount: runs.length,
290
- latestRunSessionCount: 0,
291
- });
292
- }
293
- return choices.sort((a, b) => (a.lastRunAt < b.lastRunAt ? 1 : a.lastRunAt > b.lastRunAt ? -1 : a.name.localeCompare(b.name)));
294
- }
295
- async function selectRoutineName(sessions) {
296
- const choices = buildRoutineChoices(sessions, safeListJobsWithRuns());
297
- const picked = await itemPicker({
298
- message: 'Select a routine:',
299
- items: choices,
300
- filter: (query) => {
301
- const normalized = query.trim().toLowerCase();
302
- if (!normalized)
303
- return choices;
304
- return choices.filter((choice) => choice.name.toLowerCase().includes(normalized));
305
- },
306
- labelFor: (choice) => {
307
- const runs = `${choice.runCount} run${choice.runCount === 1 ? '' : 's'}`;
308
- const sessions = `${choice.latestRunSessionCount} session${choice.latestRunSessionCount === 1 ? '' : 's'} in latest`;
309
- const age = choice.lastRunAt ? ` · ${formatRelativeTime(choice.lastRunAt)}` : '';
310
- return `${choice.name} ${chalk.gray(`${runs} · ${sessions}${age}`)}`;
311
- },
312
- shortIdFor: (choice) => choice.name,
313
- emptyMessage: 'No routines match.',
314
- enterHint: 'show sessions',
315
- });
316
- return picked?.item.name ?? null;
317
- }
318
- function safeListJobsWithRuns() {
319
- try {
320
- return [...new Set([...listJobs().map((job) => job.name), ...listJobsWithRuns()])];
321
- }
322
- catch {
323
- return [];
324
- }
325
- }
326
- async function selectRoutineTarget(sessions, routine, interactive) {
327
- const routineNames = [...new Set([
328
- ...sessions.map((session) => session.routineName).filter((name) => !!name),
329
- ...safeListJobsWithRuns(),
330
- ])].sort((a, b) => a.localeCompare(b));
331
- if (typeof routine === 'string') {
332
- const resolved = resolveRoutineName(routine, routineNames);
333
- if (!resolved) {
334
- console.error(chalk.red(`No routine matches "${routine}".`));
335
- if (routineNames.length > 0)
336
- console.error(chalk.gray(`Available routines: ${routineNames.join(', ')}`));
337
- process.exitCode = 1;
338
- return null;
339
- }
340
- return { name: resolved };
341
- }
342
- if (interactive) {
343
- const picked = await selectRoutineName(sessions);
344
- if (!picked)
345
- return null;
346
- return { name: picked };
347
- }
348
- return { name: null };
349
- }
350
- export async function filterSessionsByRoutine(sessions, routine, interactive) {
351
- const target = await selectRoutineTarget(sessions, routine, interactive);
352
- if (!target)
353
- return null;
354
- return target.name
355
- ? sessions.filter((session) => session.routineName === target.name)
356
- : sessions;
357
- }
358
- export function executionKind(meta) {
359
- if (meta.workflow)
360
- return 'workflow';
361
- if (meta.agent)
362
- return 'agent';
363
- return 'command';
364
- }
365
- function buildRoutineDrilldown(name, sessions) {
366
- const runs = listRuns(name);
367
- const forRoutine = sessions.filter((s) => s.routineName === name);
368
- const byRun = new Map();
369
- for (const s of forRoutine) {
370
- const rid = s.routineRunId ?? s.timestamp;
371
- (byRun.get(rid) ?? byRun.set(rid, []).get(rid)).push(s);
372
- }
373
- const runIds = new Set(runs.map((r) => r.runId));
374
- const entries = runs
375
- .map((meta) => ({
376
- meta,
377
- sessions: (byRun.get(meta.runId) ?? []).sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1)),
378
- }))
379
- .sort((a, b) => {
380
- const at = a.meta.startedAt || a.meta.runId;
381
- const bt = b.meta.startedAt || b.meta.runId;
382
- return at < bt ? 1 : at > bt ? -1 : b.meta.runId.localeCompare(a.meta.runId);
383
- });
384
- const orphanSessions = buildRoutineRunGroups(forRoutine.filter((s) => !runIds.has(s.routineRunId ?? s.timestamp)));
385
- return {
386
- name,
387
- runs: entries,
388
- orphanSessions,
389
- runRecordCount: runs.length,
390
- linkedSessionCount: forRoutine.length,
391
- isAgentRoutine: runs.some((r) => executionKind(r) !== 'command') || forRoutine.length > 0,
392
- };
393
- }
394
- function runStatusCell(status) {
395
- switch (status) {
396
- case 'completed': return `${chalk.green('✓')} ${chalk.green('completed')}`;
397
- case 'running': return `${chalk.cyan('◍')} ${chalk.cyan('running')}`;
398
- case 'failed': return `${chalk.red('✗')} ${chalk.red('failed')}`;
399
- case 'timeout': return `${chalk.red('✗')} ${chalk.red('timeout')}`;
400
- case 'blocked': return `${chalk.yellow('⚠')} ${chalk.yellow('blocked')}`;
401
- case 'skipped': return `${chalk.gray('↷')} ${chalk.gray('skipped')}`;
402
- case 'missed': return `${chalk.gray('·')} ${chalk.gray('missed')}`;
403
- default: return chalk.gray(status);
404
- }
405
- }
406
- function runPlacement(meta) {
407
- if (meta.host)
408
- return `host:${meta.host}`;
409
- if (meta.cloudProvider)
410
- return `cloud:${meta.cloudProvider}`;
411
- return 'local';
412
- }
413
- function runTrigger(meta) {
414
- const kind = meta.triggerKind ?? 'schedule';
415
- const who = meta.triggeredBy && !meta.triggeredBy.startsWith('UNRESOLVED') ? ` by ${meta.triggeredBy}` : '';
416
- return `${kind}${who}`;
417
- }
418
- function runOutcomeDetail(meta) {
419
- if (meta.status === 'skipped' && meta.skipReason) {
420
- const ref = meta.activeRunId ? ` → ${meta.activeRunId}` : '';
421
- return `${meta.skipReason.replace(/_/g, ' ')}${ref}`;
422
- }
423
- if (meta.status === 'blocked') {
424
- return meta.readiness ? `${meta.readiness.code}: ${meta.readiness.message}` : (meta.errorMessage ?? 'not ready');
425
- }
426
- if (meta.status === 'missed')
427
- return 'daemon down at fire time';
428
- if (meta.errorMessage)
429
- return meta.errorMessage;
430
- if (typeof meta.exitCode === 'number' && meta.exitCode !== 0)
431
- return `exit ${meta.exitCode}`;
432
- return '';
433
- }
434
- function linkedSessionMeta(session) {
435
- const parts = [];
436
- const shown = sessionDisplayAgent(session);
437
- parts.push(session.version ? `${shown} v${session.version}` : shown);
438
- if (session.account)
439
- parts.push(session.account);
440
- if (session.model)
441
- parts.push(shortenModel(session.model));
442
- if (typeof session.outputTokens === 'number')
443
- parts.push(`${formatTokenCount(session.outputTokens)} out`);
444
- else if (typeof session.tokenCount === 'number')
445
- parts.push(`${formatTokenCount(session.tokenCount)} tok`);
446
- if (typeof session.costUsd === 'number' && session.costUsd > 0)
447
- parts.push(formatUsd(session.costUsd));
448
- if (typeof session.durationMs === 'number' && session.durationMs > 0)
449
- parts.push(humanDuration(session.durationMs));
450
- if (typeof session.toolCallCount === 'number')
451
- parts.push(`${session.toolCallCount} tools`);
452
- return chalk.gray(' ' + parts.join(' · '));
453
- }
454
- export function printRoutineDrilldown(drill, liveIndex, opts = {}) {
455
- const runWord = drill.runRecordCount === 1 ? 'run record' : 'run records';
456
- const sessWord = drill.linkedSessionCount === 1 ? 'linked session' : 'linked sessions';
457
- console.log(`${chalk.cyan.bold(drill.name)} ` +
458
- chalk.gray(`${drill.runRecordCount} ${runWord} · ${drill.linkedSessionCount} ${sessWord}`));
459
- if (!drill.isAgentRoutine) {
460
- console.log(chalk.gray('Command routine — runs execute a shell command; no agent session is produced.'));
461
- }
462
- console.log();
463
- if (drill.runs.length === 0 && drill.orphanSessions.length === 0) {
464
- console.log(chalk.gray('No run records yet for this routine.'));
465
- return;
466
- }
467
- for (const entry of drill.runs) {
468
- const m = entry.meta;
469
- console.log(`${chalk.cyan('▸')} ${chalk.cyan.bold(m.runId)} ` +
470
- `${runStatusCell(m.status)} ` +
471
- chalk.gray(`${runTrigger(m)} · ${formatRelativeTime(m.startedAt)}`));
472
- const kind = executionKind(m);
473
- const detailParts = [kind];
474
- if (typeof m.duration === 'number' && m.duration > 0)
475
- detailParts.push(humanDuration(m.duration));
476
- detailParts.push(runPlacement(m));
477
- const outcome = runOutcomeDetail(m);
478
- if (outcome)
479
- detailParts.push(outcome);
480
- console.log(chalk.gray(' ' + detailParts.join(' · ')));
481
- const runDir = getRunDir(drill.name, m.runId);
482
- const logHints = [];
483
- if (fs.existsSync(path.join(runDir, 'stdout.log')))
484
- logHints.push(`log: ${path.join(runDir, 'stdout.log')}`);
485
- if (fs.existsSync(path.join(runDir, 'report.md')))
486
- logHints.push(`report: ${path.join(runDir, 'report.md')}`);
487
- if (logHints.length > 0)
488
- console.log(chalk.gray(' ' + logHints.join(' · ')));
489
- if (entry.sessions.length > 0) {
490
- for (const session of entry.sessions) {
491
- console.log(treeSessionRow(session, liveIndex?.get(session.id)));
492
- console.log(linkedSessionMeta(session));
493
- }
494
- }
495
- else if (kind !== 'command') {
496
- console.log(chalk.gray(' no agent session archived for this run'));
497
- }
498
- console.log();
499
- }
500
- if (drill.orphanSessions.length > 0) {
501
- console.log(chalk.gray('Sessions with no local run record (run archived on another host):'));
502
- for (const group of drill.orphanSessions) {
503
- console.log(`${chalk.cyan('▸')} ${chalk.cyan.bold(group.runId)} ` +
504
- chalk.gray(`${group.sessions.length} session${group.sessions.length === 1 ? '' : 's'} · ${formatRelativeTime(group.timestamp)}`));
505
- for (const session of group.sessions) {
506
- console.log(treeSessionRow(session, liveIndex?.get(session.id)));
507
- console.log(linkedSessionMeta(session));
508
- }
509
- console.log();
510
- }
511
- }
512
- console.log(chalk.gray(`Run history from .history/runs/${drill.name}/ · resume a session with agents sessions resume <id>.`));
513
- if (opts.hiddenCount && opts.hiddenCount > 0)
514
- console.log(chalk.gray(formatTeamHiddenFooter(opts.hiddenCount)));
515
- if (opts.hiddenUnmanaged && opts.hiddenUnmanaged > 0)
516
- console.log(chalk.gray(formatUnmanagedHiddenFooter(opts.hiddenUnmanaged)));
517
- }
518
- function canonicalSessionsCommand(query, options) {
519
- const a = ['sessions'];
520
- if (options.active)
521
- a.push('--active');
522
- if (options.working)
523
- a.push('--working');
524
- if (options.idle)
525
- a.push('--idle');
526
- if (options.orphan || options.orphaned)
527
- a.push('--orphan');
528
- if (options.crashed)
529
- a.push('--crashed');
530
- if (options.closed)
531
- a.push('--closed');
532
- if (options.abandoned)
533
- a.push('--abandoned');
534
- if (options.queued)
535
- a.push('--queued');
536
- if (options.unknown)
537
- a.push('--unknown');
538
- if (options.teams)
539
- a.push('--teams');
540
- if (options.inTeam)
541
- a.push('--in-team', options.inTeam);
542
- if (options.routine) {
543
- a.push('--routine');
544
- if (typeof options.routine === 'string')
545
- a.push(options.routine);
546
- }
547
- if (options.agent)
548
- a.push('-a', options.agent);
549
- for (const h of options.host ?? [])
550
- a.push('--device', h);
551
- if (options.project)
552
- a.push('--project', options.project);
553
- if (options.skill)
554
- a.push('--skill', options.skill);
555
- if (options.plugin)
556
- a.push('--plugin', options.plugin);
557
- if (options.all)
558
- a.push('--all');
559
- if (options.since)
560
- a.push('--since', options.since);
561
- if (options.until)
562
- a.push('--until', options.until);
563
- if (options.local)
564
- a.push('--local');
565
- if (options.waiting)
566
- a.push('--waiting');
567
- if (options.bookmarks)
568
- a.push('--bookmarks');
569
- const q = (query ?? '').trim();
570
- if (q)
571
- a.push(JSON.stringify(q));
572
- return 'ag ' + a.join(' ');
573
- }
574
- async function sessionsAction(query, options, limitSource) {
575
- const liveStatuses = requestedLiveStatuses(options);
576
- const liveOnly = options.active === true || liveStatuses.length > 0;
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;
583
- return;
584
- }
585
- const queryClauses = options.query ?? [];
586
- if (queryClauses.length > 1) {
587
- console.error(chalk.red('Pass --query once.'));
588
- process.exitCode = 1;
589
- return;
590
- }
591
- query = query ?? queryClauses[0];
592
- applyAgentShorthands(options);
593
- try {
594
- query = applyVersionFilters(query, options);
595
- }
596
- catch (error) {
597
- console.error(chalk.red(error instanceof Error ? error.message : String(error)));
598
- process.exitCode = 1;
599
- return;
600
- }
601
- const rawDeviceTargets = [...(options.device ?? []), ...(options.devices ?? [])];
602
- const fleetWide = rawDeviceTargets.some(t => t.toLowerCase() === 'all' || t.toLowerCase() === 'fleet');
603
- const deviceTargets = rawDeviceTargets
604
- .filter(t => t.toLowerCase() !== 'all' && t.toLowerCase() !== 'fleet');
605
- if (deviceTargets.length > 0) {
606
- options.host = [...(options.host ?? []), ...deviceTargets];
607
- }
608
- if (options.printCmd) {
609
- process.stdout.write(canonicalSessionsCommand(query, options) + '\n');
610
- return;
611
- }
612
- if (options.roots) {
613
- process.stdout.write(JSON.stringify(getSessionRoots(), null, 2) + '\n');
614
- return;
615
- }
616
- if (options.resolveLaunchId !== undefined) {
617
- if (!options.json)
618
- throw new Error('--resolve-launch-id requires --json.');
619
- const launchId = options.resolveLaunchId.trim();
620
- if (!launchId)
621
- throw new Error('--resolve-launch-id requires a non-empty launch id.');
622
- const { loadHookSessionIndex } = await import('../lib/session/hook-sessions.js');
623
- const record = loadHookSessionIndex().byLaunchId.get(launchId);
624
- process.stdout.write(JSON.stringify({ launchId, sessionId: record?.session_id ?? null }) + '\n');
625
- return;
626
- }
627
- if (options.resolve !== undefined || options.resolveSafeV1 !== undefined) {
628
- if (options.resolveSafeV1 !== undefined && process.env[NO_FANOUT_ENV] !== '1') {
629
- console.error(chalk.red('--resolve-safe-v1 is an internal fleet protocol.'));
630
- process.exit(1);
631
- }
632
- if (!options.json) {
633
- console.error(chalk.red('--resolve requires --json.'));
634
- process.exit(1);
635
- }
636
- const selector = (options.resolveSafeV1 ?? options.resolve ?? '').trim();
637
- if (!selector) {
638
- console.error(chalk.red('--resolve requires a non-empty selector.'));
639
- process.exit(1);
640
- }
641
- if (query) {
642
- console.error(chalk.red('Pass the selector to --resolve, not as a positional query.'));
643
- process.exit(1);
644
- }
645
- if (options.local === true && options.host && !shouldIncludeLocal(options.host, machineId())) {
646
- console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
647
- process.exit(1);
648
- }
649
- await resolveSessionMetadata(selector, {
650
- agent: options.agent,
651
- project: options.project,
652
- local: options.local,
653
- hosts: options.host,
654
- });
655
- return;
656
- }
657
- if (options.host && options.host.length > 0 && !liveOnly) {
658
- if (options.local === true && !shouldIncludeLocal(options.host, machineId())) {
659
- console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
660
- console.error(chalk.gray('Drop one — `--device <box>` to read that machine, `--local` to stay on this one.'));
661
- process.exit(1);
662
- }
663
- if (options.json) {
664
- await runRemoteSessionsJson(options.host);
665
- return;
666
- }
667
- if (!isBareBrowserListing(options, query)) {
668
- try {
669
- runRemoteSessions(options.host);
670
- }
671
- catch (err) {
672
- console.error(chalk.red(err.message));
673
- process.exit(1);
674
- }
675
- return;
676
- }
677
- }
678
- if (options.preview) {
679
- if (!query) {
680
- console.error(chalk.red('--preview requires a session id or query.'));
681
- process.exit(1);
682
- }
683
- await renderSessionPreview(query, { agent: options.agent, project: options.project, local: options.local, hosts: options.host });
684
- return;
685
- }
686
- if (liveOnly) {
687
- if (options.inTeam) {
688
- console.error(chalk.red('--in-team does not apply to --active: the running view carries no team lineage.'));
689
- console.error(chalk.gray('Drop --active to filter by team, or use `agents teams status <name>` for a live team.'));
690
- process.exit(1);
691
- }
692
- await runLiveRoster(options);
693
- return;
694
- }
695
- if (options.cloud) {
696
- const { runCloudTranscripts } = await import('./cloud-transcripts.js');
697
- await runCloudTranscripts(query, options);
698
- return;
699
- }
700
- if (isBareBrowserListing(options, query)) {
701
- const { runSessionBrowser, bareBrowserSeed } = await import('./sessions-browser.js');
702
- await runSessionBrowser(bareBrowserSeed({
703
- teams: options.teams,
704
- agent: options.agent,
705
- all: options.all,
706
- since: options.since,
707
- host: options.host,
708
- inTeam: options.inTeam,
709
- bookmarks: options.bookmarks,
710
- routine: options.routine,
711
- }), { local: options.local === true, hosts: options.host });
712
- return;
713
- }
714
- let filterOpts;
715
- try {
716
- filterOpts = buildFilterOptions(options);
717
- }
718
- catch (err) {
719
- console.error(chalk.red(err.message));
720
- process.exit(1);
721
- }
722
- const { agent, version } = parseAgentFilter(options.agent);
723
- let pathFilter;
724
- let searchQuery;
725
- if (query && looksLikePath(query)) {
726
- const resolved = resolvePathFilter(query);
727
- if (!fs.existsSync(resolved)) {
728
- console.log(chalk.yellow(`Path not found: ${resolved}`));
729
- console.log(chalk.gray('Did you mean to search? Use quotes: agents sessions "' + query + '"'));
730
- return;
731
- }
732
- pathFilter = fs.realpathSync(resolved);
733
- }
734
- else {
735
- searchQuery = query;
736
- }
737
- if ((options.artifacts || options.artifact !== undefined) && !query) {
738
- console.error(chalk.red('--artifacts and --artifact require a session ID or query.'));
739
- process.exit(1);
740
- }
741
- const mode = resolveViewMode(options, filterOpts);
742
- const wantsRender = mode === 'markdown' || hasAnyFilter(filterOpts);
743
- if ((options.artifacts || options.artifact !== undefined) && searchQuery) {
744
- await renderArtifactsGlobal(searchQuery, options.artifacts ?? false, options.artifact, artifactLookupScope(options.agent, options.project, options.routine));
745
- return;
746
- }
747
- if (searchQuery && looksLikeSessionId(searchQuery)) {
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 });
749
- return;
750
- }
751
- if (wantsRender && searchQuery) {
752
- await renderOneSession(searchQuery, mode, { agent: options.agent, project: options.project, routine: options.routine, filter: filterOpts, redact: options.redact, local: options.local, hosts: options.host });
753
- return;
754
- }
755
- const isInteractive = !options.json && isInteractiveTerminal();
756
- const wantsOverview = isInteractive && !searchQuery && !pathFilter && !options.flat && !options.tree;
757
- const wantsWholeTeam = !!options.inTeam;
758
- const wantsWholeRoutine = !!options.routine;
759
- const userSetLimit = limitSource === 'cli' || limitSource === 'env';
760
- const limit = wantsOverview
761
- ? OVERVIEW_POOL_LIMIT
762
- : parseInt(userSetLimit ? options.limit : wantsWholeTeam || wantsWholeRoutine ? String(WHOLE_TEAM_POOL_LIMIT) : DEFAULT_LIMIT, 10);
763
- const since = wantsOverview
764
- ? options.since
765
- : (options.since ?? (isInteractive && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? '30d' : undefined));
766
- const spinner = options.json ? null : ora().start();
767
- const tracker = createScanProgressTracker(LOAD_VERBS, 'sessions', spinner);
768
- try {
769
- const sortBy = options.sort === 'cost' ? 'cost' : options.sort === 'duration' ? 'duration' : 'timestamp';
770
- const scope = {
771
- agent,
772
- version,
773
- all: pathFilter ? undefined : options.all || wantsWholeTeam || wantsWholeRoutine,
774
- cwd: process.cwd(),
775
- cwdPrefix: pathFilter ?? (wantsOverview && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? process.cwd() : undefined),
776
- project: options.project,
777
- since,
778
- until: options.until,
779
- sortBy,
780
- origin: options.routine ? 'routine' : undefined,
781
- skill: options.skill,
782
- plugin: options.plugin,
783
- };
784
- let hiddenUnmanaged = 0;
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
- });
793
- tracker.stop();
794
- spinner?.stop();
795
- const { visible: visibleSessions } = filterTeamSessions(sessions, shouldShowTeamSessions(options));
796
- sessions = visibleSessions;
797
- if (options.inTeam)
798
- sessions = sessions.filter((s) => matchesTeam(s, options.inTeam));
799
- if (options.bookmarks) {
800
- const bookmarks = listBookmarks();
801
- sessions = sessions.filter((s) => bookmarks.has(s.id));
802
- }
803
- const hiddenCount = shouldShowTeamSessions(options) || options.inTeam
804
- ? 0
805
- : countSessionsInScope({ ...scope, onlyTeamOrigin: true });
806
- if (typeof options.routine === 'string') {
807
- const filteredByRoutine = await filterSessionsByRoutine(sessions, options.routine, false);
808
- if (!filteredByRoutine)
809
- return;
810
- sessions = filteredByRoutine;
811
- }
812
- const answeringJsonSweep = options.json === true && process.env[NO_FANOUT_ENV] === '1';
813
- if (searchQuery && !answeringJsonSweep) {
814
- const idMatches = resolveSessionById(sessions, searchQuery);
815
- if (idMatches.length === 1) {
816
- await renderSession(idMatches[0], mode, filterOpts, options);
817
- return;
818
- }
819
- if (idMatches.length === 0 && looksLikeSessionId(searchQuery)) {
820
- await renderOneSession(searchQuery, mode, { agent: options.agent, project: options.project, routine: options.routine, filter: filterOpts, redact: options.redact, local: options.local, hosts: options.host });
821
- return;
822
- }
823
- }
824
- if (options.json) {
825
- if (options.routine === true) {
826
- const filteredByRoutine = await filterSessionsByRoutine(sessions, options.routine, false);
827
- if (!filteredByRoutine)
828
- return;
829
- sessions = filteredByRoutine;
830
- }
831
- let filtered = searchQuery
832
- ? resolveSessionQuery(sessions, searchQuery, {
833
- scope: { agent: options.agent, project: options.project, routine: options.routine },
834
- }).matches
835
- : sessions;
836
- const forceLocalJson = options.local === true || process.env[NO_FANOUT_ENV] === '1';
837
- if (fleetWide && !forceLocalJson) {
838
- const forwarded = ensureWholeIndex(buildForwardedArgs(process.argv, new Set(options.host ?? [])));
839
- if (!forwarded.includes('--json'))
840
- forwarded.push('--json');
841
- const fanSpinner = isInteractiveTerminal() ? interruptibleSpinner('Reaching other machines...').start() : null;
842
- try {
843
- const { sessions: remoteSessions } = await gatherRemoteList(forwarded, undefined);
844
- if (remoteSessions.length > 0) {
845
- filtered = mergeLocalFirst([...filtered, ...remoteSessions], machineId());
846
- }
847
- }
848
- catch {
849
- }
850
- finally {
851
- fanSpinner?.stop();
852
- }
853
- }
854
- const live = await gatherActiveSessions({
855
- local: forceLocalJson,
856
- hosts: options.host,
857
- });
858
- process.stdout.write(serializeSessionsJson(serializeSessionPickerRows(filtered, live.sessions)));
859
- return;
860
- }
861
- const forceLocal = options.local === true || process.env[NO_FANOUT_ENV] === '1';
862
- if (!forceLocal) {
863
- const forwarded = buildForwardedArgs(process.argv, new Set(options.host ?? []));
864
- if (!forwarded.includes('--json'))
865
- forwarded.push('--json');
866
- const fanSpinner = isInteractiveTerminal() ? interruptibleSpinner('Reaching other machines...').start() : null;
867
- try {
868
- const { sessions: remoteSessions } = await gatherRemoteList(forwarded, options.host);
869
- if (remoteSessions.length > 0) {
870
- sessions = mergeLocalFirst([...sessions, ...remoteSessions], machineId());
871
- }
872
- }
873
- catch {
874
- }
875
- finally {
876
- fanSpinner?.stop();
877
- }
878
- }
879
- if (options.routine) {
880
- const target = await selectRoutineTarget(sessions, options.routine, isInteractive);
881
- if (!target)
882
- return;
883
- if (target.name) {
884
- sessions = sessions.filter((s) => s.routineName === target.name);
885
- if (!searchQuery && !options.flat && !options.tree) {
886
- const liveIndex = await maybeLiveIndex(options);
887
- printRoutineDrilldown(buildRoutineDrilldown(target.name, sessions), liveIndex, { hiddenCount, hiddenUnmanaged });
888
- return;
889
- }
890
- }
891
- }
892
- if (sessions.length === 0) {
893
- if (pathFilter) {
894
- console.log(chalk.gray(`No sessions found for ${pathFilter}.`));
895
- }
896
- else if (options.routine) {
897
- console.log(chalk.gray('No indexed agent sessions for this routine. Drop --flat/--tree to see its run history.'));
898
- }
899
- else {
900
- console.log(chalk.gray(formatNoSessionsMessage(options.all, options.project)));
901
- }
902
- if (hiddenCount > 0) {
903
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
904
- }
905
- if (hiddenUnmanaged > 0) {
906
- console.log(chalk.gray(formatUnmanagedHiddenFooter(hiddenUnmanaged)));
907
- }
908
- return;
909
- }
910
- if (options.teams && !options.flat && !options.tree && !searchQuery && !pathFilter) {
911
- const liveIndex = await maybeLiveIndex(options);
912
- printTeamsView(sessions, liveIndex, hiddenUnmanaged);
913
- return;
914
- }
915
- if (wantsOverview) {
916
- const liveIndex = await maybeLiveIndex(options);
917
- printSessionOverview(sessions, hiddenCount, liveIndex, { perProjectCap: OVERVIEW_ROWS_PER_PROJECT, expand: !!options.all, hiddenUnmanaged });
918
- return;
919
- }
920
- if (isInteractiveTerminal() && !options.tree && !options.flat) {
921
- const message = pathFilter
922
- ? `Search sessions (${path.basename(pathFilter)}):`
923
- : formatSearchMessage(options);
924
- const picked = await pickSessionInteractive(sessions, message, searchQuery, hiddenCount, undefined, { agent: options.agent, project: options.project, routine: options.routine });
925
- if (picked) {
926
- await handlePickedSession(picked);
927
- return;
928
- }
929
- return;
930
- }
931
- const filtered = searchQuery
932
- ? filterSessionsByQuery(sessions, searchQuery, {
933
- agent: options.agent,
934
- project: options.project,
935
- routine: options.routine,
936
- })
937
- : sessions;
938
- const liveIndex = await maybeLiveIndex(options);
939
- printSessionTable(filtered, hiddenCount, options.tree === true, liveIndex);
940
- if (hiddenUnmanaged > 0)
941
- console.log(chalk.gray(formatUnmanagedHiddenFooter(hiddenUnmanaged)));
942
- }
943
- catch (err) {
944
- tracker.stop();
945
- spinner?.stop();
946
- console.error(chalk.red(`Failed to discover sessions: ${err.message}`));
947
- process.exit(1);
948
- }
949
- }
950
- export async function maybeLiveIndex(options) {
951
- if (options.live === false || options.json)
952
- return undefined;
953
- try {
954
- return indexActiveBySessionId(await getActiveSessions({ localOnly: options.local === true }));
955
- }
956
- catch {
957
- return undefined;
958
- }
959
- }
960
- export function overviewProjectKey(s, defs) {
961
- const resolved = defs?.length ? resolveProjectNameForCwd(s.cwd, defs) : resolveProjectKey(s.cwd);
962
- if (resolved)
963
- return resolved;
964
- if (s.project && s.project.trim())
965
- return s.project.trim();
966
- return '(no project)';
967
- }
968
- export function buildOverviewGroups(pool, perProjectCap, defs) {
969
- const byKey = new Map();
970
- for (const s of pool) {
971
- const k = overviewProjectKey(s, defs);
972
- (byKey.get(k) ?? byKey.set(k, []).get(k)).push(s);
973
- }
974
- const cap = Math.max(1, perProjectCap);
975
- const groups = [];
976
- for (const [key, rows] of byKey) {
977
- const shown = rows.slice(0, cap);
978
- groups.push({ key, total: rows.length, shown, more: rows.length - shown.length, maxTs: rows[0].lastActivity ?? rows[0].timestamp });
979
- }
980
- groups.sort((a, b) => (a.maxTs < b.maxTs ? 1 : a.maxTs > b.maxTs ? -1 : a.key.localeCompare(b.key)));
981
- return { groups, projectCount: byKey.size };
982
- }
983
- function printSessionOverview(pool, hiddenCount, liveIndex, opts) {
984
- const { groups } = buildOverviewGroups(pool, opts.expand ? Infinity : opts.perProjectCap, listProjectDefs());
985
- const shownGroups = opts.expand ? groups : groups.slice(0, OVERVIEW_MAX_PROJECTS);
986
- const hiddenProjects = groups.length - shownGroups.length;
987
- const total = pool.length;
988
- const projWord = groups.length === 1 ? 'project' : 'projects';
989
- console.log(chalk.gray(`${total} session${total === 1 ? '' : 's'} · ${groups.length} ${projWord} · recent activity\n`));
990
- let first = true;
991
- for (const g of shownGroups) {
992
- if (!first)
993
- console.log();
994
- first = false;
995
- const { glyph } = liveGlyphAndPreview(liveIndex?.get(g.shown[0].id));
996
- const head = `${chalk.cyan('▸')} ${chalk.cyan.bold(g.key)} ${chalk.gray(String(g.total))}` +
997
- `${glyph ? ' ' + glyph : ''} ${chalk.gray(formatRelativeTime(g.maxTs))}`;
998
- console.log(head);
999
- for (const s of g.shown)
1000
- console.log(treeSessionRow(s, liveIndex?.get(s.id)));
1001
- if (g.more > 0)
1002
- console.log(' ' + chalk.gray(`· ${g.more} more`));
1003
- }
1004
- console.log();
1005
- const parts = [chalk.gray('newest first (by last activity)')];
1006
- if (hiddenProjects > 0)
1007
- parts.push(chalk.gray(`+${hiddenProjects} more project${hiddenProjects === 1 ? '' : 's'}`));
1008
- parts.push(chalk.gray('agents sessions --all spans every project on disk · <project> to drill in · --flat for the plain list'));
1009
- console.log(parts.join(chalk.gray(' · ')));
1010
- if (hiddenCount > 0)
1011
- console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
1012
- if (opts.hiddenUnmanaged)
1013
- console.log(chalk.gray(formatUnmanagedHiddenFooter(opts.hiddenUnmanaged)));
1014
- }
1015
- const TEAM_MODE_W = 5;
1016
- const TEAM_HANDLE_W = 16;
1017
- function teamMemberRow(session, live) {
1018
- const shown = sessionDisplayAgent(session);
1019
- const agentColor = colorAgent(shown);
1020
- const origin = session.teamOrigin;
1021
- const age = sessionAgeParts(session.timestamp, session.lastActivity);
1022
- const handle = safeTeamText(origin?.handle) ?? session.shortId;
1023
- const mode = safeTeamText(origin?.mode) ?? '';
1024
- const { glyph, preview } = liveGlyphAndPreview(live);
1025
- const restingTodo = !live ? formatTodoCompact(session.todos) : '';
1026
- const doing = [restingTodo, preview || session.topic || ''].filter(Boolean).join(' · ');
1027
- const shownHandle = truncateToWidth(handle, TEAM_HANDLE_W);
1028
- const head = doing ? `${shownHandle} · ${doing}` : shownHandle;
1029
- const badges = signalBadges(metaSignals(session));
1030
- const badgeW = badges ? stringWidth(badges) + 1 : 0;
1031
- const { cell: statusCell, width: statusW } = liveStatusCell(live);
1032
- const glyphW = glyph ? 2 : 0;
1033
- const baseTopicW = terminalWidth() - (2 + 9 + 8 + (TEAM_MODE_W + 1)) - glyphW - statusW - badgeW - stringWidth(age.last) - 1;
1034
- const when = timeCell(age, baseTopicW);
1035
- const topicW = Math.max(12, baseTopicW - when.extraW);
1036
- return (' ' +
1037
- chalk.dim(padToWidth(session.shortId, 9)) +
1038
- agentColor(padToWidth(truncateToWidth(shown, 7), 8)) +
1039
- chalk.yellow(padToWidth(truncateToWidth(mode || '-', TEAM_MODE_W), TEAM_MODE_W + 1)) +
1040
- (badges ? badges + ' ' : '') +
1041
- (glyph ? glyph + ' ' : '') +
1042
- statusCell +
1043
- padToWidth(chalk.white(truncateToWidth(head, topicW)), topicW) +
1044
- ' ' +
1045
- when.text);
1046
- }
1047
- function teamGroupHeader(g, glyph, labelById) {
1048
- const count = chalk.gray(`(${g.sessions.length})`);
1049
- if (g.kind === 'noTeam') {
1050
- return (chalk.magenta('▸') + ' ' + chalk.magenta.bold(NO_TEAM_GROUP_KEY) + ' ' + count +
1051
- ' ' + chalk.gray('team-flagged spawns with no team record (`agents run`, or aged-out teammates)'));
1052
- }
1053
- const bits = [chalk.cyan('▸') + ' ' + chalk.cyan.bold(g.key), count];
1054
- if (glyph)
1055
- bits.push(glyph);
1056
- if (g.spawnerSessionId) {
1057
- const who = labelById.get(g.spawnerSessionId) ?? g.spawnerSessionId.slice(0, 8);
1058
- bits.push(chalk.gray(`by ${who}`));
1059
- }
1060
- bits.push(chalk.gray(`spawned ${formatRelativeTime(g.firstSpawnTs)}`));
1061
- return bits.join(' ');
1062
- }
1063
- function printTeamsView(pool, liveIndex, hiddenUnmanaged = 0) {
1064
- const groups = groupSessionsByTeam(pool);
1065
- if (groups.length === 0) {
1066
- console.log(chalk.gray('No team sessions found.'));
1067
- console.log(chalk.gray('Team sessions are spawned by `agents teams` — see `agents teams status`.'));
1068
- return;
1069
- }
1070
- const labelById = new Map();
1071
- for (const s of pool) {
1072
- const label = sessionHeadline(s);
1073
- if (label)
1074
- labelById.set(s.id, cleanPreview(label));
1075
- }
1076
- const total = groups.reduce((n, g) => n + g.sessions.length, 0);
1077
- const teamCount = groups.filter((g) => g.kind === 'team').length;
1078
- const noTeam = groups.find((g) => g.kind === 'noTeam');
1079
- const parts = [
1080
- `${total} team session${total === 1 ? '' : 's'}`,
1081
- `${teamCount} team${teamCount === 1 ? '' : 's'}`,
1082
- ];
1083
- if (noTeam)
1084
- parts.push(`${noTeam.sessions.length} without a team record`);
1085
- console.log(chalk.gray(parts.join(' · ') + '\n'));
1086
- let first = true;
1087
- for (const g of groups) {
1088
- if (!first)
1089
- console.log();
1090
- first = false;
1091
- const { glyph } = liveGlyphAndPreview(liveIndex?.get(g.sessions[0].id));
1092
- console.log(teamGroupHeader(g, glyph, labelById));
1093
- for (const s of g.sessions)
1094
- console.log(teamMemberRow(s, liveIndex?.get(s.id)));
1095
- }
1096
- console.log();
1097
- console.log(chalk.gray('newest-active team first · resume any row with `agents sessions resume <id>`'));
1098
- if (hiddenUnmanaged > 0)
1099
- console.log(chalk.gray(formatUnmanagedHiddenFooter(hiddenUnmanaged)));
1100
- }
1101
- function formatSearchMessage(options) {
1102
- const filters = [];
1103
- if (options.agent)
1104
- filters.push(`agent: ${options.agent}`);
1105
- if (options.project?.trim())
1106
- filters.push(`project: ${options.project.trim()}`);
1107
- if (filters.length === 0)
1108
- return 'Search sessions:';
1109
- return `Search sessions (${filters.join(', ')}):`;
1110
- }
1111
- function ambiguityHint(byId, completeId) {
1112
- if (completeId)
1113
- return 'That is already a complete id — these rows share it as a prefix.';
1114
- return byId
1115
- ? 'Pass a longer ID to narrow it down.'
1116
- : 'That matched on text, not an id. Pass a session id, or narrow the search.';
1117
- }
1118
- export function fleetNotFoundMessage(query, deviceCount, unreachable) {
1119
- const id = query.trim();
1120
- if (deviceCount === 0) {
1121
- return [
1122
- chalk.red(`No session with id ${id} on this machine.`),
1123
- chalk.gray('No other reachable devices to search.'),
1124
- ];
1125
- }
1126
- const searched = `${deviceCount} device${deviceCount === 1 ? '' : 's'}`;
1127
- const lines = [chalk.red(`No session with id ${id} on this machine or ${searched} searched.`)];
1128
- if (unreachable.length > 0) {
1129
- lines.push(chalk.gray(`Unreachable (not searched): ${unreachable.join(', ')}`));
1130
- }
1131
- return lines;
1132
- }
1133
- export function artifactLookupScope(agent, project, routine) {
1134
- return { agent, project, routine };
1135
- }
1136
- async function renderArtifactsGlobal(query, listAll, name, scope) {
1137
- const spinner = ora().start();
1138
- const tracker = createScanProgressTracker(FIND_VERBS, 'session', spinner);
1139
- try {
1140
- const discovered = await discoverSessions({
1141
- all: true,
1142
- cwd: process.cwd(),
1143
- limit: 5000,
1144
- onProgress: tracker.onProgress,
1145
- });
1146
- tracker.stop();
1147
- const allSessions = applyScopeFilters(discovered, scope);
1148
- const { matches: queryMatches, byId, completeId } = resolveSessionQuery(allSessions, query, { scope });
1149
- if (queryMatches.length === 0) {
1150
- spinner.stop();
1151
- if (byId)
1152
- notFoundByIdMessage(query).forEach(l => console.error(l));
1153
- else
1154
- console.error(chalk.red(`No session found matching: ${query}`));
1155
- process.exit(1);
1156
- }
1157
- if (queryMatches.length > 1) {
1158
- spinner.stop();
1159
- console.error(chalk.red(`Multiple sessions match "${query}":`));
1160
- for (const m of queryMatches.slice(0, 10)) {
1161
- console.error(chalk.cyan(` ${m.shortId} ${m.id} ${sessionHeadline(m) ?? ''}`));
1162
- }
1163
- console.error(chalk.gray(ambiguityHint(byId, completeId)));
1164
- process.exit(1);
1165
- }
1166
- spinner.stop();
1167
- await renderArtifactsForSession(queryMatches[0], listAll, name);
1168
- }
1169
- catch (err) {
1170
- if (isPromptCancelled(err))
1171
- return;
1172
- tracker.stop();
1173
- spinner.stop();
1174
- console.error(chalk.red(`Failed to read session: ${err.message}`));
1175
- process.exit(1);
1176
- }
1177
- }
1178
- async function renderOneSession(query, mode, scope) {
1179
- if (looksLikeSessionId(query)) {
1180
- const outcome = await resolveSessionMetadataValue(query, scope);
1181
- if (outcome.kind === 'partial') {
1182
- const offline = outcome.failedPeers;
1183
- console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
1184
- console.error(chalk.red(`No session matching "${query}" on any reachable device (${offline.length} unreachable, not checked).`));
1185
- console.error(chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'));
1186
- process.exit(1);
1187
- }
1188
- if (outcome.kind === 'ambiguous') {
1189
- console.error(chalk.red(`Multiple sessions match "${query}" across the fleet:`));
1190
- for (const candidate of outcome.candidates) {
1191
- const match = candidate.hits[0].session;
1192
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
1193
- console.error(chalk.cyan(` ${match.shortId} ${match.id}`) + chalk.gray(` ${machines} ${match.agent}${match.version ? ` ${match.version}` : ''}`));
1194
- }
1195
- console.error(chalk.gray('Pass the full session ID to narrow it down.'));
1196
- process.exit(1);
1197
- }
1198
- if (outcome.kind === 'resolved') {
1199
- const resolved = outcome.session;
1200
- const transcriptPeer = transcriptOnPeerOf(resolved);
1201
- if (transcriptPeer) {
1202
- const args = ['sessions', resolved.id, '--local'];
1203
- const flag = modeFlag(mode);
1204
- if (flag)
1205
- args.push(flag);
1206
- if (scope.filter.include?.length)
1207
- args.push('--include', scope.filter.include.join(','));
1208
- if (scope.filter.exclude?.length)
1209
- args.push('--exclude', scope.filter.exclude.join(','));
1210
- if (scope.filter.first !== undefined)
1211
- args.push('--first', String(scope.filter.first));
1212
- if (scope.filter.last !== undefined)
1213
- args.push('--last', String(scope.filter.last));
1214
- if (scope.redact === false)
1215
- args.push('--no-redact');
1216
- const rendered = await runOnPeer(args, transcriptPeer);
1217
- if (rendered === 'no-target') {
1218
- console.error(chalk.red(`Session ${resolved.id} is on ${transcriptPeer}, but that device is not reachable.`));
1219
- process.exit(1);
1220
- }
1221
- return;
1222
- }
1223
- await renderSession(resolved, mode, scope.filter, { redact: scope.redact });
1224
- return;
1225
- }
1226
- }
1227
- const spinner = ora().start();
1228
- const tracker = createScanProgressTracker(FIND_VERBS, 'session', spinner);
1229
- try {
1230
- const discovered = await discoverSessions({
1231
- all: true,
1232
- cwd: process.cwd(),
1233
- limit: 5000,
1234
- onProgress: tracker.onProgress,
1235
- });
1236
- tracker.stop();
1237
- const allSessions = applyScopeFilters(discovered, scope);
1238
- let session;
1239
- const resolution = resolveSessionQuery(allSessions, query, { scope });
1240
- let queryMatches = resolution.matches;
1241
- let byId = resolution.byId;
1242
- const completeId = resolution.completeId;
1243
- if (queryMatches.length === 0 && !looksLikeSessionId(query)) {
1244
- const contentResults = scopedContentIndex(allSessions, query, scope);
1245
- if (contentResults.size > 0) {
1246
- const matchedSessions = Array.from(contentResults.values())
1247
- .sort((a, b) => (b._bm25Score ?? 0) - (a._bm25Score ?? 0));
1248
- byId = false;
1249
- if (matchedSessions.length === 1) {
1250
- session = matchedSessions[0];
1251
- }
1252
- else {
1253
- queryMatches = matchedSessions;
1254
- }
1255
- }
1256
- }
1257
- if (queryMatches.length === 0 && !session) {
1258
- spinner.stop();
1259
- const historyEntry = findClaudeHistoryEntry(query);
1260
- if (historyEntry) {
1261
- const resumeMatch = resolveClaudeHistoryEntryToTranscript(historyEntry, allSessions);
1262
- if (resumeMatch) {
1263
- session = resumeMatch.session;
1264
- }
1265
- else {
1266
- renderClaudeHistoryOnlyId(query, historyEntry, allSessions);
1267
- process.exit(1);
1268
- }
1269
- }
1270
- else if (byId) {
1271
- if (shouldFanOutForId(query, scope.local)) {
1272
- const outcome = await resolveSessionAcrossFleet(query, mode, scope.hosts);
1273
- if (outcome.kind === 'rendered')
1274
- return;
1275
- if (outcome.kind === 'conflict')
1276
- process.exit(1);
1277
- fleetNotFoundMessage(query, outcome.deviceCount, outcome.unreachable).forEach(l => console.error(l));
1278
- process.exit(1);
1279
- }
1280
- notFoundByIdMessage(query).forEach(l => console.error(l));
1281
- process.exit(1);
1282
- }
1283
- else {
1284
- console.error(chalk.red(`No session found matching: ${query}`));
1285
- console.error(chalk.gray('Run "agents sessions" to browse sessions.'));
1286
- process.exit(1);
1287
- }
1288
- }
1289
- if (!session) {
1290
- if (queryMatches.length > 1) {
1291
- spinner.stop();
1292
- console.error(chalk.red(`Multiple sessions match "${query}":`));
1293
- for (const match of queryMatches.slice(0, 10)) {
1294
- console.error(chalk.cyan(` ${match.shortId} ${match.id} ${sessionHeadline(match) ?? ''}`));
1295
- }
1296
- console.error(chalk.gray(ambiguityHint(byId, completeId)));
1297
- process.exit(1);
1298
- }
1299
- else {
1300
- session = queryMatches[0];
1301
- }
1302
- }
1303
- if (!session) {
1304
- throw new Error('Session resolution failed');
1305
- }
1306
- spinner.stop();
1307
- await renderSession(session, mode, scope.filter, { redact: scope.redact });
1308
- }
1309
- catch (err) {
1310
- if (isPromptCancelled(err))
1311
- return;
1312
- tracker.stop();
1313
- spinner.stop();
1314
- console.error(chalk.red(`Failed to read session: ${err.message}`));
1315
- process.exit(1);
1316
- }
1317
- }
1318
- function shouldFanOutForId(query, local) {
1319
- if (local === true)
1320
- return false;
1321
- if (process.env[NO_FANOUT_ENV] === '1')
1322
- return false;
1323
- return looksLikeSessionId(query);
1324
- }
1325
- function modeFlag(mode) {
1326
- if (mode === 'markdown')
1327
- return '--markdown';
1328
- if (mode === 'json')
1329
- return '--json';
1330
- return undefined;
1331
- }
1332
- export async function resolveSessionMetadata(selector, scope, deps = { gatherRemoteList }) {
1333
- const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
1334
- if (process.env[NO_FANOUT_ENV] === '1') {
1335
- process.stdout.write(serializeResolvedSessionsJson(localMatches));
1336
- return;
1337
- }
1338
- const outcome = await resolveSessionMetadataValue(selector, scope, deps);
1339
- if (outcome.kind === 'partial') {
1340
- const offline = outcome.failedPeers;
1341
- console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
1342
- console.error(chalk.red(`No session matching "${selector}" on any reachable device (${offline.length} unreachable, not checked).`));
1343
- console.error(chalk.gray(' If it lives on an offline box, wake it (agents devices) or run there: agents ssh <device>'));
1344
- process.exit(1);
1345
- }
1346
- if (outcome.kind === 'not-found') {
1347
- console.error(chalk.red(`No session found matching: ${selector}`));
1348
- process.exit(1);
1349
- }
1350
- if (outcome.kind === 'ambiguous') {
1351
- console.error(chalk.red(`Multiple sessions match "${selector}" across the fleet:`));
1352
- for (const candidate of outcome.candidates) {
1353
- const session = candidate.hits[0].session;
1354
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
1355
- console.error(chalk.cyan(` ${session.shortId} ${session.id}`) + chalk.gray(` ${machines} ${sessionHeadline(session) ?? ''}`));
1356
- }
1357
- console.error(chalk.gray(looksLikeSessionId(selector) ? 'Pass a longer ID to narrow it down.' : 'Narrow the keywords to one session.'));
1358
- process.exit(1);
1359
- }
1360
- process.stdout.write(serializeResolvedSessionsJson([outcome.session]));
1361
- }
1362
- async function resolveSessionAcrossFleet(query, mode, hosts, deps = { gatherRemoteList, runOnPeer }) {
1363
- const spinner = isInteractiveTerminal() ? interruptibleSpinner('Searching the fleet...').start() : null;
1364
- let candidates = [];
1365
- let deviceCount = 0;
1366
- let unreachable = [];
1367
- try {
1368
- const forwarded = ['sessions', query, '--json', '--all', '--local'];
1369
- const remote = await deps.gatherRemoteList(forwarded, hosts, selectorAllowsEarlyExit(query)
1370
- ? { isDefinitive: (session) => isDefinitiveMatch(session, query) }
1371
- : undefined);
1372
- candidates = fleetCandidatesByQuery(remote.sessions, query);
1373
- deviceCount = remote.deviceCount;
1374
- unreachable = remote.unreachable;
1375
- }
1376
- catch {
1377
- candidates = [];
1378
- }
1379
- finally {
1380
- spinner?.stop();
1381
- }
1382
- if (candidates.length === 0)
1383
- return { kind: 'not-found', deviceCount, unreachable };
1384
- if (candidates.length > 1) {
1385
- console.error(chalk.red(`Multiple sessions match "${query}" across the fleet:`));
1386
- for (const candidate of candidates) {
1387
- const s = candidate.hits[0].session;
1388
- const label = sessionHeadline(s) ?? '';
1389
- const machines = candidate.hits.map(hit => hit.machine).join(', ');
1390
- console.error(chalk.cyan(` ${s.shortId} ${s.id}`) + chalk.gray(` ${machines} ${s.agent}${s.version ? ` ${s.version}` : ''} ${label}`));
1391
- }
1392
- console.error(chalk.gray('Pass a longer ID to narrow it down.'));
1393
- return { kind: 'conflict' };
1394
- }
1395
- const candidate = candidates[0];
1396
- const { machine } = candidate.hits[0];
1397
- const peerArgs = ['sessions', candidate.id, '--local'];
1398
- const flag = modeFlag(mode);
1399
- if (flag)
1400
- peerArgs.push(flag);
1401
- const result = await deps.runOnPeer(peerArgs, machine);
1402
- if (result === 'no-target') {
1403
- console.error(chalk.red(`Session ${candidate.id} is on ${machine}, but it is not a reachable registered device.`));
1404
- console.error(chalk.gray('Register it with `agents devices` or run the command on that machine.'));
1405
- return { kind: 'conflict' };
1406
- }
1407
- return { kind: 'rendered' };
1408
- }
1409
- export function registerSessionsCommands(program) {
1410
- const sessionsCmd = program
1411
- .command('sessions')
1412
- .argument('[query]', 'Session ID, search query, or path (., ../, /path) to filter by project')
1413
- .option('--query <text>', 'Search text (same as the positional query)', collectQueryClause, [])
1414
- .option('--resolve <selector>', 'Resolve one full ID, unique prefix, or keyword query to safe session metadata (requires --json; searches the fleet unless --local)')
1415
- .addOption(new Option('--resolve-safe-v1 <selector>').hideHelp())
1416
- .addOption(new Option('--resolve-launch-id <id>').hideHelp())
1417
- .description('Find, browse, and read agent conversation transcripts. Live roster: `agents sessions --active`.')
1418
- .option('-a, --agent <agent>', 'Filter by agent type and version (e.g., claude, codex@0.116.0)')
1419
- .addOption(new Option('--session-version <version>', 'Internal spelling for the public sessions --version filter')
1420
- .hideHelp())
1421
- .option('--claude', 'Shorthand for --agent claude')
1422
- .option('--codex', 'Shorthand for --agent codex')
1423
- .option('--kimi', 'Shorthand for --agent kimi')
1424
- .option('--antigravity', 'Shorthand for --agent antigravity')
1425
- .option('--grok', 'Shorthand for --agent grok')
1426
- .option('--opencode', 'Shorthand for --agent opencode')
1427
- .option('--all', 'Widen every non-status filter to "all": every directory (not just this project) and all time (no window cap). Status filters like --active still compose; -a/--device/--since still narrow their axis.')
1428
- .option('--bookmarks', 'Show only bookmarked sessions — bookmark them with `*` in the browser or `agents sessions bookmark <id>`')
1429
- .option('--unmanaged', "Also show sessions from your own ~/.<agent> installs (hidden once agents-cli manages that agent)")
1430
- .option('--team, --teams', 'Show team-spawned sessions (hidden by default), grouped by team — each team names its spawner and spawn time, teammates show their mode + handle, and team-flagged spawns with no teammate record sink into a (no team) bucket. --flat/--tree keep the plain inline table')
1431
- .option('--in-team <name>', "Only this team: the session that spawned it plus (with --teams) its teammates. Spans every directory and all time, since a team's worktrees and history sit outside the default window.")
1432
- .option('--routines, --routine [name]', 'Show routine-run sessions; omit the name on a TTY to pick one interactively (fuzzy name matching)')
1433
- .option('-p, --project <name>', 'Filter by project name (searches across all directories)')
1434
- .option('--skill <name>', 'Only sessions that invoked this skill (matches a bare name or a namespaced plugin skill\'s short name, e.g. --skill design finds rush:design)')
1435
- .option('--plugin <name>', 'Only sessions that used a skill/command owned by this plugin')
1436
- .option('--since <time>', 'Only sessions newer than this (e.g., 2h, 7d, 4w, or ISO date)')
1437
- .option('--until <time>', 'Only sessions older than this (ISO timestamp)')
1438
- .option('-n, --limit <n>', 'Maximum number of sessions to return', DEFAULT_LIMIT)
1439
- .option('--sort <field>', 'Sort the list by: recent (default), cost, or duration')
1440
- .option('--markdown', 'Render the session as markdown (user, assistant, thinking, tool calls)')
1441
- .option('--no-redact', 'Disable default secret redaction in rendered session output (--markdown and --json)')
1442
- .option('--json', 'Output JSON (session list when browsing, event array when rendering one session)')
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`')
1444
- .option('--exclude <roles>', 'Exclude these roles (comma-separated): user, assistant, thinking, tools')
1445
- .option('--first <n>', 'Keep only the first N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
1446
- .option('--last <n>', 'Keep only the last N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
1447
- .option('--artifacts', 'List all files written or edited during a session')
1448
- .option('--artifact <name>', 'Read a specific artifact by filename or path (outputs to stdout)')
1449
- .option('--active', 'Show only sessions running right now across terminals, teams, cloud, and headless agents')
1450
- .option('--roots', 'With --json: emit the on-disk directories scanned for session transcripts, per agent (for external watchers)')
1451
- .option('--local', 'Only this machine — skip the cross-machine SSH fan-out (default listing and --active)')
1452
- .option('--working', 'Show live sessions currently doing work (implies --active)')
1453
- .option('--idle', 'Show live sessions that have stopped between turns (implies --active)')
1454
- .option('--waiting', 'Show live sessions waiting on your input; exits non-zero if any (implies --active)')
1455
- .option('--orphan', 'Show live sessions whose process outlived its terminal client (implies --active)')
1456
- .option('--orphaned', 'Alias for --orphan')
1457
- .option('--crashed', 'Show sessions whose terminal disappeared with the process (implies --active)')
1458
- .option('--closed', 'Show recently observed sessions whose process exited normally (implies --active)')
1459
- .option('--abandoned', 'Show sessions with no transcript progress for the abandonment window (implies --active)')
1460
- .option('--queued', 'Show queued sessions that have not started running (implies --active)')
1461
- .option('--unknown', 'Show sessions whose live state cannot be determined (implies --active)')
1462
- .option('--tree', 'Group the listing by directory; drops the id/version columns for readability')
1463
- .option('--flat', 'Plain flat table (one row per session) instead of the grouped project overview')
1464
- .option('--no-live', 'Do not enrich the listing with live status/preview for running sessions')
1465
- .option('--cloud', 'Source sessions from Rush Cloud (captured runs) instead of local disk')
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)')
1467
- .addOption(new Option('--devices <target...>', 'Plural alias for --device (accepts `all`/`fleet`).').hideHelp())
1468
- .option('--no-interactive', 'Print the listing instead of opening the interactive browser (default on a TTY for the bare listing and --active)')
1469
- .option('--print-cmd', 'Print the canonical `ag sessions …` command for the given flags and exit (the twin of the browser’s `y` hotkey)')
1470
- .option('--preview', 'With a session id/query: print a compact preview and exit (no pager)');
1471
- setHelpSections(sessionsCmd, {
1472
- examples: `
1473
- # Search indexed transcripts by topic, file path, or command
1474
- agents sessions "add auth middleware"
1475
-
1476
- # Read a session as markdown (user + assistant + thinking + tools)
1477
- agents sessions a1b2c3d4 --markdown
1478
-
1479
- # Just the user turns — useful for recalling intent
1480
- agents sessions a1b2c3d4 --include user
1481
-
1482
- # Show only what's running right now (terminals, teams, cloud, headless)
1483
- agents sessions --active
1484
-
1485
- # Filter the live fleet by the status word shown in the roster
1486
- agents sessions --working
1487
- agents sessions --idle
1488
- agents sessions --orphan
1489
- agents sessions --crashed
1490
-
1491
- # --- Session lifecycle ---
1492
- # Get back into a session — attaches a live pane, or recovers an ended one
1493
- agents sessions resume a1b2c3d4
1494
- # Same, by its tmux session name
1495
- agents sessions resume ag-claude-a1b2c3d4
1496
- # Attach only — never fork a copy
1497
- agents sessions resume a1b2c3d4 --attach-only
1498
- # Multi-select history and open each in a tab
1499
- agents sessions resume
1500
- # The other direction: interactive → headless (keep working unattended)
1501
- agents sessions detach a1b2c3d4
1502
-
1503
- # The interactive list folds in other online machines automatically,
1504
- # labelled by host with this machine first. Stay local with --local:
1505
- agents sessions --local
1506
-
1507
- # Search across every directory, not just this project
1508
- agents sessions "topic" --all
1509
-
1510
- # Filter one installed harness version (equivalent forms)
1511
- agents sessions claude@2.1.181
1512
- agents sessions --agent claude --version 2.1.181
1513
-
1514
- # Team-spawned sessions, grouped by team (spawner + spawn time per team,
1515
- # teammate mode/handle per row; team-flagged spawns with no team record
1516
- # in a trailing (no team) bucket)
1517
- agents sessions --teams
1518
-
1519
- # Who spawned which team: an orchestrator row carries team:<name>, and a
1520
- # teammate row [<team>/<handle>]. --in-team narrows to one team's lineage.
1521
- agents sessions --in-team redesign --teams
1522
-
1523
- # Pick a routine across every directory, then open one of its run sessions
1524
- agents sessions --routine
1525
- agents sessions --routine nightly-review
1526
- agents sessions 2026-07-21T10-30-00-000Z
1527
-
1528
- # Export for analysis
1529
- agents sessions --since 30d --limit 200 --json > sessions.json
1530
-
1531
- # Populate historical tool rows once on every device (search them with
1532
- # the standalone CLI: sessions --include tools --query 'program:git')
1533
- agents sessions backfill tools --fleet
1534
-
1535
- # Resolve one historical selector to metadata only, across the fleet
1536
- agents sessions --resolve d3470b57 --json
1537
-
1538
- # Search another machine's sessions live over SSH (no sync needed)
1539
- agents sessions "auth bug" --last 3 --device yosemite-s1
1540
-
1541
- # Fan the same query out across several machines
1542
- agents sessions --all "deploy script" --device box-a --device box-b
1543
- `,
1544
- notes: `
1545
- Session lifecycle — ONE verb gets you back in, it detects the state:
1546
- resume <id|alias> live pane -> attach; headless -> foreground; ended -> recover
1547
- resume <id> --attach-only attach only; never fork a copy
1548
- resume multi-select history -> open tabs
1549
- detach <id> the other direction: interactive -> headless
1550
- - The interactive listing and every live-status flag fold in your other online machines automatically (live over SSH, no sync) — each row is labelled by host, this machine first. Use --local to skip the fan-out; single-id lookups stay local.
1551
- - --all is not a device flag: it widens historical directory and time filters. Fleet collection is already the default. A status flag (--working/--idle/--waiting/--orphan/--crashed/--closed/--abandoned/--queued/--unknown) implies --active; combine status flags for a union.
1552
- - --version <version> requires --agent and is equivalent to --agent <agent@version>.
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.
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.
1555
- - --include and --exclude are mutually exclusive.
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.
1557
- - --first and --last are mutually exclusive.
1558
- - A filter flag (--include/--exclude/--first/--last) without --markdown/--json defaults to --markdown output.
1559
- - --cloud sources from Rush Cloud captured runs instead of local disk.
1560
- - --routine [name] spans every directory and shows transcripts archived from routine runs. On a TTY, omit the name to pick a routine; a name accepts exact, substring, or unambiguous typo matches. --routines is an alias. Routine rows also resolve by run id.
1561
- - Without --teams, team-spawned sessions are hidden by default.
1562
- `,
1563
- });
1564
- sessionsCmd.action(async (query, options, command) => {
1565
- await sessionsAction(query, options, command.getOptionValueSource('limit'));
1566
- });
1567
- registerSessionPreviewCommand(sessionsCmd, 'sessions');
1568
- registerSessionsResumeCommand(sessionsCmd);
1569
- registerSessionsForkCommand(sessionsCmd);
1570
- registerSessionsBookmarkCommand(sessionsCmd);
1571
- registerFocusCommand(sessionsCmd);
1572
- registerDetachCommand(sessionsCmd);
1573
- registerSessionsStopCommand(sessionsCmd);
1574
- registerSessionsInjectCommand(sessionsCmd);
1575
- registerSessionsExportCommand(sessionsCmd);
1576
- registerSessionsRenderCommand(sessionsCmd);
1577
- registerSessionsTraceCommand(sessionsCmd);
1578
- registerSessionsShareCommand(sessionsCmd);
1579
- registerSessionsImportCommand(sessionsCmd);
1580
- registerSessionsBackupSetupCommand(sessionsCmd);
1581
- registerSessionsMigrateCommand(sessionsCmd);
1582
- registerSessionsMigrationsCommand(sessionsCmd);
1583
- registerSessionsBackfillCommand(sessionsCmd);
1584
- registerSessionsStatsCommand(sessionsCmd);
1585
- registerSessionsInsightsCommand(sessionsCmd);
1586
- registerSessionsOptimizeCommand(sessionsCmd);
1587
- registerSessionsWatchCommand(sessionsCmd);
1588
- }
1589
- function formatNoSessionsMessage(showAll, project) {
1590
- const projectQuery = project?.trim();
1591
- if (projectQuery) {
1592
- return `No sessions found for project "${projectQuery}".`;
1593
- }
1594
- if (showAll)
1595
- return 'No sessions found.';
1596
- const command = 'agents sessions --all';
1597
- return `No sessions found for ${process.cwd()}. Run "${command}" to see sessions from every directory.`;
1598
- }
1599
- function formatUnmanagedHiddenFooter(hiddenCount) {
1600
- const noun = hiddenCount === 1 ? 'session' : 'sessions';
1601
- return `(${hiddenCount} ${noun} from your own unmanaged installs hidden — use --unmanaged to show)`;
1602
- }
1603
- function findClaudeHistoryEntry(idQuery) {
1604
- const historyPath = path.join(os.homedir(), '.claude', 'history.jsonl');
1605
- if (!fs.existsSync(historyPath))
1606
- return null;
1607
- try {
1608
- const lines = fs.readFileSync(historyPath, 'utf-8').split('\n');
1609
- for (let i = lines.length - 1; i >= 0; i--) {
1610
- const line = lines[i].trim();
1611
- if (!line)
1612
- continue;
1613
- let parsed;
1614
- try {
1615
- parsed = JSON.parse(line);
1616
- }
1617
- catch {
1618
- continue;
1619
- }
1620
- if (parsed.sessionId !== idQuery)
1621
- continue;
1622
- const timestampMs = typeof parsed.timestamp === 'number'
1623
- ? parsed.timestamp
1624
- : typeof parsed.timestamp === 'string'
1625
- ? Date.parse(parsed.timestamp)
1626
- : undefined;
1627
- return {
1628
- sessionId: parsed.sessionId,
1629
- display: typeof parsed.display === 'string' ? parsed.display : undefined,
1630
- project: typeof parsed.project === 'string' ? parsed.project : undefined,
1631
- timestampMs: Number.isFinite(timestampMs) ? timestampMs : undefined,
1632
- historyPath,
1633
- };
1634
- }
1635
- }
1636
- catch {
1637
- return null;
1638
- }
1639
- return null;
1640
- }
1641
- function renderClaudeHistoryOnlyId(idQuery, historyEntry, allSessions) {
1642
- console.error(chalk.red(`No transcript session found matching: ${idQuery}`));
1643
- console.error(chalk.yellow('This ID exists in Claude history, but not as a saved transcript session.'));
1644
- console.error(chalk.gray(`History file: ${historyEntry.historyPath}`));
1645
- if (historyEntry.display) {
1646
- console.error(chalk.gray(`History entry: ${historyEntry.display}`));
1647
- }
1648
- if (historyEntry.project) {
1649
- console.error(chalk.gray(`Project root: ${historyEntry.project}`));
1650
- }
1651
- if (historyEntry.timestampMs) {
1652
- console.error(chalk.gray(`History time: ${new Date(historyEntry.timestampMs).toISOString()}`));
1653
- }
1654
- const relatedSessions = findClaudeSessionsInProject(allSessions, historyEntry);
1655
- if (relatedSessions.length > 0) {
1656
- console.error(chalk.gray('Claude transcript sessions in the same project tree:'));
1657
- for (const session of relatedSessions) {
1658
- console.error(chalk.gray(` ${session.shortId} ${session.id} ${session.project || '-'} ${formatRelativeTime(session.timestamp)}`));
1659
- }
1660
- console.error(chalk.gray('Use one of the transcript IDs above with "agents sessions <id>".'));
1661
- return;
1662
- }
1663
- if (historyEntry.display === '/resume') {
1664
- console.error(chalk.gray('This looks like a Claude /resume history entry. In this case, the resumed conversation continued under a different transcript session ID.'));
1665
- }
1666
- const projectHint = historyEntry.project ? path.basename(historyEntry.project) : 'the project';
1667
- console.error(chalk.gray(`Try "agents sessions --agent claude --project ${projectHint}" to find the resumed transcript session.`));
1668
- }
1669
- function findClaudeSessionsInProject(sessions, historyEntry) {
1670
- return findClaudeProjectSessions(sessions, historyEntry)
1671
- .sort((a, b) => sessionDistance(a, historyEntry) - sessionDistance(b, historyEntry))
1672
- .slice(0, 3);
1673
- }
1674
- function findClaudeProjectSessions(sessions, historyEntry) {
1675
- if (!historyEntry.project)
1676
- return [];
1677
- let projectRoot = historyEntry.project;
1678
- try {
1679
- projectRoot = fs.realpathSync(projectRoot);
1680
- }
1681
- catch { }
1682
- return sessions.filter(session => session.agent === 'claude' &&
1683
- typeof session.cwd === 'string' &&
1684
- isWithinProject(session.cwd, projectRoot));
1685
- }
1686
- function resolveClaudeHistoryEntryToTranscript(historyEntry, sessions) {
1687
- if (historyEntry.display !== '/resume')
1688
- return null;
1689
- const candidates = findClaudeProjectSessions(sessions, historyEntry);
1690
- const matches = [];
1691
- for (const session of candidates) {
1692
- const resumeTimestampMs = findClaudeResumeTimestamp(session.filePath, historyEntry.timestampMs);
1693
- if (resumeTimestampMs === null)
1694
- continue;
1695
- const deltaMs = historyEntry.timestampMs === undefined
1696
- ? 0
1697
- : Math.abs(resumeTimestampMs - historyEntry.timestampMs);
1698
- if (historyEntry.timestampMs !== undefined && deltaMs > CLAUDE_RESUME_MATCH_WINDOW_MS) {
1699
- continue;
1700
- }
1701
- matches.push({ session, resumeTimestampMs, deltaMs });
1702
- }
1703
- if (matches.length === 0)
1704
- return null;
1705
- matches.sort((a, b) => {
1706
- if (a.deltaMs !== b.deltaMs)
1707
- return a.deltaMs - b.deltaMs;
1708
- return b.resumeTimestampMs - a.resumeTimestampMs;
1709
- });
1710
- const [best, second] = matches;
1711
- if (second && best.deltaMs === second.deltaMs && best.resumeTimestampMs === second.resumeTimestampMs) {
1712
- return null;
1713
- }
1714
- return best;
1715
- }
1716
- function findClaudeResumeTimestamp(filePath, targetTimestampMs) {
1717
- try {
1718
- const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
1719
- let bestTimestampMs = null;
1720
- for (const line of lines) {
1721
- if (!line.includes('SessionStart:resume'))
1722
- continue;
1723
- let parsed;
1724
- try {
1725
- parsed = JSON.parse(line);
1726
- }
1727
- catch {
1728
- continue;
1729
- }
1730
- if (parsed.attachment?.hookName !== 'SessionStart:resume')
1731
- continue;
1732
- const timestampMs = Date.parse(parsed.timestamp || '');
1733
- if (Number.isNaN(timestampMs))
1734
- continue;
1735
- if (targetTimestampMs === undefined) {
1736
- return timestampMs;
1737
- }
1738
- if (bestTimestampMs === null || Math.abs(timestampMs - targetTimestampMs) < Math.abs(bestTimestampMs - targetTimestampMs)) {
1739
- bestTimestampMs = timestampMs;
1740
- }
1741
- }
1742
- return bestTimestampMs;
1743
- }
1744
- catch {
1745
- return null;
1746
- }
1747
- }
1748
- function isWithinProject(sessionCwd, projectRoot) {
1749
- const cwd = toComparablePath(sessionCwd);
1750
- const root = toComparablePath(projectRoot);
1751
- return cwd === root || cwd.startsWith(root + '/');
1752
- }
1753
- function sessionDistance(session, historyEntry) {
1754
- if (!historyEntry.timestampMs)
1755
- return Number.MAX_SAFE_INTEGER;
1756
- const sessionTime = new Date(session.timestamp).getTime();
1757
- if (Number.isNaN(sessionTime))
1758
- return Number.MAX_SAFE_INTEGER;
1759
- return Math.abs(sessionTime - historyEntry.timestampMs);
1760
- }