@phnx-labs/agents-cli 1.22.126 → 1.22.128

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 (52) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +6 -15
  3. package/dist/commands/browser.js +4 -19
  4. package/dist/commands/computer.d.ts +2 -6
  5. package/dist/commands/computer.js +12 -18
  6. package/dist/commands/logs.js +2 -6
  7. package/dist/commands/sessions.d.ts +0 -11
  8. package/dist/commands/sessions.js +31 -364
  9. package/dist/index.js +12 -12
  10. package/dist/lib/accounting/usage-ingest.js +2 -1
  11. package/dist/lib/browser-client.d.ts +0 -21
  12. package/dist/lib/browser-client.js +1 -44
  13. package/dist/lib/computer/record.d.ts +1 -0
  14. package/dist/lib/computer/record.js +2 -16
  15. package/dist/lib/daemon/runner.js +3 -2
  16. package/dist/lib/device-config.d.ts +1 -1
  17. package/dist/lib/device-config.js +7 -7
  18. package/dist/lib/feed/tool-activity.d.ts +22 -10
  19. package/dist/lib/feed/tool-activity.js +161 -32
  20. package/dist/lib/feed/tools.d.ts +55 -2
  21. package/dist/lib/feed/tools.js +22 -28
  22. package/dist/lib/feed/watch.js +4 -3
  23. package/dist/lib/session/cloud.d.ts +0 -1
  24. package/dist/lib/session/cloud.js +0 -5
  25. package/dist/lib/session/db.d.ts +0 -64
  26. package/dist/lib/session/db.js +0 -116
  27. package/dist/lib/session/remote/remote-list.d.ts +2 -36
  28. package/dist/lib/session/remote/remote-list.js +3 -320
  29. package/dist/lib/session/tool-index.d.ts +0 -62
  30. package/dist/lib/session/tool-index.js +1 -537
  31. package/dist/lib/sessions-client.d.ts +1 -0
  32. package/dist/lib/sessions-client.js +17 -1
  33. package/dist/lib/standalone-tools.js +2 -2
  34. package/dist/lib/stdout.d.ts +1 -0
  35. package/dist/lib/stdout.js +5 -0
  36. package/package.json +1 -1
  37. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  38. package/dist/commands/browser-sessions-picker.js +0 -136
  39. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  40. package/dist/commands/computer-sessions-picker.js +0 -90
  41. package/dist/commands/sessions-tail.d.ts +0 -13
  42. package/dist/commands/sessions-tail.js +0 -222
  43. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  44. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  45. package/dist/lib/browser/paths.d.ts +0 -9
  46. package/dist/lib/browser/paths.js +0 -31
  47. package/dist/lib/browser/record.d.ts +0 -4
  48. package/dist/lib/browser/record.js +0 -19
  49. package/dist/lib/browser/sessions-list.d.ts +0 -79
  50. package/dist/lib/browser/sessions-list.js +0 -415
  51. package/dist/lib/computer/sessions-list.d.ts +0 -78
  52. package/dist/lib/computer/sessions-list.js +0 -372
@@ -11,7 +11,7 @@ import { watchLocalSessions } from '../session/watch.js';
11
11
  import { readBlock, readResolution, blockIdForSession } from './feed.js';
12
12
  import { reconcileAttention } from './attention.js';
13
13
  import { ActivityStream } from './activity-stream.js';
14
- import { collectToolRows, watchToolActivity } from './tool-activity.js';
14
+ import { watchToolActivity } from './tool-activity.js';
15
15
  import { FeedWatchState } from './envelope.js';
16
16
  import { FeedHub } from './hub.js';
17
17
  import { getCachedToolSetup, subscribeToolSetup } from '../setup-tool-status.js';
