@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
@@ -1,372 +0,0 @@
1
- /**
2
- * Read-only task/run history over the `computer.action` event ledger
3
- * (`~/.agents/.history/events/YYYY-MM-DD/events.jsonl`, see `../events.ts`) —
4
- * the durable, already-existing audit log every `agents computer <verb>`
5
- * invocation writes through `computer/record.ts`'s `recordComputerAction()`,
6
- * fed by the action events the standalone engine streams back (PHNX-4075).
7
- * Backs both `agents computer sessions` and the
8
- * `agents sessions --computer` alias.
9
- *
10
- * There is no separate capture directory the way browser tasks have
11
- * `.cache/browser/<profile>/sessions/<task>/` — a computer action drives a
12
- * live GUI in place and leaves no artifact of its own, so the event ledger
13
- * IS the canonical execution source for this history (RUSH-2432, the
14
- * computer counterpart of `../browser/sessions-list.ts`'s RUSH-2407
15
- * task-first grouping).
16
- *
17
- * Retention/privacy: `events.ts` bounds and prunes the LEDGER
18
- * (`DEFAULT_RETENTION_DAYS` / `DEFAULT_MAX_STORAGE_BYTES` — 7 days / 50 MiB
19
- * by default, gzip-rotated at 10 MiB) and nothing here changes that policy or
20
- * re-prunes that log. The durable `computer_sessions` table added in RUSH-2549
21
- * is a SECOND store with its OWN, much longer bound
22
- * (`TOOL_SESSION_MAX_AGE_DAYS`, swept by `pruneToolSessions` from the listing
23
- * path below) — that is deliberate, since the table exists precisely to outlive
24
- * the ledger's 7 days, and one row per CLI process would otherwise grow without
25
- * limit. It is metadata only. Nothing sensitive is persisted: `type` /
26
- * `type-text` events already carry only `textLength`, never the typed text
27
- * (see `computer/record.ts` `recordComputerAction`) — the
28
- * mission this module fulfils changes NONE of that. A `run --task`
29
- * description is the agent's OWN instruction, not typed-into-a-target-app
30
- * content (the same class of thing `agents sessions` already stores
31
- * unredacted as a session prompt) — it is kept, but bounded to
32
- * {@link TASK_PREVIEW_MAX_CHARS} via `events.ts`'s `truncate()` before it is
33
- * ever written (see `computer.ts` `registerRunCommand`), never the full
34
- * unbounded text, and it is not the wire-shape `prompt` field so it is a
35
- * deliberate exception to (not a bypass of) the automatic prompt-redaction
36
- * path in `events.ts` `sanitizePayload`.
37
- *
38
- * Grouping key: `recordComputerAction()` stamps one random `invocationId` for
39
- * the lifetime of the emitting CLI process. The event's own `pid` field is the emitting
40
- * CLI PROCESS's pid, never the target app's (that's `targetPid` — see
41
- * `computer/record.ts` `recordComputerAction`, and its `#11` test guarding
42
- * this). One `agents computer <verb>` invocation is one process, and
43
- * `computer run`'s whole embedded observe/act/verify loop is ALSO one
44
- * process. Grouping by `invocationId` gives exactly one row per CLI invocation without
45
- * conflating unrelated processes when the OS later reuses a pid: a
46
- * single explicit verb collapses to a one-action row, and a `run --task`
47
- * loop collapses to one row holding every verb the model drove. That row is
48
- * the "run" a task-first view groups by.
49
- *
50
- * Session identity: unlike a browser task (which only ever learns its
51
- * `launchId`, requiring the join `buildLaunchSessionIndex`/
52
- * `resolveLaunchSession` perform), a `computer.action` event is emitted
53
- * IN-PROCESS by the CLI invocation itself, so `stampProvenance()`
54
- * (`../event-provenance.ts`) already stamps its own `sessionId` directly
55
- * onto the record — no join needed for the common case. This module still
56
- * falls back to the shared launchId join — imported from
57
- * `../browser/sessions-list.ts`, never duplicated — for the case where
58
- * `sessionId` doesn't resolve (a rotated/unindexed session) but `launchId`
59
- * still does via the more authoritative pid registry.
60
- */
61
- import * as fs from 'node:fs';
62
- import * as path from 'node:path';
63
- import { getCacheDir } from '../state.js';
64
- import { machineId } from '../machine-id.js';
65
- import { query, truncate } from '../feed/events.js';
66
- import { formatRelativeTime } from '../session/relative-time.js';
67
- import { getSessionById, listComputerSessionRecords, pruneToolSessions } from '../session/db.js';
68
- import { sessionHeadline } from '../session/title.js';
69
- import { buildLaunchSessionIndex, resolveLaunchSession, } from '../browser/sessions-list.js';
70
- export const TASK_PREVIEW_MAX_CHARS = 200;
71
- const DEFAULT_ACTION_LIMIT = 5000;
72
- function parseActionCapture(value) {
73
- if (!value || typeof value !== 'object')
74
- return undefined;
75
- const record = value;
76
- if (typeof record.path !== 'string' || !record.path)
77
- return undefined;
78
- const name = typeof record.name === 'string' && record.name ? record.name : path.basename(record.path);
79
- return {
80
- path: record.path,
81
- kind: 'screenshot',
82
- name,
83
- ...(typeof record.bytes === 'number' ? { bytes: record.bytes } : {}),
84
- };
85
- }
86
- function recordToAction(r) {
87
- if (typeof r.command !== 'string' || typeof r.pid !== 'number')
88
- return null;
89
- const tsMs = Date.parse(r.ts);
90
- if (Number.isNaN(tsMs))
91
- return null;
92
- return {
93
- verb: r.command,
94
- ts: r.ts,
95
- tsMs,
96
- pid: r.pid,
97
- invocationId: typeof r.invocationId === 'string' ? r.invocationId : undefined,
98
- targetPid: typeof r.targetPid === 'number' ? r.targetPid : undefined,
99
- bundle: typeof r.bundle === 'string' ? r.bundle : undefined,
100
- host: typeof r.host === 'string' ? r.host : undefined,
101
- task: typeof r.task === 'string' ? r.task : undefined,
102
- sessionId: typeof r.sessionId === 'string' ? r.sessionId : undefined,
103
- launchId: typeof r.launchId === 'string' ? r.launchId : undefined,
104
- agent: typeof r.agent === 'string' ? r.agent : undefined,
105
- machineId: typeof r.machineId === 'string' ? r.machineId : undefined,
106
- hostname: typeof r.hostname === 'string' ? r.hostname : undefined,
107
- capture: parseActionCapture(r.capture),
108
- };
109
- }
110
- export function standaloneComputerActionsDir() {
111
- return path.join(getCacheDir(), 'computer', 'actions');
112
- }
113
- function standaloneLineToAction(line, observer) {
114
- let parsed;
115
- try {
116
- parsed = JSON.parse(line);
117
- }
118
- catch {
119
- return null;
120
- }
121
- if (!parsed || typeof parsed !== 'object')
122
- return null;
123
- const record = parsed;
124
- const verb = typeof record.command === 'string' ? record.command : undefined;
125
- const ts = typeof record.ts === 'string' ? record.ts : undefined;
126
- if (!verb || !ts)
127
- return null;
128
- const tsMs = Date.parse(ts);
129
- if (Number.isNaN(tsMs))
130
- return null;
131
- const text = (key) => (typeof record[key] === 'string' ? record[key] : undefined);
132
- const num = (key) => (typeof record[key] === 'number' ? record[key] : undefined);
133
- return {
134
- verb, ts, tsMs,
135
- pid: num('pid') ?? 0,
136
- invocationId: text('invocationId'),
137
- targetPid: num('targetPid'),
138
- bundle: text('bundle'),
139
- host: text('host'),
140
- task: text('task'),
141
- sessionId: text('sessionId'),
142
- launchId: text('launchId'),
143
- agent: text('agent'),
144
- machineId: text('machineId'),
145
- // Attribute to the observer only when the engine omitted its source machine.
146
- hostname: text('hostname') ?? observer,
147
- capture: parseActionCapture(record.capture),
148
- };
149
- }
150
- export function listStandaloneComputerActions(opts = {}) {
151
- const dir = opts.dir ?? standaloneComputerActionsDir();
152
- const limit = opts.limit ?? DEFAULT_ACTION_LIMIT;
153
- const observer = opts.observer ?? machineId();
154
- let days;
155
- try {
156
- days = fs.readdirSync(dir).filter((name) => name.endsWith('.jsonl')).sort().reverse();
157
- }
158
- catch {
159
- return [];
160
- }
161
- const out = [];
162
- for (const day of days) {
163
- if (out.length >= limit)
164
- break;
165
- let lines;
166
- try {
167
- lines = fs.readFileSync(path.join(dir, day), 'utf8').split('\n');
168
- }
169
- catch {
170
- continue;
171
- }
172
- for (let index = lines.length - 1; index >= 0 && out.length < limit; index--) {
173
- const line = lines[index];
174
- if (!line)
175
- continue;
176
- const action = standaloneLineToAction(line, observer);
177
- if (action)
178
- out.push(action);
179
- }
180
- }
181
- out.sort((a, b) => b.tsMs - a.tsMs);
182
- return out;
183
- }
184
- export function mergeComputerActionSources(standalone, legacy) {
185
- const standaloneRuns = new Set();
186
- for (const action of standalone)
187
- if (action.invocationId)
188
- standaloneRuns.add(action.invocationId);
189
- const merged = [...standalone];
190
- for (const action of legacy) {
191
- if (action.invocationId && standaloneRuns.has(action.invocationId))
192
- continue;
193
- merged.push(action);
194
- }
195
- merged.sort((a, b) => b.tsMs - a.tsMs);
196
- return merged;
197
- }
198
- export function listComputerActions(opts = {}) {
199
- const records = query({ eventTypes: ['computer.action'], limit: opts.limit ?? DEFAULT_ACTION_LIMIT });
200
- const out = [];
201
- for (const r of records) {
202
- const a = recordToAction(r);
203
- if (a)
204
- out.push(a);
205
- }
206
- return out;
207
- }
208
- export function groupIntoComputerRuns(actions, resolveSession, resolveLaunch) {
209
- const byInvocation = new Map();
210
- for (const [index, a] of actions.entries()) {
211
- const key = a.invocationId ?? `legacy:${a.pid}:${a.tsMs}:${index}`;
212
- const list = byInvocation.get(key) ?? [];
213
- list.push(a);
214
- byInvocation.set(key, list);
215
- }
216
- const rows = [];
217
- for (const group of byInvocation.values()) {
218
- const pid = group[0].pid;
219
- group.sort((a, b) => b.tsMs - a.tsMs);
220
- const marker = group.find((a) => a.verb === 'run');
221
- const driving = group.filter((a) => a.verb !== 'run');
222
- const counts = {};
223
- for (const a of driving)
224
- counts[a.verb] = (counts[a.verb] ?? 0) + 1;
225
- const bundle = group.find((a) => a.bundle)?.bundle;
226
- const remoteHost = group.find((a) => a.host)?.host;
227
- const identity = group.find((a) => a.sessionId || a.launchId) ?? group[0];
228
- const machine = group.find((a) => a.hostname)?.hostname ?? 'unknown';
229
- const machineId = group.find((a) => a.machineId)?.machineId;
230
- let linkedSession = null;
231
- if (identity.sessionId)
232
- linkedSession = resolveSession?.(identity.sessionId) ?? null;
233
- if (!linkedSession && identity.launchId)
234
- linkedSession = resolveLaunch?.(identity.launchId) ?? null;
235
- const times = group.map((a) => a.tsMs);
236
- rows.push({
237
- pid,
238
- invocationId: group[0].invocationId,
239
- task: marker?.task,
240
- machine,
241
- machineId,
242
- remoteHost,
243
- bundle,
244
- agent: identity.agent,
245
- sessionId: identity.sessionId,
246
- launchId: identity.launchId,
247
- linkStatus: linkedSession ? 'linked' : (identity.sessionId || identity.launchId) ? 'unresolved' : 'unlinked',
248
- linkedSession: linkedSession ?? undefined,
249
- actions: driving,
250
- counts,
251
- startMs: Math.min(...times),
252
- endMs: Math.max(...times),
253
- });
254
- }
255
- rows.sort((a, b) => b.endMs - a.endMs);
256
- return rows;
257
- }
258
- function appendPrunedRunsFromDb(rows, limit) {
259
- const seen = new Set(rows.map((r) => r.invocationId));
260
- const startedBeforeMs = rows.length > 0
261
- ? Math.min(...rows.map((r) => r.startMs))
262
- : undefined;
263
- for (const record of listComputerSessionRecords({ limit, startedBeforeMs })) {
264
- if (seen.has(record.invocationId))
265
- continue;
266
- const linked = record.sessionId ? getSessionById(record.sessionId) : null;
267
- rows.push({
268
- pid: undefined,
269
- invocationId: record.invocationId,
270
- task: record.taskPreview,
271
- machine: record.machine,
272
- machineId: record.machine,
273
- bundle: undefined,
274
- remoteHost: undefined,
275
- agent: undefined,
276
- sessionId: record.sessionId,
277
- launchId: record.launchId,
278
- linkStatus: linked ? 'linked' : (record.sessionId || record.launchId) ? 'unresolved' : 'unlinked',
279
- linkedSession: linked ?? undefined,
280
- actions: [],
281
- counts: {},
282
- recoveredActionCount: record.actionCount,
283
- startMs: record.startedAt,
284
- endMs: record.lastActivity ?? record.startedAt,
285
- });
286
- }
287
- }
288
- export function buildComputerSessionRows(opts = {}) {
289
- const actions = mergeComputerActionSources(listStandaloneComputerActions({ limit: opts.limit, ...(opts.observer ? { observer: opts.observer } : {}) }), listComputerActions({ limit: opts.limit }));
290
- const index = buildLaunchSessionIndex();
291
- const rows = groupIntoComputerRuns(actions, (sessionId) => getSessionById(sessionId), (launchId) => resolveLaunchSession(index, launchId));
292
- try {
293
- pruneToolSessions();
294
- }
295
- catch { }
296
- appendPrunedRunsFromDb(rows, opts.limit);
297
- rows.sort((a, b) => b.endMs - a.endMs);
298
- if (!opts.machine)
299
- return rows;
300
- const q = opts.machine.toLowerCase();
301
- return rows.filter((r) => r.machine.toLowerCase().includes(q) ||
302
- r.remoteHost?.toLowerCase().includes(q) ||
303
- r.machineId?.toLowerCase().includes(q));
304
- }
305
- export function matchesComputerSessionRow(row, queryText) {
306
- const q = queryText.trim().toLowerCase();
307
- if (!q)
308
- return true;
309
- if (row.task?.toLowerCase().includes(q))
310
- return true;
311
- if (row.machine.toLowerCase().includes(q))
312
- return true;
313
- if (row.remoteHost?.toLowerCase().includes(q))
314
- return true;
315
- if (row.bundle?.toLowerCase().includes(q))
316
- return true;
317
- const s = row.linkedSession;
318
- if (s && (s.agent.toLowerCase().includes(q) || s.topic?.toLowerCase().includes(q) || s.label?.toLowerCase().includes(q))) {
319
- return true;
320
- }
321
- return row.actions.some((a) => a.verb.toLowerCase().includes(q));
322
- }
323
- export function formatRowActions(row) {
324
- if (row.recoveredActionCount !== undefined) {
325
- const n = row.recoveredActionCount;
326
- return `${n} action${n === 1 ? '' : 's'} (per-verb detail pruned from the event log)`;
327
- }
328
- return formatActionCounts(row.counts);
329
- }
330
- export function formatActionCounts(counts) {
331
- const parts = Object.entries(counts)
332
- .sort((a, b) => b[1] - a[1])
333
- .map(([verb, n]) => `${verb} ${n}`);
334
- return parts.join(', ') || '(no actions)';
335
- }
336
- export function renderComputerSessionRows(rows) {
337
- if (rows.length === 0)
338
- return 'No computer actions recorded.';
339
- const lines = [];
340
- for (const r of rows) {
341
- const when = formatRelativeTime(new Date(r.endMs).toISOString());
342
- const where = r.remoteHost ? `${r.machine} -> ${r.remoteHost}` : r.machine;
343
- const label = r.task ? truncate(r.task, 60) : (r.bundle ?? `pid ${r.pid}`);
344
- const link = r.linkStatus === 'linked' && r.linkedSession
345
- ? `${r.linkedSession.agent} — ${sessionHeadline(r.linkedSession) || r.linkedSession.shortId}`
346
- : r.linkStatus === 'unresolved'
347
- ? 'unresolved (session not indexed here)'
348
- : 'unlinked';
349
- lines.push(`${when.padEnd(12)} ${where.padEnd(24)} ${String(label ?? '').padEnd(40)} ${link}`);
350
- lines.push(` ${formatRowActions(r)}`);
351
- }
352
- return lines.join('\n');
353
- }
354
- export const DEFAULT_ROW_DISPLAY_LIMIT = 50;
355
- export function applyRowDisplayLimit(rows, limit = DEFAULT_ROW_DISPLAY_LIMIT) {
356
- const shown = rows.slice(0, limit);
357
- return { shown, more: rows.length - shown.length };
358
- }
359
- export function runComputerSessions(opts) {
360
- const rows = buildComputerSessionRows({ machine: opts.machine });
361
- printComputerSessionRows(rows, opts);
362
- }
363
- export function printComputerSessionRows(rows, opts) {
364
- if (opts.json) {
365
- console.log(JSON.stringify(rows, null, 2));
366
- return;
367
- }
368
- const { shown, more } = applyRowDisplayLimit(rows, opts.limit ?? DEFAULT_ROW_DISPLAY_LIMIT);
369
- console.log(renderComputerSessionRows(shown));
370
- if (more > 0)
371
- console.log(`\n… (${more} more; --limit ${rows.length} or --json to see all, --machine to narrow)`);
372
- }