@phnx-labs/agents-cli 1.22.126 → 1.23.0

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 (80) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +13 -16
  3. package/dist/bootstrap.js +4 -3
  4. package/dist/commands/browser.js +4 -19
  5. package/dist/commands/computer.d.ts +2 -6
  6. package/dist/commands/computer.js +12 -18
  7. package/dist/commands/logs.js +2 -6
  8. package/dist/commands/menubar.js +28 -1
  9. package/dist/commands/projects.js +103 -40
  10. package/dist/commands/sessions.d.ts +0 -11
  11. package/dist/commands/sessions.js +31 -364
  12. package/dist/index.js +12 -12
  13. package/dist/lib/accounting/usage-ingest.js +2 -1
  14. package/dist/lib/browser-client.d.ts +0 -21
  15. package/dist/lib/browser-client.js +1 -44
  16. package/dist/lib/computer/record.d.ts +1 -0
  17. package/dist/lib/computer/record.js +2 -16
  18. package/dist/lib/config-keys.d.ts +2 -2
  19. package/dist/lib/config-keys.js +8 -2
  20. package/dist/lib/daemon/daemon.js +1 -8
  21. package/dist/lib/daemon/runner.js +3 -2
  22. package/dist/lib/daemon-services.d.ts +1 -1
  23. package/dist/lib/daemon-services.js +0 -5
  24. package/dist/lib/device-config.d.ts +1 -1
  25. package/dist/lib/device-config.js +48 -7
  26. package/dist/lib/feed/tool-activity.d.ts +22 -10
  27. package/dist/lib/feed/tool-activity.js +161 -32
  28. package/dist/lib/feed/tools.d.ts +55 -2
  29. package/dist/lib/feed/tools.js +22 -28
  30. package/dist/lib/feed/watch.js +4 -3
  31. package/dist/lib/github/open-prs.d.ts +41 -0
  32. package/dist/lib/github/open-prs.js +157 -0
  33. package/dist/lib/github/project-prs.d.ts +20 -1
  34. package/dist/lib/github/project-prs.js +8 -7
  35. package/dist/lib/helper-versions.js +1 -1
  36. package/dist/lib/menubar/install-menubar.d.ts +5 -7
  37. package/dist/lib/menubar/install-menubar.js +120 -29
  38. package/dist/lib/menubar/resolve-version.d.ts +1 -0
  39. package/dist/lib/menubar/resolve-version.js +4 -2
  40. package/dist/lib/menubar/snapshot.d.ts +2 -0
  41. package/dist/lib/menubar/snapshot.js +2 -0
  42. package/dist/lib/menubar/update-state.d.ts +15 -0
  43. package/dist/lib/menubar/update-state.js +36 -0
  44. package/dist/lib/owner-notify.d.ts +0 -12
  45. package/dist/lib/owner-notify.js +1 -10
  46. package/dist/lib/self-heal/checks/menubar-helper.js +1 -0
  47. package/dist/lib/session/cloud.d.ts +0 -1
  48. package/dist/lib/session/cloud.js +0 -5
  49. package/dist/lib/session/db.d.ts +0 -64
  50. package/dist/lib/session/db.js +0 -116
  51. package/dist/lib/session/remote/remote-list.d.ts +2 -36
  52. package/dist/lib/session/remote/remote-list.js +3 -320
  53. package/dist/lib/session/tool-index.d.ts +0 -62
  54. package/dist/lib/session/tool-index.js +1 -537
  55. package/dist/lib/sessions-client.d.ts +1 -0
  56. package/dist/lib/sessions-client.js +17 -1
  57. package/dist/lib/standalone-tools.js +2 -2
  58. package/dist/lib/stdout.d.ts +1 -0
  59. package/dist/lib/stdout.js +5 -0
  60. package/dist/lib/testdata/owner-notify-api.d.ts +0 -13
  61. package/dist/lib/testdata/owner-notify-api.js +3 -23
  62. package/package.json +1 -1
  63. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  64. package/dist/commands/browser-sessions-picker.js +0 -136
  65. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  66. package/dist/commands/computer-sessions-picker.js +0 -90
  67. package/dist/commands/sessions-tail.d.ts +0 -13
  68. package/dist/commands/sessions-tail.js +0 -222
  69. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  70. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  71. package/dist/lib/browser/paths.d.ts +0 -9
  72. package/dist/lib/browser/paths.js +0 -31
  73. package/dist/lib/browser/record.d.ts +0 -4
  74. package/dist/lib/browser/record.js +0 -19
  75. package/dist/lib/browser/sessions-list.d.ts +0 -79
  76. package/dist/lib/browser/sessions-list.js +0 -415
  77. package/dist/lib/computer/sessions-list.d.ts +0 -78
  78. package/dist/lib/computer/sessions-list.js +0 -372
  79. package/dist/lib/daemon/owner-device-delivery-service.d.ts +0 -10
  80. package/dist/lib/daemon/owner-device-delivery-service.js +0 -28
@@ -19,10 +19,9 @@ import { viewingInLabel } from '../lib/session/viewing-in.js';
19
19
  import { machineId } from '../lib/session/sync/config.js';
20
20
  import { NO_FANOUT_ENV } from '../lib/session/remote-active.js';
21
21
  import { loadLocalActiveSessions, readActiveSessionsCache, } from '../lib/session/session-cache.js';
22
- import { gatherRemoteList, gatherRemoteToolProgramCounts, gatherRemoteToolSearch, runOnPeer } from '../lib/session/remote-list.js';
23
- import { gatherRemoteAgentsJson } from '../lib/remote-agents-json.js';
22
+ import { gatherRemoteList, runOnPeer } from '../lib/session/remote-list.js';
24
23
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
25
- import { discoverSessions, queryIndexedSessions, countSessionsInScope, resolveSessionById, isCompleteSessionId, looksLikeSessionId, searchContentIndex, getSessionRoots, scopeToManaged } from '../lib/session/discover.js';
24
+ import { discoverSessions, countSessionsInScope, resolveSessionById, isCompleteSessionId, looksLikeSessionId, searchContentIndex, getSessionRoots } from '../lib/session/discover.js';
26
25
  import { findSessionsById, querySessions, readSessionTimelineAny } from '../lib/session/db.js';