@@ -182,7 +182,8 @@ export async function watchLocalFeed(options) {
182
182
  const state = new FeedWatchState();
183
183
  const activity = new ActivityStream();
184
184
  let activityCursor = Date.now();
185
- let toolRows = collectToolRows(options.scope, options.tools?.sources).rows;
185
+ // The tool listings spawn processes; the first projection runs on the tool watcher so it never delays sessions or attention.
186
+ let toolRows = [];
186
187
  const readSetup = options.setup?.read ?? getCachedToolSetup;
187
188
  let setupRows = (() => {
188
189
  try {
@@ -234,7 +235,7 @@ export async function watchLocalFeed(options) {
234
235
  });
235
236
  }, options.activityPollMs ?? 500);
236
237
  const toolWatch = watchToolActivity({
237
- ...options.tools, scope: options.scope, signal: options.signal, initial: toolRows,
238
+ ...options.tools, scope: options.scope, signal: options.signal,
238
239
  onDiff: (diff) => {
239
240
  for (const tool of diff.upserts) {
240
241
  toolRows = [...toolRows.filter((row) => row.rowKey !== tool.rowKey), tool];
@@ -3,4 +3,3 @@ export declare function discoverCloudSessions(options?: {
3
3
  limit?: number;
4
4
  }): Promise<SessionMeta[]>;
5
5
  export declare function ensureCloudSessionCached(executionId: string, destPath?: string): Promise<string>;
6
- export declare function isCloudSessionPath(filePath: string): boolean;
@@ -87,8 +87,3 @@ export async function ensureCloudSessionCached(executionId, destPath) {
87
87
  fs.writeFileSync(finalPath, body);
88
88
  return finalPath;
89
89
  }
90
- export function isCloudSessionPath(filePath) {
91
- const root = path.resolve(CLOUD_CACHE_DIR);
92
- const resolved = path.resolve(filePath);
93
- return resolved.startsWith(root + path.sep);
94
- }
@@ -356,68 +356,4 @@ export declare function reindexMovedSessionPaths(moves: ReadonlyArray<{
356
356
  }>): number;
357
357
  export declare function updateSessionFilePaths(oldPrefix: string, newPrefix: string): number;
358
358
  export declare function countSessionsWithFilePrefix(prefix: string): number;
359
- interface BrowserCaptureCounts {
360
- screenshot: number;
361
- pdf: number;
362
- recording: number;
363
- download: number;
364
- }
365
- interface BrowserSessionRecord {
366
- task: string;
367
- profile: string;
368
- sessionId?: string;
369
- launchId?: string;
370
- actor?: string;
371
- machine?: string;
372
- startedAt?: number;
373
- lastActivity?: number;
374
- counts?: Partial<BrowserCaptureCounts>;
375
- captureDir?: string;
376
- capturesRemote?: string;
377
- }
378
- interface ComputerSessionRecord {
379
- invocationId: string;
380
- sessionId?: string;
381
- launchId?: string;
382
- actor?: string;
383
- machine?: string;
384
- startedAt?: number;
385
- lastActivity?: number;
386
- actionCount?: number;
387
- taskPreview?: string;
388
- }
389
- export declare function recordBrowserSession(record: BrowserSessionRecord): void;
390
- export declare function recordComputerSession(record: ComputerSessionRecord): void;
391
- interface StoredBrowserSession extends Required<Pick<BrowserSessionRecord, 'task' | 'profile'>> {
392
- sessionId?: string;
393
- launchId?: string;
394
- actor?: string;
395
- machine: string;
396
- startedAt: number;
397
- lastActivity?: number;
398
- counts: BrowserCaptureCounts;
399
- captureDir?: string;
400
- capturesRemote?: string;
401
- }
402
- export declare function listBrowserSessionRecords(profile?: string, opts?: {
403
- limit?: number;
404
- deviceKeys?: boolean;
405
- }): StoredBrowserSession[];
406
- export declare function getBrowserSessionRecord(profile: string, task: string): StoredBrowserSession | null;
407
- interface StoredComputerSession {
408
- invocationId: string;
409
- sessionId?: string;
410
- launchId?: string;
411
- actor?: string;
412
- machine: string;
413
- startedAt: number;
414
- lastActivity?: number;
415
- actionCount: number;
416
- taskPreview?: string;
417
- }
418
- export declare function pruneToolSessions(maxAgeDays?: number): number;
419
- export declare function listComputerSessionRecords(opts?: {
420
- limit?: number;
421
- startedBeforeMs?: number;
422
- }): StoredComputerSession[];
423
359
  export {};
@@ -14,10 +14,8 @@ import { buildClaudeAccountIndex, resolveClaudeAccount } from './claude-accounts
14
14
  import { extractBackgroundShells, extractSkills, extractSlashCommands, harnessTracksBackgroundShells, isSubAgentTool, } from '@phnx-labs/sessions-cli/reader';
15
15
  import { resolveResource } from '../resources.js';
16
16
  import { discoverPlugins } from '../plugins/plugins.js';
17
- import { machineId } from '../machine-id.js';
18
17
  import { firstUserMessageFromEvents, lastUserMessageFromEvents } from '@phnx-labs/sessions-cli/reader';
19
18
  import { emptyTimelineState, TIMELINE_EXTRACTOR_VERSION } from '@phnx-labs/sessions-cli/reader';
20
- import { profileScopeSql } from '../browser/paths.js';
21
19
  const SESSIONS_DIR = getSessionsDir();
22
20
  const DB_PATH = getSessionsDbPath();
23
21
  export const SCHEMA_VERSION = 52;
@@ -3516,117 +3514,3 @@ export function countSessionsWithFilePrefix(prefix) {
3516
3514
  .get(prefix + '%');
3517
3515
  return row.c;
3518
3516
  }
3519
- export function recordBrowserSession(record) {
3520
- const db = getDB();
3521
- const now = Date.now();
3522
- db.prepare(`
3523
- INSERT INTO browser_sessions (
3524
- task, profile, session_id, launch_id, actor, machine,
3525
- started_at, last_activity,
3526
- screenshot_count, pdf_count, recording_count, download_count,
3527
- capture_dir, captures_remote
3528
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3529
- ON CONFLICT(profile, task) DO UPDATE SET
3530
- session_id = COALESCE(excluded.session_id, browser_sessions.session_id),
3531
- launch_id = COALESCE(excluded.launch_id, browser_sessions.launch_id),
3532
- actor = COALESCE(excluded.actor, browser_sessions.actor),
3533
- last_activity = excluded.last_activity,
3534
- screenshot_count = excluded.screenshot_count,
3535
- pdf_count = excluded.pdf_count,
3536
- recording_count = excluded.recording_count,
3537
- download_count = excluded.download_count,
3538
- capture_dir = COALESCE(excluded.capture_dir, browser_sessions.capture_dir),
3539
- captures_remote = COALESCE(excluded.captures_remote, browser_sessions.captures_remote)
3540
- `).run(record.task, record.profile, record.sessionId ?? null, record.launchId ?? null, record.actor ?? null, record.machine ?? machineId(), record.startedAt ?? now, record.lastActivity ?? now, record.counts?.screenshot ?? 0, record.counts?.pdf ?? 0, record.counts?.recording ?? 0, record.counts?.download ?? 0, record.captureDir ?? null, record.capturesRemote ?? null);
3541
- }
3542
- export function recordComputerSession(record) {
3543
- const db = getDB();
3544
- const now = Date.now();
3545
- db.prepare(`
3546
- INSERT INTO computer_sessions (
3547
- invocation_id, session_id, launch_id, actor, machine,
3548
- started_at, last_activity, action_count, task_preview
3549
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
3550
- ON CONFLICT(invocation_id) DO UPDATE SET
3551
- session_id = COALESCE(excluded.session_id, computer_sessions.session_id),
3552
- launch_id = COALESCE(excluded.launch_id, computer_sessions.launch_id),
3553
- actor = COALESCE(excluded.actor, computer_sessions.actor),
3554
- last_activity = excluded.last_activity,
3555
- action_count = computer_sessions.action_count + excluded.action_count,
3556
- task_preview = COALESCE(excluded.task_preview, computer_sessions.task_preview)
3557
- `).run(record.invocationId, record.sessionId ?? null, record.launchId ?? null, record.actor ?? null, record.machine ?? machineId(), record.startedAt ?? now, record.lastActivity ?? now, record.actionCount ?? 1, record.taskPreview ?? null);
3558
- }
3559
- function toStoredBrowserSession(row) {
3560
- return {
3561
- task: row.task,
3562
- profile: row.profile,
3563
- sessionId: row.session_id ?? undefined,
3564
- launchId: row.launch_id ?? undefined,
3565
- actor: row.actor ?? undefined,
3566
- machine: row.machine,
3567
- startedAt: row.started_at,
3568
- lastActivity: row.last_activity ?? undefined,
3569
- counts: {
3570
- screenshot: row.screenshot_count,
3571
- pdf: row.pdf_count,
3572
- recording: row.recording_count,
3573
- download: row.download_count,
3574
- },
3575
- captureDir: row.capture_dir ?? undefined,
3576
- capturesRemote: row.captures_remote ?? undefined,
3577
- };
3578
- }
3579
- export function listBrowserSessionRecords(profile, opts = {}) {
3580
- const db = getDB();
3581
- const where = !profile ? undefined
3582
- : opts.deviceKeys ? profileScopeSql('profile', profile) : { sql: 'profile = ?', params: [profile] };
3583
- const limit = profile ? opts.limit : opts.limit ?? TOOL_SESSION_LIST_LIMIT;
3584
- const rows = db.prepare(`SELECT * FROM browser_sessions${where ? ` WHERE ${where.sql}` : ''} ORDER BY started_at DESC${limit === undefined ? '' : ' LIMIT ?'}`).all(...(where?.params ?? []), ...(limit === undefined ? [] : [limit]));
3585
- return rows.map(toStoredBrowserSession);
3586
- }
3587
- export function getBrowserSessionRecord(profile, task) {
3588
- const db = getDB();
3589
- const row = db
3590
- .prepare(`SELECT * FROM browser_sessions WHERE profile = ? AND task = ?`)
3591
- .get(profile, task);
3592
- return row ? toStoredBrowserSession(row) : null;
3593
- }
3594
- const TOOL_SESSION_MAX_AGE_DAYS = 365;
3595
- const TOOL_SESSION_LIST_LIMIT = 2000;
3596
- export function pruneToolSessions(maxAgeDays = TOOL_SESSION_MAX_AGE_DAYS) {
3597
- const db = getDB();
3598
- const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
3599
- const stale = db.prepare(`
3600
- SELECT 1 FROM computer_sessions WHERE started_at < ?
3601
- UNION ALL
3602
- SELECT 1 FROM browser_sessions WHERE started_at < ?
3603
- LIMIT 1
3604
- `).get(cutoff, cutoff);
3605
- if (!stale)
3606
- return 0;
3607
- const computer = db.prepare(`DELETE FROM computer_sessions WHERE started_at < ?`).run(cutoff);
3608
- const browser = db.prepare(`DELETE FROM browser_sessions WHERE started_at < ?`).run(cutoff);
3609
- return Number(computer.changes ?? 0) + Number(browser.changes ?? 0);
3610
- }
3611
- export function listComputerSessionRecords(opts = {}) {
3612
- const db = getDB();
3613
- const limit = opts.limit ?? TOOL_SESSION_LIST_LIMIT;
3614
- const rows = (opts.startedBeforeMs === undefined
3615
- ? db
3616
- .prepare(`SELECT * FROM computer_sessions ORDER BY started_at DESC LIMIT ?`)
3617
- .all(limit)
3618
- : db
3619
- .prepare(`SELECT * FROM computer_sessions WHERE started_at < ? ORDER BY started_at DESC LIMIT ?`)
3620
- .all(opts.startedBeforeMs, limit));
3621
- return rows.map((row) => ({
3622
- invocationId: row.invocation_id,
3623
- sessionId: row.session_id ?? undefined,
3624
- launchId: row.launch_id ?? undefined,
3625
- actor: row.actor ?? undefined,
3626
- machine: row.machine,
3627
- startedAt: row.started_at,
3628
- lastActivity: row.last_activity ?? undefined,
3629
- actionCount: row.action_count,
3630
- taskPreview: row.task_preview ?? undefined,
3631
- }));
3632
- }
@@ -1,29 +1,18 @@
1
1
  import { type DeviceProfile } from '../../devices/registry.js';
2
- import { type RemoteAgentsJsonParseResult } from '../../remote-agents-json.js';
3
2
  import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
4
- import { type ToolProgramCountEnvelope, type ToolSearchEnvelope } from '../tool-index.js';
5
- export { REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator } from '../../ssh-exec.js';
6
- export declare const REMOTE_TOOL_AGGREGATE_MAX_BYTES: number;
7
- interface RemoteToolByteBudget {
8
- remainingBytes: number;
9
- exhausted: boolean;
10
- }
11
- export declare function consumeRemoteToolByteBudget(budget: RemoteToolByteBudget, bytes: number): boolean;
12
- export declare function consumeParsedRemoteToolSearchBudget(budget: RemoteToolByteBudget, envelope: ToolSearchEnvelope): boolean;
13
3
  export declare function remoteListCommand(forwardedArgs: string[], os?: string): string;
14
4
  export declare function parseRemoteList(stdout: string, machine: string): SessionMeta[];
15
5
  export declare function parseRemoteListPayload(stdout: string, machine: string, safeResolver?: boolean): {
16
6
  items: SessionMeta[];
17
7
  valid: boolean;
18
8
  };
19
- export declare function sshCapture(target: string, remoteCmd: string, timeoutMs: number, aggregateBudget?: RemoteToolByteBudget, options?: {
9
+ export declare function sshCapture(target: string, remoteCmd: string, timeoutMs: number, options?: {
20
10
  multiplex?: boolean;
21
11
  port?: number;
22
12
  hostKeyOpts?: string[];
23
13
  }): Promise<{
24
14
  code: number | null;
25
15
  stdout: string;
26
- aggregateBudgetExceeded?: boolean;
27
16
  }>;
28
17
  interface RemoteListResult {
29
18
  sessions: SessionMeta[];
@@ -36,30 +25,6 @@ interface GatherRemoteListOptions {
36
25
  timeoutMs?: number;
37
26
  }
38
27
  export declare function gatherRemoteList(forwardedArgs: string[], hosts?: string[], opts?: GatherRemoteListOptions): Promise<RemoteListResult>;
39
- interface RemoteToolSearchResult {
40
- envelopes: Array<{
41
- machine: string;
42
- envelope: ToolSearchEnvelope;
43
- }>;
44
- deviceCount: number;
45
- unreachable: string[];
46
- truncated: string[];
47
- }
48
- interface RemoteToolProgramCountResult {
49
- envelopes: Array<{
50
- machine: string;
51
- envelope: ToolProgramCountEnvelope;
52
- }>;
53
- deviceCount: number;
54
- unreachable: string[];
55
- }
56
- export declare function parseRemoteToolProgramCount(stdout: string, machine: string, expectedProgram: string): RemoteAgentsJsonParseResult<{
57
- machine: string;
58
- envelope: ToolProgramCountEnvelope;
59
- }>;
60
- export declare function gatherRemoteToolProgramCounts(forwardedArgs: string[], hosts: string[] | undefined, expectedProgram: string): Promise<RemoteToolProgramCountResult>;
61
- export declare function parseRemoteToolSearch(stdout: string, machine: string, expectedClauses?: string[]): ToolSearchEnvelope | undefined;
62
- export declare function gatherRemoteToolSearch(forwardedArgs: string[], hosts?: string[], maxAggregateBytes?: number, expectedClauses?: string[]): Promise<RemoteToolSearchResult>;
63
28
  export declare function resolvePeerTarget(machine: string): Promise<{
64
29
  target: string;
65
30
  os?: string;
@@ -84,3 +49,4 @@ export declare function runOnPeer(args: string[], machine: string, opts?: {
84
49
  env?: Record<string, string>;
85
50
  sessionId?: string;
86
51
  }): Promise<'ok' | 'no-target' | 'unreachable'>;
52
+ export {};
@@ -3,34 +3,12 @@ import chalk from 'chalk';
3
3
  import { SSH_OPTS, controlOpts, assertValidSshTarget, shellQuote, SSH_CONN_FAILURE_CODE, REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator, } from '../../ssh-exec.js';
4
4
  import { connectionEndedNotice } from '../../hosts/reconnect.js';
5
5
  import { sshTargetFor } from '../../devices/connect.js';
6
- import { resolveExplicitTargetSet } from '../../devices/resolve-target.js';
7
6
  import { loadDevices, isDialableDevice } from '../../devices/registry.js';
8
7
  import { remoteShellFor, buildWindowsAgentsCommand, stripClixml } from '../../hosts/remote-cmd.js';
9
8
  import { gatherRemoteAgentsJson } from '../../remote-agents-json.js';
10
- import { machineId, normalizeHost } from '../sync/config.js';
9
+ import { normalizeHost } from '../sync/config.js';
11
10
  import { NO_FANOUT_ENV } from '../remote-active.js';
12
11
  import { terminalWidth } from '../../text/width.js';
13
- import { sanitizeForTerminal } from '../../redact.js';
14
- import { mapBounded } from '../../concurrency.js';
15
- import { TOOL_QUERY_MAX_CLAUSE_BYTES, TOOL_QUERY_MAX_CALL_ROWS, TOOL_QUERY_MAX_CLAUSES, TOOL_QUERY_MAX_RESULT_SESSIONS, TOOL_QUERY_MAX_SERIALIZED_BYTES, serializedToolSearchEnvelopeBytes, } from '../tool-index.js';
16
- import { TOOL_ERROR_OUTPUT_MAX_BYTES, TOOL_INPUT_MAX_BYTES, TOOL_SUCCESS_OUTPUT_MAX_BYTES, sanitizeToolEvidenceText, } from '@phnx-labs/sessions-cli/reader';
17
- const REMOTE_TOOL_TIMEOUT_MS = 60_000;
18
- export { REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator } from '../../ssh-exec.js';
19
- export const REMOTE_TOOL_AGGREGATE_MAX_BYTES = TOOL_QUERY_MAX_SERIALIZED_BYTES;
20
- export function consumeRemoteToolByteBudget(budget, bytes) {
21
- if (budget.exhausted || bytes > budget.remainingBytes) {
22
- budget.remainingBytes = 0;
23
- budget.exhausted = true;
24
- return false;
25
- }
26
- budget.remainingBytes -= bytes;
27
- if (budget.remainingBytes === 0)
28
- budget.exhausted = true;
29
- return true;
30
- }
31
- export function consumeParsedRemoteToolSearchBudget(budget, envelope) {
32
- return consumeRemoteToolByteBudget(budget, serializedToolSearchEnvelopeBytes(envelope));
33
- }
34
12
  export function remoteListCommand(forwardedArgs, os) {
35
13
  if (remoteShellFor(os) === 'powershell') {
36
14
  return buildWindowsAgentsCommand({
@@ -86,7 +64,7 @@ export function parseRemoteListPayload(stdout, machine, safeResolver = false) {
86
64
  }
87
65
  return { items: out, valid: true };
88
66
  }
89
- export function sshCapture(target, remoteCmd, timeoutMs, aggregateBudget, options = {}) {
67
+ export function sshCapture(target, remoteCmd, timeoutMs, options = {}) {
90
68
  assertValidSshTarget(target);
91
69
  return new Promise((resolve) => {
92
70
  const args = [
@@ -100,7 +78,6 @@ export function sshCapture(target, remoteCmd, timeoutMs, aggregateBudget, option
100
78
  const child = spawn('ssh', args, { stdio: ['ignore', 'pipe', 'ignore'] });
101
79
  const decoded = new RemoteUtf8Accumulator();
102
80
  let stdoutBytes = 0;
103
- let aggregateBudgetExceeded = false;
104
81
  let settled = false;
105
82
  const done = (code) => {
106
83
  if (settled)
@@ -108,7 +85,7 @@ export function sshCapture(target, remoteCmd, timeoutMs, aggregateBudget, option
108
85
  settled = true;
109
86
  clearTimeout(timer);
110
87
  const stdout = code === null ? decoded.current() : decoded.end();
111
- resolve({ code, stdout, aggregateBudgetExceeded: aggregateBudgetExceeded || undefined });
88
+ resolve({ code, stdout });
112
89
  };
113
90
  const timer = setTimeout(() => { child.kill('SIGKILL'); done(null); }, timeoutMs);
114
91
  child.stdout.on('data', (d) => {
@@ -117,12 +94,6 @@ export function sshCapture(target, remoteCmd, timeoutMs, aggregateBudget, option
117
94
  done(null);
118
95
  return;
119
96
  }
120
- if (aggregateBudget && !consumeRemoteToolByteBudget(aggregateBudget, d.byteLength)) {
121
- aggregateBudgetExceeded = true;
122
- child.kill('SIGKILL');
123
- done(null);
124
- return;
125
- }
126
97
  stdoutBytes += d.byteLength;
127
98
  decoded.write(d);
128
99
  });
@@ -157,294 +128,6 @@ export async function gatherRemoteList(forwardedArgs, hosts, opts) {
157
128
  ],
158
129
  };
159
130
  }
160
- export function parseRemoteToolProgramCount(stdout, machine, expectedProgram) {
161
- try {
162
- const parsed = JSON.parse(stdout);
163
- const query = parsed.query;
164
- const coverage = parsed.coverage;
165
- const totals = parsed.totals;
166
- const machines = parsed.machines;
167
- const coverageKeys = ['indexedFiles', 'indexedCalls', 'skippedFiles', 'limitedFiles', 'remainingFiles'];
168
- const totalKeys = ['occurrences', 'toolCalls', 'sessions'];
169
- if (parsed.schemaVersion !== 1 || parsed.kind !== 'tool-program-count'
170
- || !query || query.program !== expectedProgram || query.semantics !== 'static-program-occurrences-v1'
171
- || !coverage || typeof coverage.complete !== 'boolean'
172
- || coverageKeys.some((key) => !Number.isSafeInteger(coverage[key]) || coverage[key] < 0)
173
- || !totals || totalKeys.some((key) => !Number.isSafeInteger(totals[key]) || totals[key] < 0)
174
- || !Array.isArray(machines) || machines.length !== 1
175
- || boundedRemoteString(parsed.generatedAt, 128) === undefined) {
176
- return { items: [], valid: false };
177
- }
178
- return {
179
- valid: true,
180
- items: [{
181
- machine,
182
- envelope: {
183
- schemaVersion: 1,
184
- kind: 'tool-program-count',
185
- generatedAt: parsed.generatedAt,
186
- query: { program: expectedProgram, semantics: 'static-program-occurrences-v1' },
187
- coverage: coverage,
188
- totals: totals,
189
- machines: [{
190
- machine,
191
- coverage: coverage,
192
- totals: totals,
193
- }],
194
- },
195
- }],
196
- };
197
- }
198
- catch {
199
- return { items: [], valid: false };
200
- }
201
- }
202
- export async function gatherRemoteToolProgramCounts(forwardedArgs, hosts, expectedProgram) {
203
- const result = await gatherRemoteAgentsJson({
204
- args: forwardedArgs,
205
- noFanoutEnv: NO_FANOUT_ENV,
206
- hosts,
207
- timeoutMs: REMOTE_TOOL_TIMEOUT_MS,
208
- parse: (stdout, machine) => parseRemoteToolProgramCount(stdout, machine, expectedProgram),
209
- });
210
- return {
211
- envelopes: result.items,
212
- deviceCount: result.deviceCount,
213
- unreachable: [
214
- ...(result.discoveryFailed ? ['device registry'] : []),
215
- ...result.skipped,
216
- ...result.parseFailed,
217
- ],
218
- };
219
- }
220
- function boundedRemoteString(value, maxBytes) {
221
- if (typeof value !== 'string' || Buffer.byteLength(value) > maxBytes)
222
- return undefined;
223
- return sanitizeToolEvidenceText(value, maxBytes);
224
- }
225
- function optionalRemoteString(value, maxBytes) {
226
- if (value === undefined || value === null)
227
- return undefined;
228
- return boundedRemoteString(value, maxBytes) ?? null;
229
- }
230
- function parseRemoteCall(value) {
231
- if (!value || typeof value !== 'object' || Array.isArray(value))
232
- return undefined;
233
- const call = value;
234
- const id = boundedRemoteString(call.id, 512);
235
- const timestamp = boundedRemoteString(call.timestamp, 128);
236
- const tool = boundedRemoteString(call.tool, 512);
237
- const input = boundedRemoteString(call.input, TOOL_INPUT_MAX_BYTES);
238
- const sourceCallId = optionalRemoteString(call.sourceCallId, 512);
239
- const output = optionalRemoteString(call.output, TOOL_SUCCESS_OUTPUT_MAX_BYTES);
240
- const error = optionalRemoteString(call.error, TOOL_ERROR_OUTPUT_MAX_BYTES);
241
- const errorCode = optionalRemoteString(call.errorCode, 512);
242
- const parseError = optionalRemoteString(call.parseError, 1024);
243
- if (call.programs !== undefined
244
- && (!Array.isArray(call.programs) || call.programs.length > 128))
245
- return undefined;
246
- const programs = Array.isArray(call.programs)
247
- ? call.programs.map((program) => boundedRemoteString(program, 512))
248
- : [];
249
- if (!Array.isArray(call.programOccurrences) || call.programOccurrences.length > 10_000)
250
- return undefined;
251
- const programOccurrences = call.programOccurrences.map((value) => {
252
- if (!value || typeof value !== 'object' || Array.isArray(value))
253
- return undefined;
254
- const occurrence = value;
255
- const program = boundedRemoteString(occurrence.program, 512);
256
- if (!program || (occurrence.role !== 'wrapper' && occurrence.role !== 'effective'))
257
- return undefined;
258
- return { program, role: occurrence.role };
259
- });
260
- if (!id || !timestamp || !tool || input === undefined
261
- || !Number.isSafeInteger(call.ordinal) || call.ordinal < 0
262
- || !['ok', 'error', 'unknown'].includes(String(call.outcome))
263
- || sourceCallId === null || output === null || error === null || errorCode === null || parseError === null
264
- || programs.some((program) => program === undefined)
265
- || programOccurrences.some((occurrence) => occurrence === undefined))
266
- return undefined;
267
- for (const code of [call.exitCode, call.statusCode]) {
268
- if (code !== undefined && (!Number.isSafeInteger(code) || code < 0))
269
- return undefined;
270
- }
271
- return {
272
- id,
273
- ordinal: call.ordinal,
274
- sourceCallId,
275
- timestamp,
276
- tool,
277
- programs: programs,
278
- programOccurrences: programOccurrences,
279
- input,
280
- outcome: call.outcome,
281
- exitCode: call.exitCode,
282
- statusCode: call.statusCode,
283
- errorCode,
284
- output,
285
- error,
286
- parseError,
287
- };
288
- }
289
- function parseRemoteToolSession(value, machine) {
290
- if (!value || typeof value !== 'object' || Array.isArray(value))
291
- return undefined;
292
- const session = value;
293
- const id = boundedRemoteString(session.id, 512);
294
- const shortId = boundedRemoteString(session.shortId, 128);
295
- const agent = boundedRemoteString(session.agent, 128);
296
- const timestamp = boundedRemoteString(session.timestamp, 128);
297
- const project = optionalRemoteString(session.project, 4096);
298
- const cwd = optionalRemoteString(session.cwd, 4096);
299
- const topic = optionalRemoteString(session.topic, 4096);
300
- const label = optionalRemoteString(session.label, 4096);
301
- const originMachine = optionalRemoteString(session.machine, 512);
302
- const dialedMachine = boundedRemoteString(machine, 512);
303
- if (!id || !shortId || !agent || !timestamp || !dialedMachine || originMachine === null
304
- || project === null || cwd === null || topic === null || label === null
305
- || !Array.isArray(session.calls) || session.calls.length > TOOL_QUERY_MAX_CALL_ROWS)
306
- return undefined;
307
- const calls = session.calls.map(parseRemoteCall);
308
- if (calls.some((call) => call === undefined))
309
- return undefined;
310
- return {
311
- id,
312
- shortId,
313
- agent,
314
- machine: originMachine ?? dialedMachine,
315
- timestamp,
316
- project,
317
- cwd,
318
- topic,
319
- label,
320
- calls: calls,
321
- };
322
- }
323
- export function parseRemoteToolSearch(stdout, machine, expectedClauses) {
324
- stdout = stripClixml(stdout);
325
- if (Buffer.byteLength(stdout) > REMOTE_STDOUT_MAX_BYTES)
326
- return undefined;
327
- try {
328
- const parsed = JSON.parse(stdout);
329
- const coverage = parsed?.coverage;
330
- const query = parsed?.query;
331
- if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.sessions)
332
- || parsed.sessions.length > TOOL_QUERY_MAX_RESULT_SESSIONS || !coverage || !query
333
- || !Array.isArray(query.clauses) || query.clauses.length > TOOL_QUERY_MAX_CLAUSES
334
- || query.clauses.some((clause) => boundedRemoteString(clause, TOOL_QUERY_MAX_CLAUSE_BYTES) === undefined))
335
- return undefined;
336
- let totalCalls = 0;
337
- for (const sessionValue of parsed.sessions) {
338
- if (!sessionValue || typeof sessionValue !== 'object' || Array.isArray(sessionValue))
339
- return undefined;
340
- const calls = sessionValue.calls;
341
- if (!Array.isArray(calls) || calls.length > TOOL_QUERY_MAX_CALL_ROWS)
342
- return undefined;
343
- totalCalls += calls.length;
344
- if (totalCalls > TOOL_QUERY_MAX_CALL_ROWS)
345
- return undefined;
346
- }
347
- const clauses = query.clauses.map((clause) => sanitizeForTerminal(clause));
348
- const expected = expectedClauses?.map((clause) => sanitizeForTerminal(clause));
349
- if (expected && (clauses.length !== expected.length
350
- || clauses.some((clause, index) => clause !== expected[index])))
351
- return undefined;
352
- const coverageNumbers = ['indexedFiles', 'indexedCalls', 'skippedFiles', 'limitedFiles', 'remainingFiles'];
353
- if (coverageNumbers.some((key) => !Number.isSafeInteger(coverage[key]) || coverage[key] < 0)
354
- || typeof coverage.complete !== 'boolean')
355
- return undefined;
356
- const sessions = parsed.sessions.map((session) => parseRemoteToolSession(session, machine));
357
- const generatedAt = boundedRemoteString(parsed.generatedAt, 128);
358
- if (!generatedAt || sessions.some((session) => session === undefined))
359
- return undefined;
360
- return {
361
- schemaVersion: 1,
362
- generatedAt,
363
- query: { clauses },
364
- coverage: {
365
- indexedFiles: coverage.indexedFiles,
366
- indexedCalls: coverage.indexedCalls,
367
- skippedFiles: coverage.skippedFiles,
368
- limitedFiles: coverage.limitedFiles,
369
- remainingFiles: coverage.remainingFiles,
370
- complete: coverage.complete,
371
- },
372
- sessions: sessions,
373
- };
374
- }
375
- catch {
376
- return undefined;
377
- }
378
- }
379
- export async function gatherRemoteToolSearch(forwardedArgs, hosts, maxAggregateBytes = REMOTE_TOOL_AGGREGATE_MAX_BYTES, expectedClauses = []) {
380
- const self = machineId();
381
- const targets = [];
382
- const unresolved = [];
383
- if (hosts && hosts.length > 0) {
384
- const resolved = await resolveExplicitTargetSet(hosts);
385
- targets.push(...resolved.targets);
386
- unresolved.push(...resolved.unresolved);
387
- }
388
- else {
389
- let reg;
390
- try {
391
- reg = await loadDevices();
392
- }
393
- catch {
394
- return { envelopes: [], deviceCount: 0, unreachable: ['device registry'], truncated: [] };
395
- }
396
- for (const d of Object.values(reg)) {
397
- if (!isAutomaticSessionPeer(d, self))
398
- continue;
399
- try {
400
- targets.push({ target: sshTargetFor(d), machine: normalizeHost(d.name), name: d.name, os: d.platform });
401
- }
402
- catch {
403
- }
404
- }
405
- }
406
- const remainingBytes = Math.max(0, Math.min(REMOTE_TOOL_AGGREGATE_MAX_BYTES, maxAggregateBytes));
407
- const aggregateBudget = {
408
- remainingBytes,
409
- exhausted: remainingBytes === 0,
410
- };
411
- const parsedBudget = {
412
- remainingBytes,
413
- exhausted: remainingBytes === 0,
414
- };
415
- const results = await mapBounded(targets, async (target) => {
416
- if (aggregateBudget.exhausted)
417
- return { target, truncated: target.name };
418
- const capture = await sshCapture(target.target, remoteListCommand(forwardedArgs, target.os), REMOTE_TOOL_TIMEOUT_MS, aggregateBudget, { multiplex: false });
419
- if (capture.aggregateBudgetExceeded)
420
- return { target, truncated: target.name };
421
- if (capture.code !== 0)
422
- return { target, unreachable: target.name };
423
- const envelope = parseRemoteToolSearch(capture.stdout, target.machine, expectedClauses);
424
- if (!envelope)
425
- return { target, unreachable: target.name };
426
- if (!consumeParsedRemoteToolSearchBudget(parsedBudget, envelope)) {
427
- return { target, truncated: target.name };
428
- }
429
- return { target, envelope };
430
- }, { concurrency: 6 });
431
- for (const result of results) {
432
- if (result.unreachable) {
433
- process.stderr.write(chalk.gray(` ${result.unreachable}: unreachable, incompatible, or no agents CLI — skipped\n`));
434
- }
435
- if (result.truncated) {
436
- process.stderr.write(chalk.gray(` ${result.truncated}: fleet tool-result budget exhausted — skipped\n`));
437
- }
438
- }
439
- return {
440
- envelopes: results.flatMap((result) => result.envelope
441
- ? [{ machine: result.target.machine, envelope: result.envelope }]
442
- : []),
443
- deviceCount: targets.length,
444
- unreachable: [...unresolved, ...results.map((result) => result.unreachable).filter((name) => !!name)],
445
- truncated: results.map((result) => result.truncated).filter((name) => !!name),
446
- };
447
- }
448
131
  export async function resolvePeerTarget(machine) {
449
132
  let reg;
450
133
  try {