@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
@@ -1,31 +1,149 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import * as fs from 'node:fs';
2
3
  import * as path from 'node:path';
3
- import { getBrowserRuntimeDir, getHistoryDir } from '../state.js';
4
+ import { getBrowserRuntimeDir, getCacheDir } from '../state.js';
4
5
  import { getEventsDir } from './events.js';
5
- import { readBrowserSessionRows } from '../browser/sessions-list.js';
6
- import { buildComputerSessionRows, standaloneComputerActionsDir } from '../computer/sessions-list.js';
6
+ import { readRecentActivity } from './activity.js';
7
+ import { invocation as browserInvocation, resolveBrowserBin } from '../browser-client.js';
8
+ import { invocation as computerInvocation, resolveComputerBin } from '../computer-client.js';
9
+ import { getSessionById } from '../session/db.js';
10
+ import { loadHookSessionIndex } from '../session/hook-sessions.js';
11
+ import { listPidSessionEntries } from '../session/pid-registry.js';
7
12
  import { boundBrowserRow, projectBrowserToolRow, projectComputerToolRow, sortToolRows } from './tools.js';
8
13
  export const TOOL_SWEEP_MS = 5_000;
9
14
  const TOOL_COMPUTER_LIMIT = 500;
10
- export function collectToolRows(scope, sources = {}) {
11
- let complete = true;
12
- const read = (source, empty) => {
15
+ const TOOL_JSON_MAX_BYTES = 64 * 1024 * 1024;
16
+ const TOOL_JSON_TIMEOUT_MS = 30_000;
17
+ export class ToolNotInstalledError extends Error {
18
+ }
19
+ function resolveTool(tool) {
20
+ let bin;
21
+ try {
22
+ bin = tool === 'browser' ? resolveBrowserBin() : resolveComputerBin();
23
+ }
24
+ catch (error) {
25
+ throw new ToolNotInstalledError(`${error.message}\nRun \`agents setup tools\` to install the pinned \`${tool}\` CLI.`);
26
+ }
27
+ return tool === 'browser' ? browserInvocation(bin) : computerInvocation(bin);
28
+ }
29
+ /** Runs a standalone tool's `--json` listing; any failure rejects so the snapshot is reported incomplete. */
30
+ export async function readToolJson(tool, argv) {
31
+ const { command, prefix } = resolveTool(tool);
32
+ const label = `\`${tool} ${argv.join(' ')}\``;
33
+ return new Promise((resolve, reject) => {
34
+ const child = spawn(command, [...prefix, ...argv], { stdio: ['ignore', 'pipe', 'pipe'] });
35
+ const stdout = [];
36
+ let stdoutBytes = 0;
37
+ let stderr = '';
38
+ let failure;
39
+ const fail = (error) => { failure ??= error; child.kill('SIGKILL'); };
40
+ const timer = setTimeout(() => fail(new Error(`${label} did not finish within ${TOOL_JSON_TIMEOUT_MS / 1000}s`)), TOOL_JSON_TIMEOUT_MS);
41
+ child.stdout.on('data', (chunk) => {
42
+ stdoutBytes += chunk.length;
43
+ if (stdoutBytes > TOOL_JSON_MAX_BYTES)
44
+ fail(new Error(`${label} printed more than ${TOOL_JSON_MAX_BYTES} bytes`));
45
+ else
46
+ stdout.push(chunk);
47
+ });
48
+ child.stderr.on('data', (chunk) => { if (stderr.length < 4096)
49
+ stderr += chunk.toString('utf8'); });
50
+ child.on('error', (error) => fail(new Error(`${label} failed: ${error.message}`)));
51
+ child.on('close', (code, signal) => {
52
+ clearTimeout(timer);
53
+ if (failure)
54
+ return reject(failure);
55
+ if (code !== 0)
56
+ return reject(new Error(`${label} exited ${code ?? signal}: ${stderr.trim().slice(0, 500)}`));
57
+ let value;
58
+ try {
59
+ value = JSON.parse(Buffer.concat(stdout).toString('utf8'));
60
+ }
61
+ catch (error) {
62
+ return reject(new Error(`${label} printed unparseable JSON: ${error.message}`));
63
+ }
64
+ if (!Array.isArray(value))
65
+ return reject(new Error(`${label} printed ${typeof value}, expected an array of rows`));
66
+ resolve(value);
67
+ });
68
+ });
69
+ }
70
+ function isRecord(value) {
71
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
72
+ }
73
+ export async function readStandaloneBrowserRows() {
74
+ return (await readToolJson('browser', ['sessions', '--tasks', '--json', '--no-interactive'])).map((row, index) => {
75
+ if (!isRecord(row) || typeof row.profile !== 'string' || !Array.isArray(row.artifacts)
76
+ || !isRecord(row.counts) || typeof row.latestMtimeMs !== 'number') {
77
+ throw new Error(`\`browser sessions --json\` row ${index} lacks profile, artifacts, counts or latestMtimeMs`);
78
+ }
79
+ return row;
80
+ });
81
+ }
82
+ export async function readStandaloneComputerRows() {
83
+ return (await readToolJson('computer', ['sessions', '--json', '--no-interactive', '--limit', String(TOOL_COMPUTER_LIMIT)])).map((row, index) => {
84
+ if (!isRecord(row) || typeof row.machine !== 'string' || !Array.isArray(row.actions)
85
+ || !isRecord(row.counts) || typeof row.startMs !== 'number' || typeof row.endMs !== 'number') {
86
+ throw new Error(`\`computer sessions --json\` row ${index} lacks machine, actions, counts or startMs/endMs`);
87
+ }
88
+ return row;
89
+ });
90
+ }
91
+ function buildLaunchSessionIndex() {
92
+ const byLaunchId = new Map();
93
+ for (const event of readRecentActivity({ maxBytesPerSession: 64 * 1024 })) {
94
+ if (event.launchId && event.sessionId)
95
+ byLaunchId.set(event.launchId, event.sessionId);
96
+ }
97
+ for (const [launchId, record] of loadHookSessionIndex().byLaunchId) {
98
+ if (record.session_id)
99
+ byLaunchId.set(launchId, record.session_id);
100
+ }
101
+ for (const entry of listPidSessionEntries()) {
102
+ if (entry.launchId && entry.sessionId)
103
+ byLaunchId.set(entry.launchId, entry.sessionId);
104
+ }
105
+ return byLaunchId;
106
+ }
107
+ /** The tools record a session or launch id; only agents-cli's index can say which agent session that was. */
108
+ export function linkToolSessions(rows) {
109
+ let byLaunchId;
110
+ return rows.map((row) => {
111
+ let linked = row.sessionId ? getSessionById(row.sessionId) : null;
112
+ if (!linked && row.launchId) {
113
+ byLaunchId ??= buildLaunchSessionIndex();
114
+ const sessionId = byLaunchId.get(row.launchId);
115
+ linked = sessionId ? getSessionById(sessionId) : null;
116
+ }
117
+ return linked ? { ...row, linkedSession: linked } : row;
118
+ });
119
+ }
120
+ export async function collectToolRows(scope, sources = {}) {
121
+ const incomplete = new Set();
122
+ let retry = false;
123
+ const read = async (kind, source, empty) => {
13
124
  try {
14
- return source();
125
+ return await source();
15
126
  }
16
- catch {
17
- complete = false;
127
+ catch (error) {
128
+ incomplete.add(kind);
129
+ if (!(error instanceof ToolNotInstalledError))
130
+ retry = true;
18
131
  return empty;
19
132
  }
20
133
  };
134
+ const [bindingList, liveTaskList, browserRows, computerRows] = await Promise.all([
135
+ read('browser', sources.bindings ?? (() => []), []),
136
+ read('browser', sources.liveTasks ?? (() => readLiveBrowserTasks()), []),
137
+ read('browser', sources.browserRows ?? (async () => linkToolSessions(await readStandaloneBrowserRows())), []),
138
+ read('computer', sources.computerRows ?? (async () => linkToolSessions(await readStandaloneComputerRows())), []),
139
+ ]);
21
140
  const bindings = new Map();
22
- for (const binding of read(sources.bindings ?? (() => []), []))
141
+ for (const binding of bindingList)
23
142
  bindings.set(binding.name, binding);
24
143
  const liveTasks = new Map();
25
- for (const task of read(sources.liveTasks ?? (() => readLiveBrowserTasks()), []))
144
+ for (const task of liveTaskList)
26
145
  liveTasks.set(task.task, task);
27
146
  const rows = [];
28
- const browserRows = read(sources.browserRows ?? (() => readBrowserSessionRows()), []);
29
147
  const captured = new Set();
30
148
  for (const row of browserRows) {
31
149
  if (row.task)
@@ -39,27 +157,27 @@ export function collectToolRows(scope, sources = {}) {
39
157
  const live = liveTasks.get(task);
40
158
  rows.push(projectBrowserToolRow(scope, boundBrowserRow(task, live ?? binding ?? {}), binding, live));
41
159
  }
42
- const computerRows = read(sources.computerRows ?? (() => buildComputerSessionRows({ limit: TOOL_COMPUTER_LIMIT, observer: scope })), []);
43
160
  for (const row of computerRows)
44
161
  rows.push(projectComputerToolRow(scope, row));
45
- return { rows: sortToolRows(rows), complete };
162
+ return { rows: sortToolRows(rows.filter((row) => !incomplete.has(row.kind))), incomplete: [...incomplete], retry };
46
163
  }
47
164
  export class ToolRowSet {
48
165
  rows = new Map();
49
- diff(next) {
166
+ // A kind whose read failed keeps the rows it last published: a failed read is not "every task closed".
167
+ diff(next, unreadKinds = []) {
50
168
  const upserts = [];
51
169
  const seen = new Set();
52
170
  for (const row of next) {
53
171
  seen.add(row.rowKey);
54
172
  const serialized = JSON.stringify(row);
55
- if (this.rows.get(row.rowKey) === serialized)
173
+ if (this.rows.get(row.rowKey)?.serialized === serialized)
56
174
  continue;
57
- this.rows.set(row.rowKey, serialized);
175
+ this.rows.set(row.rowKey, { kind: row.kind, serialized });
58
176
  upserts.push(row);
59
177
  }
60
178
  const removes = [];
61
- for (const key of [...this.rows.keys()]) {
62
- if (seen.has(key))
179
+ for (const [key, { kind }] of [...this.rows]) {
180
+ if (seen.has(key) || unreadKinds.includes(kind))
63
181
  continue;
64
182
  this.rows.delete(key);
65
183
  removes.push(key);
@@ -69,11 +187,13 @@ export class ToolRowSet {
69
187
  reset(rows) {
70
188
  this.rows.clear();
71
189
  for (const row of rows)
72
- this.rows.set(row.rowKey, JSON.stringify(row));
190
+ this.rows.set(row.rowKey, { kind: row.kind, serialized: JSON.stringify(row) });
73
191
  }
74
192
  }
75
- export function toolWatchRoots() {
76
- return [getBrowserRuntimeDir(), path.join(getHistoryDir(), 'browser'), getEventsDir(), standaloneComputerActionsDir()];
193
+ // Only roots the tools append to while they act: their history databases are
194
+ // written by the very listings this watcher runs, so watching those would loop.
195
+ function toolWatchRoots() {
196
+ return [getBrowserRuntimeDir(), getEventsDir(), path.join(getCacheDir(), 'computer', 'actions')];
77
197
  }
78
198
  function readLiveTasksFor(profileDir) {
79
199
  const file = path.join(profileDir, 'tasks.json');
@@ -171,24 +291,33 @@ export function watchToolActivity(options) {
171
291
  for (const root of roots)
172
292
  armRoot(root);
173
293
  const armed = () => [...watchers.values()].every((watcher) => watcher !== undefined);
174
- const reproject = () => {
175
- const snapshot = collectToolRows(options.scope, options.sources);
176
- if (!snapshot.complete) {
177
- dirty = true;
178
- return;
294
+ let projecting = false;
295
+ const reproject = async () => {
296
+ projecting = true;
297
+ try {
298
+ const snapshot = await collectToolRows(options.scope, options.sources);
299
+ if (stopped)
300
+ return;
301
+ if (snapshot.retry)
302
+ dirty = true;
303
+ const diff = set.diff(snapshot.rows, snapshot.incomplete);
304
+ if (diff.upserts.length > 0 || diff.removes.length > 0)
305
+ options.onDiff(diff);
306
+ }
307
+ finally {
308
+ projecting = false;
179
309
  }
180
- const diff = set.diff(snapshot.rows);
181
- if (diff.upserts.length > 0 || diff.removes.length > 0)
182
- options.onDiff(diff);
183
310
  };
184
311
  const timer = setInterval(() => {
185
312
  for (const root of roots)
186
313
  armRoot(root);
187
- if (armed() && !dirty)
314
+ if (projecting || (armed() && !dirty))
188
315
  return;
189
316
  dirty = false;
190
- reproject();
317
+ void reproject();
191
318
  }, options.sweepMs ?? TOOL_SWEEP_MS);
319
+ if (!options.initial)
320
+ void reproject();
192
321
  const stop = () => {
193
322
  stopped = true;
194
323
  clearInterval(timer);
@@ -1,5 +1,58 @@
1
- import type { BrowserSessionRow, ArtifactKind } from '../browser/sessions-list.js';
2
- import type { ComputerRunRow } from '../computer/sessions-list.js';
1
+ import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
2
+ export type ArtifactKind = 'screenshot' | 'pdf' | 'recording' | 'download';
3
+ export interface BrowserArtifact {
4
+ kind: ArtifactKind;
5
+ task?: string;
6
+ name: string;
7
+ path: string;
8
+ bytes: number;
9
+ mtimeMs: number;
10
+ }
11
+ export interface BrowserSessionRow {
12
+ kind: 'task' | 'downloads';
13
+ profile: string;
14
+ task?: string;
15
+ launchId?: string;
16
+ sessionId?: string;
17
+ linkedSession?: SessionMeta;
18
+ artifacts: BrowserArtifact[];
19
+ counts: Record<ArtifactKind, number>;
20
+ latestMtimeMs: number;
21
+ startedAt?: number;
22
+ machine?: string;
23
+ captureDir?: string;
24
+ capturesRemote?: string;
25
+ }
26
+ export interface ComputerAction {
27
+ verb: string;
28
+ tsMs: number;
29
+ host?: string;
30
+ bundle?: string;
31
+ capture?: {
32
+ kind: 'screenshot';
33
+ path: string;
34
+ name: string;
35
+ bytes?: number;
36
+ };
37
+ }
38
+ export interface ComputerRunRow {
39
+ pid?: number;
40
+ invocationId?: string;
41
+ task?: string;
42
+ machine: string;
43
+ remoteHost?: string;
44
+ bundle?: string;
45
+ sessionId?: string;
46
+ launchId?: string;
47
+ linkedSession?: SessionMeta;
48
+ actions: ComputerAction[];
49
+ counts: Record<string, number>;
50
+ recoveredActionCount?: number;
51
+ captures?: ComputerAction[];
52
+ captureCount?: number;
53
+ startMs: number;
54
+ endMs: number;
55
+ }
3
56
  export declare const TOOL_CAPTURE_LIMIT = 20;
4
57
  export declare const TOOL_ACTION_LIMIT = 50;
5
58
  export type ToolKind = 'browser' | 'computer';
@@ -3,15 +3,16 @@
3
3
  * projected into one row contract, alongside the agent and attention rows.
4
4
  *
5
5
  * WHY A PROJECTION AND NOT A NEW STORE. Both sources already exist and already
6
- * have an owner: `agents browser sessions` groups a profile's captures into
7
- * task-first rows (`browser/sessions-list.ts`), and `agents computer sessions`
8
- * groups `computer.action` ledger entries into run rows
9
- * (`computer/sessions-list.ts`). A menu-bar or Fleet view that wanted the same
10
- * information had only one way to get it: shell out to those two commands, per
11
- * tool, per device, on a timer. That is the per-tool polling this module
12
- * removes — the rows ride the ONE stream `agents feed watch --json` already
13
- * holds open, so a consumer switching its All/Agents/Browser/Computer filter
14
- * spawns zero commands.
6
+ * have an owner: the standalone `browser sessions --tasks --json` groups a
7
+ * profile's captures into task-first rows, and the standalone
8
+ * `computer sessions --json` groups its action ledger into run rows. A menu-bar
9
+ * or Fleet view that wanted the same information had only one way to get it:
10
+ * shell out to those two commands, per tool, per device, on a timer. That is the
11
+ * per-tool polling this module removes — the rows ride the ONE stream
12
+ * `agents feed watch --json` already holds open, so a consumer switching its
13
+ * All/Agents/Browser/Computer filter spawns zero commands. {@link BrowserSessionRow}
14
+ * and {@link ComputerRunRow} are those commands' JSON rows, plus the agent session
15
+ * agents-cli resolved for them from its own index.
15
16
  *
16
17
  * WHAT IS DELIBERATELY DIFFERENT BETWEEN THE TWO KINDS. A browser task is a
17
18
  * LIVE resource: it is bound in the task index while it exists, it can be
@@ -70,12 +71,12 @@ function ownerOf(sessionId, linkedSession, scope) {
70
71
  };
71
72
  }
72
73
  function knownMachine(machine) {
73
- return machine && machine !== 'unknown' ? machine : undefined;
74
+ return machine !== 'local' ? machine : undefined;
74
75
  }
75
76
  export function boundBrowserRow(task, binding) {
76
77
  return {
77
78
  kind: 'task', task, profile: binding.profile ?? '',
78
- linkStatus: 'unlinked', artifacts: [],
79
+ artifacts: [],
79
80
  counts: { screenshot: 0, pdf: 0, recording: 0, download: 0 },
80
81
  latestMtimeMs: 0,
81
82
  };
@@ -125,22 +126,15 @@ export function projectBrowserToolRow(scope, row, binding, live) {
125
126
  export function projectComputerToolRow(scope, row) {
126
127
  const host = normalizeHost(scope);
127
128
  const owner = ownerOf(row.sessionId, row.linkedSession, host);
128
- const agent = row.agent ?? row.linkedSession?.agent;
129
- const captures = [];
130
- const captureCounts = {};
131
- for (const action of row.actions) {
132
- if (!action.capture)
133
- continue;
134
- captureCounts[action.capture.kind] = (captureCounts[action.capture.kind] ?? 0) + 1;
135
- if (captures.length >= TOOL_CAPTURE_LIMIT)
136
- continue;
137
- captures.push({
138
- kind: action.capture.kind, name: action.capture.name, path: action.capture.path,
139
- host,
140
- ...(action.capture.bytes !== undefined ? { bytes: action.capture.bytes } : {}),
141
- atMs: action.tsMs,
142
- });
143
- }
129
+ const agent = row.linkedSession?.agent;
130
+ const captured = (row.captures ?? row.actions).flatMap((action) => action.capture ? [{ ...action.capture, atMs: action.tsMs }] : []);
131
+ const captures = captured.slice(0, TOOL_CAPTURE_LIMIT).map((capture) => ({
132
+ kind: capture.kind, name: capture.name, path: capture.path, host,
133
+ ...(capture.bytes !== undefined ? { bytes: capture.bytes } : {}),
134
+ atMs: capture.atMs,
135
+ }));
136
+ const captureTotal = row.captureCount ?? captured.length;
137
+ const captureCounts = captureTotal > 0 ? { screenshot: captureTotal } : {};
144
138
  const actions = row.actions.slice(0, TOOL_ACTION_LIMIT).map((action) => ({
145
139
  verb: action.verb, atMs: action.tsMs,
146
140
  ...(action.host ? { host: action.host } : {}),
@@ -157,7 +151,7 @@ export function projectComputerToolRow(scope, row) {
157
151
  ...(row.launchId ? { launchId: row.launchId } : {}),
158
152
  ...(agent ? { agent } : {}),
159
153
  ...(owner ? { owner } : {}),
160
- linkStatus: row.linkStatus,
154
+ linkStatus: row.linkedSession ? 'linked' : (row.sessionId || row.launchId) ? 'unresolved' : 'unlinked',
161
155
  startedAtMs: row.startMs,
162
156
  updatedAtMs: row.endMs,
163
157
  captures,
@@ -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];
@@ -0,0 +1,41 @@
1
+ import { type GhExec } from './pr-mergeable.js';
2
+ import { type ProjectPr, type RepoMergeAbility } from './project-prs.js';
3
+ import type { ProjectDef } from '../projects.js';
4
+ export type NeedsMe = 'review' | 'failing' | 'conflicts';
5
+ export interface OpenPr extends ProjectPr {
6
+ reviewRequested: boolean;
7
+ needsMe: NeedsMe | null;
8
+ }
9
+ export interface OpenPrRepo {
10
+ slug: string;
11
+ projects: string[];
12
+ merge: RepoMergeAbility | null;
13
+ pullRequests: OpenPr[];
14
+ ciError: string | null;
15
+ }
16
+ export interface OpenPrOwner {
17
+ login: string;
18
+ open: number;
19
+ truncated: boolean;
20
+ error: string | null;
21
+ }
22
+ export interface OpenPrsEnvelope {
23
+ viewer: string | null;
24
+ owners: OpenPrOwner[];
25
+ reviewRequestedError: string | null;
26
+ repositories: OpenPrRepo[];
27
+ partial: boolean;
28
+ }
29
+ export interface OpenPrsOptions {
30
+ owners?: string[];
31
+ repo?: string;
32
+ number?: number;
33
+ cacheDir?: string;
34
+ nowMs?: number;
35
+ }
36
+ export declare const SEARCH_RESULT_CAP = 1000;
37
+ export declare function listViewerOwners(viewer: string | null, gh?: GhExec): Promise<string[]>;
38
+ export declare function needsMeFor(pr: ProjectPr, viewer: string | null, reviewRequested: boolean): NeedsMe | null;
39
+ export declare function compareOpenPrs(a: OpenPr, b: OpenPr): number;
40
+ export declare const OWNER_LOGIN: RegExp;
41
+ export declare function buildOpenPrs(defs: readonly ProjectDef[], opts?: OpenPrsOptions, gh?: GhExec): Promise<OpenPrsEnvelope>;
@@ -0,0 +1,157 @@
1
+ import { ghExec, canonicalizeRepo, projectRepoSlugs } from './pr-mergeable.js';
2
+ import { CiErrors, KeyedCache, enrichPr, fetchOnePr, fetchViewer, ghFailure, isCachedRollup, mapBounded, readCi, readRepoMergeAbility, rowToProjectPr, } from './project-prs.js';
3
+ import { getCacheDir } from '../state.js';
4
+ const NEEDS_ME_RANK = { review: 0, failing: 1, conflicts: 2 };
5
+ export const SEARCH_RESULT_CAP = 1000;
6
+ const SEARCH_JQ = '.items[] | {number, title, url: .html_url, isDraft: (.draft // false), ' +
7
+ 'state: (.state // "" | ascii_upcase), createdAt: (.created_at // ""), updatedAt: (.updated_at // ""), ' +
8
+ 'login: (.user.login // ""), avatarUrl: (.user.avatar_url // ""), ' +
9
+ 'slug: (.repository_url // "" | sub("^.*/repos/"; ""))}';
10
+ function parseNdjson(out) {
11
+ return out.split('\n').map((l) => l.trim()).filter(Boolean).map((l) => JSON.parse(l));
12
+ }
13
+ async function searchOpenPrs(qualifier, gh) {
14
+ const q = encodeURIComponent(`is:pr is:open archived:false ${qualifier}`);
15
+ const out = await gh([
16
+ 'api', `search/issues?q=${q}&sort=updated&order=desc&per_page=100`, '--paginate', '--cache', '60s', '--jq', SEARCH_JQ,
17
+ ]);
18
+ return parseNdjson(out).map((row) => ({ slug: String(row.slug ?? ''), pr: rowToProjectPr(row) }));
19
+ }
20
+ export async function listViewerOwners(viewer, gh = ghExec) {
21
+ const orgs = (await gh(['api', 'user/orgs', '--paginate', '--cache', '1h', '--jq', '.[].login']))
22
+ .split('\n').map((l) => l.trim()).filter(Boolean);
23
+ return [...new Set([...(viewer ? [viewer] : []), ...orgs.sort((a, b) => a.localeCompare(b))])];
24
+ }
25
+ export function needsMeFor(pr, viewer, reviewRequested) {
26
+ if (reviewRequested)
27
+ return 'review';
28
+ if (!viewer || pr.author.login.toLowerCase() !== viewer.toLowerCase())
29
+ return null;
30
+ if (pr.ciState === 'FAILURE' || pr.ciState === 'ERROR')
31
+ return 'failing';
32
+ if (pr.mergeableState === 'dirty')
33
+ return 'conflicts';
34
+ return null;
35
+ }
36
+ const needsRank = (pr) => (pr.needsMe === null ? 3 : NEEDS_ME_RANK[pr.needsMe]);
37
+ export function compareOpenPrs(a, b) {
38
+ return needsRank(a) - needsRank(b) || b.updatedAt.localeCompare(a.updatedAt);
39
+ }
40
+ function compareRepos(a, b) {
41
+ const best = (r) => Math.min(3, ...r.pullRequests.map(needsRank));
42
+ return best(a) - best(b) || a.slug.localeCompare(b.slug);
43
+ }
44
+ export const OWNER_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
45
+ async function projectsBySlug(defs, gh) {
46
+ const out = new Map();
47
+ await Promise.all(defs.map(async (def) => {
48
+ const slugs = await Promise.all(projectRepoSlugs([def]).map((s) => canonicalizeRepo(s, gh)));
49
+ for (const slug of new Set(slugs.map((s) => s.toLowerCase()))) {
50
+ out.set(slug, [...(out.get(slug) ?? []), def.name]);
51
+ }
52
+ }));
53
+ for (const names of out.values())
54
+ names.sort((a, b) => a.localeCompare(b));
55
+ return out;
56
+ }
57
+ function withNeeds(pr, viewer, reviewRequested) {
58
+ return { ...pr, reviewRequested, needsMe: needsMeFor(pr, viewer, reviewRequested) };
59
+ }
60
+ export async function buildOpenPrs(defs, opts = {}, gh = ghExec) {
61
+ const viewer = await fetchViewer(gh);
62
+ const projectMap = projectsBySlug(defs, gh);
63
+ if (opts.repo !== undefined && opts.number !== undefined) {
64
+ const slug = await canonicalizeRepo(opts.repo, gh);
65
+ const [{ pr, reviewError }, merge, requested] = await Promise.all([
66
+ fetchOnePr(slug, opts.number, gh).then((pr) => enrichPr(slug, pr, gh)),
67
+ readRepoMergeAbility(slug, gh).then((m) => ({ merge: m, error: null }), (err) => ({ merge: null, error: ghFailure(err) })),
68
+ gh(['api', `repos/${slug}/pulls/${opts.number}/requested_reviewers`, '--jq', '.users[].login'])
69
+ .then((out) => ({ logins: out.split('\n').map((l) => l.trim().toLowerCase()).filter(Boolean), error: null }), (err) => ({ logins: [], error: ghFailure(err) })),
70
+ ]);
71
+ const reviewRequested = viewer !== null && requested.logins.includes(viewer.toLowerCase());
72
+ return {
73
+ viewer,
74
+ owners: [],
75
+ reviewRequestedError: requested.error,
76
+ repositories: [{
77
+ slug,
78
+ projects: (await projectMap).get(slug.toLowerCase()) ?? [],
79
+ merge: merge.merge,
80
+ pullRequests: [withNeeds(pr, viewer, reviewRequested)],
81
+ ciError: [reviewError, merge.error].filter(Boolean).join('; ') || null,
82
+ }],
83
+ partial: false,
84
+ };
85
+ }
86
+ const bad = opts.owners?.find((o) => !OWNER_LOGIN.test(o));
87
+ if (bad !== undefined)
88
+ throw new Error(`--org expects a GitHub org or account login, got "${bad}".`);
89
+ const ownerLogins = opts.owners?.length ? [...new Set(opts.owners)] : await listViewerOwners(viewer, gh);
90
+ const ownerSet = new Set(ownerLogins.map((o) => o.toLowerCase()));
91
+ const [ownerReads, requestedRead] = await Promise.all([
92
+ Promise.all(ownerLogins.map(async (login) => {
93
+ try {
94
+ const rows = await searchOpenPrs(`user:${login}`, gh);
95
+ return { owner: { login, open: rows.length, truncated: rows.length >= SEARCH_RESULT_CAP, error: null }, rows };
96
+ }
97
+ catch (err) {
98
+ return { owner: { login, open: 0, truncated: false, error: ghFailure(err) }, rows: [] };
99
+ }
100
+ })),
101
+ searchOpenPrs('review-requested:@me', gh).then((rows) => ({ rows, error: null }), (err) => ({ rows: [], error: ghFailure(err) })),
102
+ ]);
103
+ const key = (slug, n) => `${slug.toLowerCase()}#${n}`;
104
+ const requestedRows = opts.owners?.length
105
+ ? requestedRead.rows.filter((r) => ownerSet.has(r.slug.split('/')[0].toLowerCase()))
106
+ : requestedRead.rows;
107
+ const requested = new Set(requestedRows.map((r) => key(r.slug, r.pr.number)));
108
+ const bySlug = new Map();
109
+ for (const { slug, pr } of [...ownerReads.flatMap((r) => r.rows), ...requestedRows]) {
110
+ if (!slug)
111
+ continue;
112
+ const prs = bySlug.get(slug) ?? new Map();
113
+ prs.set(pr.number, pr);
114
+ bySlug.set(slug, prs);
115
+ }
116
+ const cacheDir = opts.cacheDir ?? getCacheDir();
117
+ const rollups = new KeyedCache(cacheDir, 'project-pr-ci.json', '@', isCachedRollup);
118
+ const nowMs = opts.nowMs ?? Date.now();
119
+ const projects = await projectMap;
120
+ const readers = new Map();
121
+ for (const slug of bySlug.keys())
122
+ readers.set(slug, { slug, gh, rollups, errors: new CiErrors(), nowMs, reads: new Map() });
123
+ const merges = new Map([...bySlug.keys()].map((slug) => [slug, readRepoMergeAbility(slug, gh).catch((err) => {
124
+ readers.get(slug).errors.record(err);
125
+ return null;
126
+ })]));
127
+ const listed = [...bySlug].flatMap(([slug, prs]) => [...prs.values()].map((pr) => ({ slug, pr })));
128
+ const read = await mapBounded(listed, 8, async ({ slug, pr: row }) => {
129
+ const ci = readers.get(slug);
130
+ let pr = row;
131
+ try {
132
+ pr = await fetchOnePr(slug, row.number, gh, '60s');
133
+ }
134
+ catch (err) {
135
+ ci.errors.record(err);
136
+ }
137
+ const ciSummary = await readCi(ci, pr.headSha || null);
138
+ return { slug, pr: withNeeds({ ...pr, ...ciSummary }, viewer, requested.has(key(slug, pr.number))) };
139
+ });
140
+ const repositories = await Promise.all([...bySlug.keys()].map(async (slug) => ({
141
+ slug,
142
+ projects: projects.get(slug.toLowerCase()) ?? [],
143
+ merge: await merges.get(slug),
144
+ pullRequests: read.filter((r) => r.slug === slug).map((r) => r.pr).sort(compareOpenPrs),
145
+ ciError: readers.get(slug).errors.message,
146
+ })));
147
+ repositories.sort(compareRepos);
148
+ rollups.save();
149
+ const owners = ownerReads.map((r) => r.owner);
150
+ return {
151
+ viewer,
152
+ owners,
153
+ reviewRequestedError: requestedRead.error,
154
+ repositories,
155
+ partial: owners.some((o) => o.error !== null) || requestedRead.error !== null,
156
+ };
157
+ }