27
26
  import { foldTimeline, emptyTimelineState, projectTimeline, projectSessionFiles } from '@phnx-labs/sessions-cli/reader';
28
27
  import { readSessionTail } from '@phnx-labs/sessions-cli/reader';
@@ -47,10 +46,9 @@ import { sessionAgentSupportsResume, sessionRecoveryRunArgs } from '../lib/sessi
47
46
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
48
47
  import { sessionPicker, buildPreview, loadSessionPreviewDigest, transcriptOnPeerOf, formatTodoCompact, } from './sessions-picker.js';
49
48
  import { setHelpSections } from '../lib/help.js';
50
- import { cleanPreview, gatherActiveSessions, indexActiveBySessionId, isAwaitingUser, liveGlyphAndPreview, liveStatusWord, remoteHostsToDial, requestedLiveStatuses, resolveRoutineName, runLiveRoster, shouldIncludeLocal, statusColor, } from './ps-roster.js';
49
+ import { cleanPreview, gatherActiveSessions, indexActiveBySessionId, isAwaitingUser, liveGlyphAndPreview, liveStatusWord, requestedLiveStatuses, resolveRoutineName, runLiveRoster, shouldIncludeLocal, statusColor, } from './ps-roster.js';
51
50
  import { buildFilterOptions, hasAnyFilter, metaSignals, renderSession, resolveViewMode, signalBadges, } from '../lib/session/presentation.js';
52
51
  export { buildFilterOptions, renderSession, renderSessionLog, renderSessionLogJson, resolveViewMode, } from '../lib/session/presentation.js';
53
- import { registerSessionsTailCommand } from './sessions-tail.js';
54
52
  import { registerSessionsResumeCommand } from './sessions-resume.js';
55
53
  import { registerSessionsForkCommand } from './fork.js';
56
54
  import { registerSessionsBookmarkCommand } from './sessions-bookmark.js';
@@ -71,10 +69,6 @@ import { registerSessionsStatsCommand } from './sessions-stats.js';
71
69
  import { registerSessionsInsightsCommand } from './insights.js';
72
70
  import { registerSessionsOptimizeCommand } from './sessions-optimize.js';
73
71
  import { registerSessionsWatchCommand } from './sessions-watch.js';
74
- import { runBrowserSessionsCommand } from './browser-sessions-picker.js';
75
- import { runComputerSessionsCommand } from './computer-sessions-picker.js';
76
- import { buildComputerSessionRows } from '../lib/computer/sessions-list.js';
77
- import { countToolProgramOccurrences, parseToolProgramCountClause, readToolIndexCoverage, searchToolCalls, TOOL_QUERY_MAX_CLAUSE_BYTES, TOOL_QUERY_MAX_CLAUSES, TOOL_QUERY_MAX_RESULT_SESSIONS, serializeToolSearchEnvelope, toolSearchRemoteReceiveBudget, } from '../lib/session/tool-index.js';
78
72
  const SESSION_AGENT_FILTER_HELP = `Filter by agent, e.g. claude, codex, claude@2.0.65`;
79
73
  function collectQueryClause(value, previous) {
80
74
  return [...previous, value];
@@ -331,35 +325,6 @@ async function runRemoteSessionsJson(hosts) {
331
325
  const { sessions } = await gatherRemoteList(forwarded, hosts);
332
326
  process.stdout.write(serializeSessionsJson(sessions));
333
327
  }
334
- export function parseRemoteComputerSessionRows(stdout, machine) {
335
- try {
336
- const value = JSON.parse(stdout);
337
- if (!Array.isArray(value))
338
- return { items: [], valid: false };
339
- const items = value
340
- .filter((row) => Boolean(row && typeof row === 'object' && !Array.isArray(row)))
341
- .map((row) => ({ ...row, machine: row.machine || machine }));
342
- return { items, valid: true };
343
- }
344
- catch {
345
- return { items: [], valid: false };
346
- }
347
- }
348
- async function gatherRemoteComputerSessionRows(hosts) {
349
- const hostSet = new Set(hosts ?? []);
350
- const forwarded = buildForwardedArgs(process.argv, hostSet);
351
- if (!forwarded.includes('--json'))
352
- forwarded.push('--json');
353
- if (!forwarded.includes('--no-interactive'))
354
- forwarded.push('--no-interactive');
355
- const result = await gatherRemoteAgentsJson({
356
- args: forwarded,
357
- noFanoutEnv: NO_FANOUT_ENV,
358
- hosts,
359
- parse: parseRemoteComputerSessionRows,
360
- });
361
- return result.items;
362
- }
363
328
  function useInteractiveBrowser(options) {
364
329
  return options.interactive !== false && !options.json && isInteractiveTerminal();
365
330
  }
@@ -918,176 +883,24 @@ export function formatLiveStatusHeadline(live, bookmarked = false) {
918
883
  }
919
884
  return `${star}${glyph} ${statusColor(live.status)(word)}${suffix}`;
920
885
  }
921
- export function mergeToolSearchEnvelopes(local, remotes) {
922
- const all = [local, ...remotes];
923
- const sessions = new Map();
924
- for (const envelope of all) {
925
- for (const session of envelope.sessions) {
926
- sessions.set(`${session.machine ?? 'local'}\0${session.id}`, session);
927
- }
928
- }
929
- return {
930
- schemaVersion: 1,
931
- generatedAt: new Date().toISOString(),
932
- query: local.query,
933
- coverage: {
934
- indexedFiles: all.reduce((n, envelope) => n + envelope.coverage.indexedFiles, 0),
935
- indexedCalls: all.reduce((n, envelope) => n + envelope.coverage.indexedCalls, 0),
936
- skippedFiles: all.reduce((n, envelope) => n + envelope.coverage.skippedFiles, 0),
937
- limitedFiles: all.reduce((n, envelope) => n + envelope.coverage.limitedFiles, 0),
938
- remainingFiles: all.reduce((n, envelope) => n + envelope.coverage.remainingFiles, 0),
939
- complete: all.every((envelope) => envelope.coverage.complete),
940
- },
941
- sessions: [...sessions.values()].sort((a, b) => b.timestamp.localeCompare(a.timestamp)),
942
- };
943
- }
944
- export function mergeToolProgramCountEnvelopes(local, remotes) {
945
- const all = [local, ...remotes];
946
- return {
947
- schemaVersion: 1,
948
- kind: 'tool-program-count',
949
- generatedAt: new Date().toISOString(),
950
- query: local.query,
951
- coverage: {
952
- indexedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.indexedFiles, 0),
953
- indexedCalls: all.reduce((sum, envelope) => sum + envelope.coverage.indexedCalls, 0),
954
- skippedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.skippedFiles, 0),
955
- limitedFiles: all.reduce((sum, envelope) => sum + envelope.coverage.limitedFiles, 0),
956
- remainingFiles: all.reduce((sum, envelope) => sum + envelope.coverage.remainingFiles, 0),
957
- complete: all.every((envelope) => envelope.coverage.complete),
958
- },
959
- totals: {
960
- occurrences: all.reduce((sum, envelope) => sum + envelope.totals.occurrences, 0),
961
- toolCalls: all.reduce((sum, envelope) => sum + envelope.totals.toolCalls, 0),
962
- sessions: all.reduce((sum, envelope) => sum + envelope.totals.sessions, 0),
963
- },
964
- machines: all.flatMap((envelope) => envelope.machines),
965
- };
966
- }
967
- export function toolOriginSessions(sessions, machine, originOnly) {
968
- return originOnly
969
- ? sessions.filter((session) => (session.machine ?? machine) === machine)
970
- : sessions;
971
- }
972
- function printToolProgramCount(envelope) {
973
- const { totals } = envelope;
974
- const qualifier = envelope.coverage.complete ? '' : 'at least ';
975
- console.log(`${envelope.query.program}: ${qualifier}${totals.occurrences.toLocaleString()} static occurrence${totals.occurrences === 1 ? '' : 's'} `
976
- + `in ${totals.toolCalls.toLocaleString()} tool call${totals.toolCalls === 1 ? '' : 's'} `
977
- + `across ${totals.sessions.toLocaleString()} session${totals.sessions === 1 ? '' : 's'}.`);
978
- if (!envelope.coverage.complete) {
979
- console.log(chalk.yellow(`Partial tool index: ${envelope.coverage.remainingFiles.toLocaleString()} transcript${envelope.coverage.remainingFiles === 1 ? '' : 's'} still need `
980
- + '`agents sessions backfill tools`.'));
981
- }
982
- }
983
- export function toolSearchFleetSortError(sort, spansDevices) {
984
- if (!spansDevices || !sort || sort === 'recent')
985
- return undefined;
986
- return 'Tool search across devices supports only --sort recent; cost and duration are local-only.';
987
- }
988
- function printToolSearch(envelope) {
989
- for (const session of envelope.sessions) {
990
- const machineName = session.machine
991
- ? truncate(sanitizeForTerminal(session.machine).replace(/\s+/g, ' '), 80)
992
- : '';
993
- const machine = machineName ? ` @ ${machineName}` : '';
994
- const rawHeading = sessionHeadline(session) || session.project || session.shortId;
995
- const heading = truncate(sanitizeForTerminal(rawHeading).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 20));
996
- console.log(`${chalk.cyan(session.shortId)}${chalk.gray(machine)} ${heading}`);
997
- for (const call of session.calls) {
998
- const tool = truncate(sanitizeForTerminal(call.tool).replace(/\s+/g, ' '), 80);
999
- const safePrograms = call.programs.map((program) => truncate(sanitizeForTerminal(program).replace(/\s+/g, ' '), 80));
1000
- const programs = safePrograms.length > 0 ? ` [${safePrograms.join(', ')}]` : '';
1001
- const status = call.outcome === 'unknown' ? '' : ` ${call.outcome}`;
1002
- const input = truncate(sanitizeForTerminal(call.input).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 26));
1003
- console.log(` ${chalk.gray(`#${call.ordinal + 1}`)} ${tool}${programs}${status} ${input}`);
1004
- const snippet = call.error || call.output;
1005
- if (snippet) {
1006
- console.log(` ${chalk.gray(truncate(sanitizeForTerminal(snippet).replace(/\s+/g, ' '), Math.max(30, terminalWidth() - 8)))}`);
1007
- }
1008
- }
1009
- console.log();
1010
- }
1011
- const count = envelope.sessions.length;
1012
- console.log(chalk.gray(`${count} matching session${count === 1 ? '' : 's'}.`));
1013
- if (!envelope.coverage.complete) {
1014
- const skipped = envelope.coverage.skippedFiles > 0
1015
- ? ` ${envelope.coverage.skippedFiles} transcript${envelope.coverage.skippedFiles === 1 ? ' was' : 's were'} skipped.`
1016
- : '';
1017
- const limited = envelope.coverage.limitedFiles > 0
1018
- ? ` ${envelope.coverage.limitedFiles} transcript${envelope.coverage.limitedFiles === 1 ? ' has' : 's have'} incomplete evidence because a safety limit was reached.`
1019
- : '';
1020
- const retry = envelope.coverage.remainingFiles > 0
1021
- ? ' Run `agents sessions backfill tools` to index historical transcripts.'
1022
- : '';
1023
- console.log(chalk.yellow(`Tool index coverage is partial: ${envelope.coverage.remainingFiles} transcript${envelope.coverage.remainingFiles === 1 ? '' : 's'} remain.${skipped}${limited}${retry}`));
1024
- }
1025
- }
1026
886
  async function sessionsAction(query, options, limitSource) {
1027
- const queryClauses = options.query ?? [];
1028
887
  const liveStatuses = requestedLiveStatuses(options);
1029
888
  const liveOnly = options.active === true || liveStatuses.length > 0;
1030
- const toolOnly = options.include?.split(',').map((role) => role.trim()).filter(Boolean).join(',') === 'tools';
1031
- const toolEvidenceMode = toolOnly;
1032
- if (options.count && !toolOnly) {
1033
- console.error(chalk.red('--count requires --include tools.'));
1034
- process.exitCode = 1;
1035
- return;
1036
- }
1037
- if (!toolEvidenceMode) {
1038
- if (queryClauses.length > 1) {
1039
- console.error(chalk.red('Repeated --query clauses require --include tools.'));
1040
- process.exitCode = 1;
1041
- return;
1042
- }
1043
- query = query ?? queryClauses[0];
1044
- }
1045
- if (options.fleet && !toolEvidenceMode) {
1046
- console.error(chalk.red('--fleet applies to tool-call queries: add --include tools.'));
1047
- process.exitCode = 1;
1048
- return;
1049
- }
1050
- if (toolEvidenceMode && (options.markdown || options.redact === false)) {
1051
- const incompatible = [
1052
- options.markdown ? '--markdown' : undefined,
1053
- options.redact === false ? '--no-redact' : undefined,
1054
- ].filter((flag) => flag !== undefined);
1055
- console.error(chalk.red(`${incompatible.join(' and ')} cannot be used with --include tools.`));
1056
- console.error(chalk.gray('Tool evidence is always redacted and byte-bounded; drop the conflicting render flag.'));
1057
- process.exitCode = 1;
1058
- return;
1059
- }
1060
- if (toolEvidenceMode && queryClauses.length > TOOL_QUERY_MAX_CLAUSES) {
1061
- console.error(chalk.red(`Tool search accepts at most ${TOOL_QUERY_MAX_CLAUSES} --query clauses.`));
1062
- process.exitCode = 1;
1063
- return;
1064
- }
1065
- if (toolEvidenceMode && queryClauses.some((clause) => Buffer.byteLength(clause) > TOOL_QUERY_MAX_CLAUSE_BYTES)) {
1066
- console.error(chalk.red(`Each tool --query clause is limited to ${TOOL_QUERY_MAX_CLAUSE_BYTES} bytes.`));
1067
- process.exitCode = 1;
1068
- return;
1069
- }
1070
- if (options.count && (queryClauses.length !== 1 || query !== undefined)) {
1071
- console.error(chalk.red('--count requires exactly one --query program:<name> clause and no positional query.'));
1072
- process.exitCode = 1;
889
+ const includesOnlyTools = options.include?.split(',').map((role) => role.trim()).filter(Boolean).join(',') === 'tools';
890
+ const readsOneSession = query !== undefined && looksLikeSessionId(query) && (options.query ?? []).length === 0;
891
+ if (includesOnlyTools && !readsOneSession) {
892
+ console.error(chalk.red('Tool-call search lives in the standalone sessions CLI:'));
893
+ console.error(chalk.gray(" sessions --include tools --query 'program:git' [--count] [--host <device>] [--json]"));
894
+ process.exitCode = 2;
1073
895
  return;
1074
896
  }
1075
- if (options.count && (limitSource === 'cli' || limitSource === 'env')) {
1076
- console.error(chalk.red('--count covers the complete filtered scope and cannot be combined with --limit.'));
897
+ const queryClauses = options.query ?? [];
898
+ if (queryClauses.length > 1) {
899
+ console.error(chalk.red('Pass --query once.'));
1077
900
  process.exitCode = 1;
1078
901
  return;
1079
902
  }
1080
- let countProgram;
1081
- if (options.count) {
1082
- try {
1083
- countProgram = parseToolProgramCountClause(queryClauses[0]);
1084
- }
1085
- catch (error) {
1086
- console.error(chalk.red(error instanceof Error ? error.message : String(error)));
1087
- process.exitCode = 1;
1088
- return;
1089
- }
1090
- }
903
+ query = query ?? queryClauses[0];
1091
904
  applyAgentShorthands(options);
1092
905
  try {
1093
906
  query = applyVersionFilters(query, options);
@@ -1153,13 +966,7 @@ async function sessionsAction(query, options, limitSource) {
1153
966
  });
1154
967
  return;
1155
968
  }
1156
- if (toolEvidenceMode && options.local === true
1157
- && options.host && !shouldIncludeLocal(options.host, machineId())) {
1158
- console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
1159
- console.error(chalk.gray('Drop one — `--device <box>` to read that machine, `--local` to stay on this one.'));
1160
- process.exit(1);
1161
- }
1162
- if (options.host && options.host.length > 0 && !liveOnly && !toolEvidenceMode) {
969
+ if (options.host && options.host.length > 0 && !liveOnly) {
1163
970
  if (options.local === true && !shouldIncludeLocal(options.host, machineId())) {
1164
971
  console.error(chalk.red('--local and --device name opposite scopes: --local skips the SSH fan-out that --device needs.'));
1165
972
  console.error(chalk.gray('Drop one — `--device <box>` to read that machine, `--local` to stay on this one.'));
@@ -1244,12 +1051,12 @@ async function sessionsAction(query, options, limitSource) {
1244
1051
  process.exit(1);
1245
1052
  }
1246
1053
  const mode = resolveViewMode(options, filterOpts);
1247
- const wantsRender = !toolEvidenceMode && (mode === 'markdown' || hasAnyFilter(filterOpts));
1054
+ const wantsRender = mode === 'markdown' || hasAnyFilter(filterOpts);
1248
1055
  if ((options.artifacts || options.artifact !== undefined) && searchQuery) {
1249
1056
  await renderArtifactsGlobal(searchQuery, options.artifacts ?? false, options.artifact, artifactLookupScope(options.agent, options.project, options.routine));
1250
1057
  return;
1251
1058
  }
1252
- if (!toolEvidenceMode && searchQuery && looksLikeSessionId(searchQuery)) {
1059
+ if (searchQuery && looksLikeSessionId(searchQuery)) {
1253
1060
  await renderOneSession(searchQuery, mode, { agent: options.agent, project: options.project, routine: options.routine, filter: filterOpts, redact: options.redact, local: options.local, hosts: options.host });
1254
1061
  return;
1255
1062
  }
@@ -1265,22 +1072,9 @@ async function sessionsAction(query, options, limitSource) {
1265
1072
  const limit = wantsOverview
1266
1073
  ? OVERVIEW_POOL_LIMIT
1267
1074
  : parseInt(userSetLimit ? options.limit : wantsWholeTeam || wantsWholeRoutine ? String(WHOLE_TEAM_POOL_LIMIT) : DEFAULT_LIMIT, 10);
1268
- if (toolEvidenceMode && (!Number.isSafeInteger(limit) || limit < 1 || limit > TOOL_QUERY_MAX_RESULT_SESSIONS)) {
1269
- console.error(chalk.red(`Tool search --limit must be from 1 to ${TOOL_QUERY_MAX_RESULT_SESSIONS}.`));
1270
- process.exitCode = 1;
1271
- return;
1272
- }
1273
1075
  const since = wantsOverview
1274
1076
  ? options.since
1275
1077
  : (options.since ?? (isInteractive && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? '30d' : undefined));
1276
- const toolSpansDevices = toolEvidenceMode
1277
- && (options.fleet || (options.host?.length ?? 0) > 0);
1278
- const toolSortError = toolSearchFleetSortError(options.sort, toolSpansDevices);
1279
- if (toolSortError) {
1280
- console.error(chalk.red(toolSortError));
1281
- process.exitCode = 1;
1282
- return;
1283
- }
1284
1078
  const spinner = options.json ? null : ora().start();
1285
1079
  const tracker = createScanProgressTracker(LOAD_VERBS, 'sessions', spinner);
1286
1080
  try {
@@ -1288,50 +1082,26 @@ async function sessionsAction(query, options, limitSource) {
1288
1082
  const scope = {
1289
1083
  agent,
1290
1084
  version,
1291
- all: pathFilter ? undefined : options.all || wantsWholeTeam || wantsWholeRoutine || toolSpansDevices,
1085
+ all: pathFilter ? undefined : options.all || wantsWholeTeam || wantsWholeRoutine,
1292
1086
  cwd: process.cwd(),
1293
- cwdPrefix: pathFilter ?? (wantsOverview && !options.all && !wantsWholeTeam && !wantsWholeRoutine && !toolSpansDevices ? process.cwd() : undefined),
1087
+ cwdPrefix: pathFilter ?? (wantsOverview && !options.all && !wantsWholeTeam && !wantsWholeRoutine ? process.cwd() : undefined),
1294
1088
  project: options.project,
1295
1089
  since,
1296
1090
  until: options.until,
1297
1091
  sortBy,
1298
1092
  origin: options.routine ? 'routine' : undefined,
1299
- skipExistenceCheck: toolEvidenceMode,
1300
- unbounded: toolEvidenceMode,
1301
1093
  skill: options.skill,
1302
1094
  plugin: options.plugin,
1303
1095
  };
1304
1096
  let hiddenUnmanaged = 0;
1305
- const toolSelf = toolEvidenceMode ? machineId() : undefined;
1306
- const toolIncludesLocal = !toolEvidenceMode
1307
- || process.env[NO_FANOUT_ENV] === '1'
1308
- || shouldIncludeLocal(options.host, toolSelf);
1309
- const indexedIdMatches = toolIncludesLocal && toolEvidenceMode && searchQuery && looksLikeSessionId(searchQuery)
1310
- ? scopeToManaged(findSessionsById(searchQuery, { agent, version, project: options.project }), agent ? [agent] : SESSION_AGENTS, { agent, includeUnmanaged: options.unmanaged })
1311
- : [];
1312
- let sessions;
1313
- if (!toolIncludesLocal) {
1314
- sessions = [];
1315
- }
1316
- else if (indexedIdMatches.length > 0) {
1317
- sessions = indexedIdMatches.map((session) => ({
1318
- ...session,
1319
- machine: session.machine ?? toolSelf,
1320
- }));
1321
- }
1322
- else {
1323
- const readOptions = {
1324
- ...scope,
1325
- limit,
1326
- excludeTeamOrigin: !shouldShowTeamSessions(options),
1327
- onProgress: tracker.onProgress,
1328
- includeUnmanaged: options.unmanaged,
1329
- onHiddenUnmanaged: (n) => { hiddenUnmanaged = n; },
1330
- };
1331
- sessions = toolEvidenceMode
1332
- ? await queryIndexedSessions(readOptions, { resolveLinear: false })
1333
- : await discoverSessions(readOptions);
1334
- }
1097
+ let sessions = await discoverSessions({
1098
+ ...scope,
1099
+ limit,
1100
+ excludeTeamOrigin: !shouldShowTeamSessions(options),
1101
+ onProgress: tracker.onProgress,
1102
+ includeUnmanaged: options.unmanaged,
1103
+ onHiddenUnmanaged: (n) => { hiddenUnmanaged = n; },
1104
+ });
1335
1105
  tracker.stop();
1336
1106
  spinner?.stop();
1337
1107
  const { visible: visibleSessions } = filterTeamSessions(sessions, shouldShowTeamSessions(options));
@@ -1342,62 +1112,6 @@ async function sessionsAction(query, options, limitSource) {
1342
1112
  const bookmarks = listBookmarks();
1343
1113
  sessions = sessions.filter((s) => bookmarks.has(s.id));
1344
1114
  }
1345
- if (toolEvidenceMode) {
1346
- const self = toolSelf;
1347
- const selectedSessions = searchQuery
1348
- ? filterSessionsByQuery(sessions, searchQuery, {
1349
- agent: options.agent,
1350
- project: options.project,
1351
- routine: options.routine,
1352
- })
1353
- : sessions;
1354
- const localSessions = selectedSessions;
1355
- const mayFanOut = options.local !== true && process.env[NO_FANOUT_ENV] !== '1';
1356
- const hosts = remoteHostsToDial(options.host, self);
1357
- const originOnly = process.env[NO_FANOUT_ENV] === '1'
1358
- || (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0));
1359
- const querySessions = toolOriginSessions(localSessions, self, originOnly);
1360
- if (countProgram) {
1361
- const countCoverage = readToolIndexCoverage(querySessions);
1362
- let countEnvelope = countToolProgramOccurrences(querySessions, countProgram, countCoverage, self);
1363
- if (!toolIncludesLocal)
1364
- countEnvelope.machines = [];
1365
- if (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0)
1366
- && (!options.host?.length || (hosts && hosts.length > 0))) {
1367
- const stripped = toolSearchForwardedArgs(process.argv, options.host ?? []);
1368
- const remote = await gatherRemoteToolProgramCounts(stripped, options.host?.length ? hosts : undefined, countProgram);
1369
- countEnvelope = mergeToolProgramCountEnvelopes(countEnvelope, remote.envelopes.map((item) => item.envelope));
1370
- if (remote.unreachable.length > 0)
1371
- countEnvelope.coverage.complete = false;
1372
- }
1373
- if (options.json)
1374
- process.stdout.write(JSON.stringify(countEnvelope, null, 2) + '\n');
1375
- else
1376
- printToolProgramCount(countEnvelope);
1377
- return;
1378
- }
1379
- const coverage = readToolIndexCoverage(querySessions);
1380
- let envelope = searchToolCalls(querySessions, queryClauses, coverage, limit);
1381
- if (mayFanOut && (options.fleet || (options.host?.length ?? 0) > 0)) {
1382
- if (!options.host?.length || (hosts && hosts.length > 0)) {
1383
- const stripped = toolSearchForwardedArgs(process.argv, options.host ?? []);
1384
- const remote = await gatherRemoteToolSearch(stripped, options.host?.length ? hosts : undefined, toolSearchRemoteReceiveBudget(envelope), queryClauses);
1385
- envelope = mergeToolSearchEnvelopes(envelope, remote.envelopes.map((item) => item.envelope));
1386
- if (remote.truncated.length > 0 || remote.unreachable.length > 0) {
1387
- envelope.coverage.complete = false;
1388
- }
1389
- }
1390
- }
1391
- envelope.sessions = envelope.sessions.slice(0, limit);
1392
- const serializedEnvelope = serializeToolSearchEnvelope(envelope);
1393
- if (options.json) {
1394
- process.stdout.write(serializedEnvelope);
1395
- }
1396
- else {
1397
- printToolSearch(envelope);
1398
- }
1399
- return;
1400
- }
1401
1115
  const hiddenCount = shouldShowTeamSessions(options) || options.inTeam
1402
1116
  ? 0
1403
1117
  : countSessionsInScope({ ...scope, onlyTeamOrigin: true });
@@ -2653,14 +2367,6 @@ export function metadataResolveForwardedArgs(selector, scope) {
2653
2367
  args.push('--project', scope.project);
2654
2368
  return args;
2655
2369
  }
2656
- export function toolSearchForwardedArgs(argv, hosts) {
2657
- const args = ensureWholeIndex(buildForwardedArgs(argv, new Set(hosts)).filter((arg) => arg !== '--fleet'));
2658
- if (!args.includes('--json'))
2659
- args.push('--json');
2660
- if (!args.includes('--local'))
2661
- args.push('--local');
2662
- return args;
2663
- }
2664
2370
  const SHORT_SESSION_ID_WIDTH = 8;
2665
2371
  export function isUniqueEnoughSelector(selector) {
2666
2372
  const trimmed = selector.trim();
@@ -2855,7 +2561,7 @@ export function registerSessionsCommands(program) {
2855
2561
  const sessionsCmd = program
2856
2562
  .command('sessions')
2857
2563
  .argument('[query]', 'Session ID, search query, or path (., ../, /path) to filter by project')
2858
- .option('--query <clause>', 'Search text; repeat with --include tools to require distinct matching calls', collectQueryClause, [])
2564
+ .option('--query <text>', 'Search text (same as the positional query)', collectQueryClause, [])
2859
2565
  .option('--resolve <selector>', 'Resolve one full ID, unique prefix, or keyword query to safe session metadata (requires --json; searches the fleet unless --local)')
2860
2566
  .addOption(new Option('--resolve-safe-v1 <selector>').hideHelp())
2861
2567
  .addOption(new Option('--resolve-launch-id <id>').hideHelp())
@@ -2885,7 +2591,7 @@ export function registerSessionsCommands(program) {
2885
2591
  .option('--markdown', 'Render the session as markdown (user, assistant, thinking, tool calls)')
2886
2592
  .option('--no-redact', 'Disable default secret redaction in rendered session output (--markdown and --json)')
2887
2593
  .option('--json', 'Output JSON (session list when browsing, event array when rendering one session)')
2888
- .option('--include <roles>', 'Only include these roles (comma-separated): user, assistant, thinking, tools. "user" is genuine user turns only, not harness-injected scaffolding (bash-input, system-reminder)')
2594
+ .option('--include <roles>', 'Only include these roles (comma-separated): user, assistant, thinking, tools. "user" is genuine user turns only, not harness-injected scaffolding (bash-input, system-reminder). Tool-call search across sessions is `sessions --include tools`')
2889
2595
  .option('--exclude <roles>', 'Exclude these roles (comma-separated): user, assistant, thinking, tools')
2890
2596
  .option('--first <n>', 'Keep only the first N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
2891
2597
  .option('--last <n>', 'Keep only the last N turns (a turn starts at each genuine user message, not harness-injected scaffolding)')
@@ -2910,10 +2616,6 @@ export function registerSessionsCommands(program) {
2910
2616
  .option('--cloud', 'Source sessions from Rush Cloud (captured runs) instead of local disk')
2911
2617
  .option('-D, --device <target...>', 'Run this query on remote machine(s) over SSH (device alias from `agents devices`, user@host, or `all` to search the whole fleet; repeatable)')
2912
2618
  .addOption(new Option('--devices <target...>', 'Plural alias for --device (accepts `all`/`fleet`).').hideHelp())
2913
- .option('--fleet', 'With --include tools: query every registered online compute device and merge compact matches')
2914
- .option('--count', 'With one program:<name> tool query: count static occurrences, containing calls, and sessions')
2915
- .option('--browser', 'List browser-profile captures (screenshots, PDFs, recordings, downloads) instead of agent transcripts — alias of `agents browser sessions`')
2916
- .option('--computer', 'List computer-driving history, grouped by run, instead of agent transcripts — alias of `agents computer sessions`')
2917
2619
  .option('--no-interactive', 'Print the listing instead of opening the interactive browser (default on a TTY for the bare listing and --active)')
2918
2620
  .option('--print-cmd', 'Print the canonical `ag sessions …` command for the given flags and exit (the twin of the browser’s `y` hotkey)')
2919
2621
  .option('--preview', 'With a session id/query: print a compact preview and exit (no pager)');
@@ -2977,16 +2679,8 @@ export function registerSessionsCommands(program) {
2977
2679
  # Export for analysis
2978
2680
  agents sessions --since 30d --limit 200 --json > sessions.json
2979
2681
 
2980
- # List indexed tool calls in recent Codex sessions on one device
2981
- agents sessions --include tools --agent codex --device mac-mini --since 7d
2982
-
2983
- # Each repeated clause must match a different call in the same session
2984
- agents sessions --include tools --query 'program:git input:merge' --query 'program:gh output:CONFLICT' --fleet --json
2985
-
2986
- # Count every pre-indexed static git site without reparsing transcripts
2987
- agents sessions --include tools --query 'program:git' --count --fleet --json
2988
-
2989
- # Explicitly populate historical tool rows once on every device
2682
+ # Populate historical tool rows once on every device (search them with
2683
+ # the standalone CLI: sessions --include tools --query 'program:git')
2990
2684
  agents sessions backfill tools --fleet
2991
2685
 
2992
2686
  # Resolve one historical selector to metadata only, across the fleet
@@ -3010,11 +2704,7 @@ export function registerSessionsCommands(program) {
3010
2704
  - --device runs the query on the remote's own index over SSH (host alias or user@host); repeat or pass several to fan out. SSH access is the only auth.
3011
2705
  - --in-team matches both ends of the lineage: the session that ran 'agents teams create/add', and (with --teams) that team's teammates. In the interactive list, 't' cycles the same filter over the teams in view.
3012
2706
  - --include and --exclude are mutually exclusive.
3013
- - With --include tools, repeat --query for same-session AND across distinct calls. Fields: tool, program, input, output, status, exit, error.
3014
- - --count accepts exactly one program:<name> clause and reports static source occurrences, containing tool calls, and sessions.
3015
- - Tool queries read SQLite only. Run 'agents sessions backfill tools' once for historical transcripts; normal scans index new and changed sessions.
3016
- - Tool evidence is redacted and bounded before it reaches SQLite. --markdown and --no-redact conflict with --include tools.
3017
- - Tool queries accept 32 clauses (4 KiB each), --limit 1–1,000, and at most 8 MiB of materialized evidence.
2707
+ - Tool-call search and --count run in the standalone \`sessions\` CLI (\`sessions --include tools --query <clause>\`). agents indexes the calls: run 'agents sessions backfill tools' once for historical transcripts; normal scans index new and changed sessions.
3018
2708
  - --first and --last are mutually exclusive.
3019
2709
  - A filter flag (--include/--exclude/--first/--last) without --markdown/--json defaults to --markdown output.
3020
2710
  - --cloud sources from Rush Cloud captured runs instead of local disk.
@@ -3023,28 +2713,6 @@ export function registerSessionsCommands(program) {
3023
2713
  `,
3024
2714
  });
3025
2715
  sessionsCmd.action(async (query, options, command) => {
3026
- if (options.browser) {
3027
- await runBrowserSessionsCommand({ profile: query, json: options.json, interactive: options.interactive });
3028
- return;
3029
- }
3030
- if (options.computer) {
3031
- const limit = options.limit === undefined ? undefined : Number.parseInt(options.limit, 10);
3032
- const deviceArgs = [...(options.device ?? []), ...(options.devices ?? [])];
3033
- const allFleet = deviceArgs.some((host) => ['all', 'fleet'].includes(host.toLowerCase()));
3034
- const hosts = [...(options.host ?? []), ...deviceArgs]
3035
- .filter((host) => !['all', 'fleet'].includes(host.toLowerCase()));
3036
- if (hosts.length > 0 || allFleet) {
3037
- const remoteRows = await gatherRemoteComputerSessionRows(allFleet ? undefined : hosts);
3038
- const rows = allFleet
3039
- ? [...buildComputerSessionRows({ machine: query }), ...remoteRows]
3040
- : remoteRows;
3041
- rows.sort((a, b) => b.endMs - a.endMs);
3042
- await runComputerSessionsCommand({ rows, machine: query, limit, json: options.json, interactive: options.interactive });
3043
- return;
3044
- }
3045
- await runComputerSessionsCommand({ machine: query, limit, json: options.json, interactive: options.interactive });
3046
- return;
3047
- }
3048
2716
  await sessionsAction(query, options, command.getOptionValueSource('limit'));
3049
2717
  });
3050
2718
  const previewCmd = sessionsCmd
@@ -3093,7 +2761,6 @@ export function registerSessionsCommands(program) {
3093
2761
  revision: options.revision,
3094
2762
  });
3095
2763
  });
3096
- registerSessionsTailCommand(sessionsCmd);
3097
2764
  registerSessionsResumeCommand(sessionsCmd);
3098
2765
  registerSessionsForkCommand(sessionsCmd);
3099
2766
  registerSessionsBookmarkCommand(sessionsCmd);
package/dist/index.js CHANGED
@@ -34,7 +34,8 @@ if (process.argv[2] === '__usage-ingest') {
34
34
  }
35
35
  if (process.argv[2] === '__usage-export') {
36
36
  const { exportClaudeUsageCacheRows } = await import('./lib/accounting/usage.js');
37
- process.stdout.write(JSON.stringify({ v: 1, rows: exportClaudeUsageCacheRows() }));
37
+ const { writeStdoutFlushed } = await import('./lib/stdout.js');
38
+ await writeStdoutFlushed(JSON.stringify({ v: 1, rows: exportClaudeUsageCacheRows() }));
38
39
  process.exit(0);
39
40
  }
40
41
  if (process.argv[2] === '__harness-update-run') {
@@ -123,19 +124,18 @@ if (process.argv[2] === 'sessions') {
123
124
  }
124
125
  }
125
126
  if (isReadQuery(forwarded, { filters, host })) {
126
- if (bin) {
127
- const { spawnSync } = await import('node:child_process');
128
- const { command, prefix } = invocation(bin);
129
- const res = spawnSync(command, [...prefix, ...forwarded], { stdio: 'inherit' });
130
- if (res.error) {
131
- process.stderr.write(`Failed to run \`sessions\`: ${res.error.message}\n`);
132
- process.exit(1);
133
- }
134
- process.exit(res.status ?? 1);
127
+ if (!bin) {
128
+ process.stderr.write(`agents: the standalone \`sessions\` CLI was not found. Install it with ${SESSIONS_INSTALL_HINT}, or point $SESSIONS_BIN at its executable.\n`);
129
+ process.exit(1);
135
130
  }
136
- if (process.env.AGENTS_SESSIONS_FASTPATH_HINT !== '0') {
137
- process.stderr.write(`agents: standalone \`sessions\` not installed; using the in-process engine (${SESSIONS_INSTALL_HINT})\n`);
131
+ const { spawnSync } = await import('node:child_process');
132
+ const { command, prefix } = invocation(bin);
133
+ const res = spawnSync(command, [...prefix, ...forwarded], { stdio: 'inherit' });
134
+ if (res.error) {
135
+ process.stderr.write(`Failed to run \`sessions\`: ${res.error.message}\n`);
136
+ process.exit(1);
138
137
  }
138
+ process.exit(res.status ?? 1);
139
139
  }
140
140
  }
141
141
  await import('./bootstrap.js');
@@ -1,5 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import { REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator } from '../ssh-exec.js';
3
+ import { writeStdoutFlushed } from '../stdout.js';
3
4
  import { ingestPeerClaudeUsageRows } from './usage.js';
4
5
  import { applyPeerFleetState, buildFleetStatePayload, formatFleetStateReply, parseFleetStateExchangeInput, publishOwnFleetState, } from './usage-sync.js';
5
6
  export class UsageIngestInputTooLargeError extends Error {
@@ -98,6 +99,6 @@ export async function runUsageIngest(argv = process.argv.slice(3)) {
98
99
  errors.push(...published.errors);
99
100
  for (const message of published.errors)
100
101
  process.stderr.write(`[agents] __usage-ingest: ${message}\n`);
101
- process.stdout.write(formatFleetStateReply(buildFleetStatePayload({ errors })));
102
+ await writeStdoutFlushed(formatFleetStateReply(buildFleetStatePayload({ errors })));
102
103
  return 0;
103
104
  }
@@ -1,5 +1,4 @@
1
1
  export declare const BROWSER_CONTEXT_FD = 3;
2
- export declare const BROWSER_EVENTS_FD = 4;
3
2
  export declare class BrowserClientError extends Error {
4
3
  code: string;
5
4
  constructor(code: string, message: string);
@@ -12,29 +11,9 @@ export declare function invocation(bin: string): {
12
11
  command: string;
13
12
  prefix: string[];
14
13
  };
15
- export interface BrowserActionEvent {
16
- event?: string;
17
- ts?: string;
18
- command: string;
19
- invocationId?: string;
20
- pid?: number;
21
- task?: string;
22
- profile?: string;
23
- url?: string;
24
- host?: string;
25
- sessionId?: string;
26
- launchId?: string;
27
- actor?: string;
28
- [key: string]: unknown;
29
- }
30
- export declare function parseEventLines(buffer: string): {
31
- events: BrowserActionEvent[];
32
- rest: string;
33
- };
34
14
  interface RunBrowserOptions {
35
15
  argv: string[];
36
16
  context: unknown;
37
- onEvent?: (event: BrowserActionEvent) => void;
38
17
  capture?: boolean;
39
18
  }
40
19
  interface RunBrowserResult {