@phnx-labs/agents-cli 1.22.114 → 1.22.116

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 (243) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/README.md +22 -102
  3. package/dist/browser.js +0 -0
  4. package/dist/cli/command-registry.js +0 -7
  5. package/dist/commands/accounts.d.ts +3 -77
  6. package/dist/commands/accounts.js +13 -366
  7. package/dist/commands/audit.js +1 -1
  8. package/dist/commands/auth.js +0 -2
  9. package/dist/commands/browser.d.ts +53 -0
  10. package/dist/commands/browser.js +210 -9
  11. package/dist/commands/doctor.d.ts +2 -3
  12. package/dist/commands/doctor.js +0 -11
  13. package/dist/commands/events.d.ts +1 -3
  14. package/dist/commands/events.js +4 -7
  15. package/dist/commands/exec.d.ts +0 -1
  16. package/dist/commands/exec.js +214 -148
  17. package/dist/commands/feed-watch.js +52 -8
  18. package/dist/commands/feed.js +65 -14
  19. package/dist/commands/focus.js +1 -1
  20. package/dist/commands/go.d.ts +0 -17
  21. package/dist/commands/go.js +2 -19
  22. package/dist/commands/logs.js +1 -1
  23. package/dist/commands/mcp.js +8 -83
  24. package/dist/commands/memory.js +4 -47
  25. package/dist/commands/message.js +4 -4
  26. package/dist/commands/plugins.js +1 -93
  27. package/dist/commands/repo.js +0 -44
  28. package/dist/commands/resume.js +4 -1
  29. package/dist/commands/secrets-passthrough.js +2 -2
  30. package/dist/commands/send.d.ts +4 -4
  31. package/dist/commands/send.js +6 -51
  32. package/dist/commands/sessions-backup-setup.js +1 -1
  33. package/dist/commands/sessions-picker.d.ts +11 -0
  34. package/dist/commands/sessions-picker.js +88 -7
  35. package/dist/commands/sessions-resume.js +0 -1
  36. package/dist/commands/sessions-share.d.ts +5 -7
  37. package/dist/commands/sessions-share.js +98 -49
  38. package/dist/commands/sessions.d.ts +21 -2
  39. package/dist/commands/sessions.js +158 -11
  40. package/dist/commands/setup-browser.js +18 -2
  41. package/dist/commands/setup-computer.js +20 -6
  42. package/dist/commands/setup-secrets.d.ts +2 -2
  43. package/dist/commands/setup-secrets.js +24 -4
  44. package/dist/commands/setup-term.d.ts +24 -0
  45. package/dist/commands/setup-term.js +70 -0
  46. package/dist/commands/setup-terminal.d.ts +3 -0
  47. package/dist/commands/setup-terminal.js +22 -0
  48. package/dist/commands/setup.d.ts +1 -1
  49. package/dist/commands/setup.js +29 -11
  50. package/dist/commands/skills.js +0 -8
  51. package/dist/commands/ssh.d.ts +6 -0
  52. package/dist/commands/ssh.js +93 -302
  53. package/dist/commands/sync.js +14 -5
  54. package/dist/commands/teams.js +1 -1
  55. package/dist/commands/traces.js +1 -1
  56. package/dist/lib/accounting/rotate.d.ts +63 -1
  57. package/dist/lib/accounting/rotate.js +56 -0
  58. package/dist/lib/accounts/add.d.ts +0 -5
  59. package/dist/lib/accounts/add.js +3 -9
  60. package/dist/lib/accounts/slots.js +32 -2
  61. package/dist/lib/answer-router.d.ts +11 -2
  62. package/dist/lib/answer-router.js +26 -2
  63. package/dist/lib/artifacts-client.d.ts +20 -0
  64. package/dist/lib/artifacts-client.js +46 -0
  65. package/dist/lib/auth-mint.d.ts +5 -4
  66. package/dist/lib/auth-mint.js +6 -5
  67. package/dist/lib/browser/drivers/arc.d.ts +1 -1
  68. package/dist/lib/browser/runtime-state.d.ts +55 -0
  69. package/dist/lib/browser/runtime-state.js +99 -18
  70. package/dist/lib/browser/service.d.ts +10 -0
  71. package/dist/lib/browser/service.js +229 -37
  72. package/dist/lib/browser/types.d.ts +18 -0
  73. package/dist/lib/cli-resources.js +3 -1
  74. package/dist/lib/cloud/dispatch.js +1 -1
  75. package/dist/lib/cloudflare/creds.d.ts +10 -0
  76. package/dist/lib/cloudflare/creds.js +46 -0
  77. package/dist/lib/cloudflare/provision.d.ts +35 -0
  78. package/dist/lib/cloudflare/provision.js +144 -0
  79. package/dist/lib/computer/sessions-list.d.ts +55 -0
  80. package/dist/lib/computer/sessions-list.js +168 -1
  81. package/dist/lib/config-keys.d.ts +1 -1
  82. package/dist/lib/config-keys.js +5 -0
  83. package/dist/lib/daemon/daemon.js +8 -1
  84. package/dist/lib/daemon/feed-stream-service.d.ts +23 -0
  85. package/dist/lib/daemon/feed-stream-service.js +40 -0
  86. package/dist/lib/daemon-services.d.ts +1 -1
  87. package/dist/lib/daemon-services.js +5 -0
  88. package/dist/lib/device-config.js +61 -0
  89. package/dist/lib/devices/connect.d.ts +49 -5
  90. package/dist/lib/devices/connect.js +169 -21
  91. package/dist/lib/devices/doctor-findings.js +2 -6
  92. package/dist/lib/feed/answer.d.ts +153 -4
  93. package/dist/lib/feed/answer.js +716 -105
  94. package/dist/lib/feed/envelope.d.ts +79 -0
  95. package/dist/lib/feed/envelope.js +23 -0
  96. package/dist/lib/feed/events.d.ts +6 -0
  97. package/dist/lib/feed/events.js +8 -0
  98. package/dist/lib/feed/feed.d.ts +61 -1
  99. package/dist/lib/feed/feed.js +226 -14
  100. package/dist/lib/feed/hub-server.d.ts +141 -0
  101. package/dist/lib/feed/hub-server.js +586 -0
  102. package/dist/lib/feed/hub.d.ts +95 -0
  103. package/dist/lib/feed/hub.js +255 -0
  104. package/dist/lib/feed/pr-status.d.ts +8 -0
  105. package/dist/lib/feed/pr-status.js +9 -1
  106. package/dist/lib/feed/tool-activity.d.ts +108 -0
  107. package/dist/lib/feed/tool-activity.js +313 -0
  108. package/dist/lib/feed/tools.d.ts +198 -0
  109. package/dist/lib/feed/tools.js +265 -0
  110. package/dist/lib/feed/watch.d.ts +50 -50
  111. package/dist/lib/feed/watch.js +147 -16
  112. package/dist/lib/feed-outcome.d.ts +1 -1
  113. package/dist/lib/feed-outcome.js +9 -2
  114. package/dist/lib/feed-policy.js +9 -3
  115. package/dist/lib/fleet/auth-sync.d.ts +2 -55
  116. package/dist/lib/fleet/auth-sync.js +2 -89
  117. package/dist/lib/format.d.ts +1 -1
  118. package/dist/lib/format.js +1 -1
  119. package/dist/lib/git.d.ts +0 -16
  120. package/dist/lib/git.js +0 -58
  121. package/dist/lib/harness-auth-capabilities.js +7 -2
  122. package/dist/lib/helper-versions.js +1 -1
  123. package/dist/lib/hosts/dispatch.d.ts +20 -1
  124. package/dist/lib/hosts/dispatch.js +52 -30
  125. package/dist/lib/hosts/remote-cmd.d.ts +72 -1
  126. package/dist/lib/hosts/remote-cmd.js +151 -10
  127. package/dist/lib/hosts/remote-cmd.test-fixture.d.ts +2 -0
  128. package/dist/lib/hosts/remote-cmd.test-fixture.js +22 -0
  129. package/dist/lib/mailbox.d.ts +12 -0
  130. package/dist/lib/mailbox.js +16 -2
  131. package/dist/lib/mcp.js +17 -11
  132. package/dist/lib/menubar/snapshot.d.ts +51 -0
  133. package/dist/lib/menubar/snapshot.js +42 -3
  134. package/dist/lib/open-url.js +2 -2
  135. package/dist/lib/probe.d.ts +4 -1
  136. package/dist/lib/probe.js +5 -2
  137. package/dist/lib/projects.d.ts +23 -0
  138. package/dist/lib/projects.js +78 -0
  139. package/dist/lib/pwsh.d.ts +33 -0
  140. package/dist/lib/pwsh.js +56 -0
  141. package/dist/lib/redact.d.ts +8 -0
  142. package/dist/lib/redact.js +11 -0
  143. package/dist/lib/refresh.d.ts +6 -2
  144. package/dist/lib/refresh.js +92 -72
  145. package/dist/lib/secrets-cli.d.ts +11 -0
  146. package/dist/lib/secrets-cli.js +30 -0
  147. package/dist/lib/secrets-client.js +3 -2
  148. package/dist/lib/session/active.d.ts +1 -0
  149. package/dist/lib/session/active.js +8 -0
  150. package/dist/lib/session/db.d.ts +67 -3
  151. package/dist/lib/session/db.js +381 -126
  152. package/dist/lib/session/detached.d.ts +7 -0
  153. package/dist/lib/session/detached.js +29 -0
  154. package/dist/lib/session/prompt.d.ts +23 -7
  155. package/dist/lib/session/prompt.js +46 -8
  156. package/dist/lib/session/remote/peer-stream.d.ts +24 -2
  157. package/dist/lib/session/remote/peer-stream.js +33 -6
  158. package/dist/lib/session/remote/remote-list.d.ts +20 -0
  159. package/dist/lib/session/remote/remote-list.js +22 -6
  160. package/dist/lib/session/remote/watch.d.ts +12 -0
  161. package/dist/lib/session/remote/watch.js +9 -0
  162. package/dist/lib/session/remote-preview-cache.d.ts +29 -0
  163. package/dist/lib/session/remote-preview-cache.js +373 -0
  164. package/dist/lib/session/sync/backend.d.ts +3 -3
  165. package/dist/lib/session/sync/backend.js +3 -3
  166. package/dist/lib/session/sync/provision.d.ts +1 -1
  167. package/dist/lib/session/sync/provision.js +2 -2
  168. package/dist/lib/session/tail.d.ts +50 -0
  169. package/dist/lib/session/tail.js +219 -0
  170. package/dist/lib/sessions-client.js +0 -3
  171. package/dist/lib/setup-tool-install.d.ts +3 -0
  172. package/dist/lib/setup-tool-install.js +27 -0
  173. package/dist/lib/setup-tool-status.d.ts +22 -0
  174. package/dist/lib/setup-tool-status.js +220 -0
  175. package/dist/lib/share-runtime.d.ts +11 -0
  176. package/dist/lib/share-runtime.js +63 -0
  177. package/dist/lib/signin-badge.d.ts +19 -4
  178. package/dist/lib/signin-badge.js +29 -11
  179. package/dist/lib/smart-launch.d.ts +1 -5
  180. package/dist/lib/smart-launch.js +3 -11
  181. package/dist/lib/ssh-exec.d.ts +44 -0
  182. package/dist/lib/ssh-exec.js +119 -0
  183. package/dist/lib/startup/command-registry.d.ts +6 -4
  184. package/dist/lib/startup/command-registry.js +10 -7
  185. package/dist/lib/state.js +2 -2
  186. package/dist/lib/storage/selection.d.ts +2 -2
  187. package/dist/lib/storage/selection.js +2 -2
  188. package/dist/lib/sync-umbrella.d.ts +5 -0
  189. package/dist/lib/sync-umbrella.js +18 -10
  190. package/dist/lib/term-driver.d.ts +24 -0
  191. package/dist/lib/term-driver.js +36 -0
  192. package/dist/lib/terminal/index.d.ts +1 -1
  193. package/dist/lib/terminal/index.js +1 -1
  194. package/dist/lib/terminal/inject.d.ts +38 -0
  195. package/dist/lib/terminal/inject.js +55 -9
  196. package/dist/lib/terminal/transport.d.ts +15 -5
  197. package/dist/lib/terminal/transport.js +61 -11
  198. package/dist/lib/traces/backend.d.ts +1 -2
  199. package/dist/lib/traces/backend.js +1 -2
  200. package/dist/lib/traces/provision.d.ts +1 -1
  201. package/dist/lib/traces/provision.js +2 -2
  202. package/dist/lib/types.d.ts +8 -6
  203. package/package.json +2 -3
  204. package/dist/commands/artifacts-setup.d.ts +0 -53
  205. package/dist/commands/artifacts-setup.js +0 -161
  206. package/dist/commands/artifacts.d.ts +0 -18
  207. package/dist/commands/artifacts.js +0 -58
  208. package/dist/commands/attach.d.ts +0 -12
  209. package/dist/commands/attach.js +0 -86
  210. package/dist/commands/auth-mint.d.ts +0 -12
  211. package/dist/commands/auth-mint.js +0 -108
  212. package/dist/commands/reconnect.d.ts +0 -46
  213. package/dist/commands/reconnect.js +0 -115
  214. package/dist/commands/share.d.ts +0 -293
  215. package/dist/commands/share.js +0 -1424
  216. package/dist/lib/fleet/remote-login.d.ts +0 -170
  217. package/dist/lib/fleet/remote-login.js +0 -568
  218. package/dist/lib/share/analytics.d.ts +0 -13
  219. package/dist/lib/share/analytics.js +0 -45
  220. package/dist/lib/share/backend.d.ts +0 -120
  221. package/dist/lib/share/backend.js +0 -176
  222. package/dist/lib/share/capture.d.ts +0 -31
  223. package/dist/lib/share/capture.js +0 -174
  224. package/dist/lib/share/config.d.ts +0 -72
  225. package/dist/lib/share/config.js +0 -211
  226. package/dist/lib/share/delete.d.ts +0 -123
  227. package/dist/lib/share/delete.js +0 -173
  228. package/dist/lib/share/html.d.ts +0 -20
  229. package/dist/lib/share/html.js +0 -88
  230. package/dist/lib/share/http-error.d.ts +0 -53
  231. package/dist/lib/share/http-error.js +0 -65
  232. package/dist/lib/share/og.d.ts +0 -26
  233. package/dist/lib/share/og.js +0 -84
  234. package/dist/lib/share/provision.d.ts +0 -127
  235. package/dist/lib/share/provision.js +0 -285
  236. package/dist/lib/share/publish.d.ts +0 -379
  237. package/dist/lib/share/publish.js +0 -818
  238. package/dist/lib/share/worker-template.d.ts +0 -27
  239. package/dist/lib/share/worker-template.js +0 -2424
  240. package/dist/lib/storage/index.d.ts +0 -14
  241. package/dist/lib/storage/index.js +0 -14
  242. package/dist/lib/storage/visibility.d.ts +0 -82
  243. package/dist/lib/storage/visibility.js +0 -99
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Event-driven tool-activity collector — the thing that makes the rows in
3
+ * `tools.ts` reach the feed stream without a poll.
4
+ *
5
+ * THE COST THIS EXISTS TO AVOID. A status surface that wants "which browser
6
+ * tasks and computer runs are there right now" has, until this module, one way
7
+ * to ask: run `agents browser sessions --json` and `agents computer sessions
8
+ * --json`, per device, on a timer. Two subprocesses per tool per device per
9
+ * tick, each paying a full CLI boot, to answer "nothing changed" almost every
10
+ * time. A menu bar at a one-minute cadence over a ten-device fleet is 1,200
11
+ * process spawns an hour for, typically, zero new rows.
12
+ *
13
+ * WHAT REPLACES IT. The two sources are files on the machine that owns them:
14
+ * the browser runtime tree (task index + capture dirs) and the event ledger
15
+ * that `computer.action` appends to. This collector watches those roots, and
16
+ * re-projects ONLY when one of them reports a change. A warm idle does no work
17
+ * at all: no directory read, no subprocess, no emission. When something does
18
+ * change it re-projects and emits the DIFF — the changed rows and the vanished
19
+ * row keys — never a full snapshot, so a single new screenshot costs one
20
+ * `tool.upsert`.
21
+ *
22
+ * WHEN THE WATCHERS CANNOT ARM (an unsupported filesystem, a root that does not
23
+ * exist yet) the collector says so on `armed` and re-projects on the bounded
24
+ * sweep cadence instead. That is a stated degradation, not a silent one: a
25
+ * caller can surface it, and the diff shape is identical either way.
26
+ */
27
+ import * as fs from 'node:fs';
28
+ import * as path from 'node:path';
29
+ import { getBrowserRuntimeDir } from '../state.js';
30
+ import { getEventsDir } from './events.js';
31
+ import { listTaskBindings } from '../browser/task-index.js';
32
+ import { buildBrowserSessionRows } from '../browser/sessions-list.js';
33
+ import { buildComputerSessionRows, standaloneComputerActionsDir } from '../computer/sessions-list.js';
34
+ import { boundBrowserRow, projectBrowserToolRow, projectComputerToolRow, sortToolRows } from './tools.js';
35
+ /** Re-projection cadence used only while no directory watcher could arm. */
36
+ export const TOOL_SWEEP_MS = 5_000;
37
+ /** Computer ledger rows read per projection. Bounds the newest-first window. */
38
+ const TOOL_COMPUTER_LIMIT = 500;
39
+ /**
40
+ * Project every browser task and computer run this machine knows about into
41
+ * canonical tool rows, newest first. Impure by design — the three readers are
42
+ * injectable so a test drives real temp stores rather than a mocked service.
43
+ */
44
+ export function collectToolRows(scope, sources = {}) {
45
+ let complete = true;
46
+ const read = (source, empty) => {
47
+ try {
48
+ return source();
49
+ }
50
+ catch {
51
+ complete = false;
52
+ return empty;
53
+ }
54
+ };
55
+ const bindings = new Map();
56
+ for (const binding of read(sources.bindings ?? listTaskBindings, []))
57
+ bindings.set(binding.name, binding);
58
+ const liveTasks = new Map();
59
+ for (const task of read(sources.liveTasks ?? (() => readLiveBrowserTasks()), []))
60
+ liveTasks.set(task.task, task);
61
+ const rows = [];
62
+ const browserRows = read(sources.browserRows ?? (() => buildBrowserSessionRows()), []);
63
+ const captured = new Set();
64
+ for (const row of browserRows) {
65
+ if (row.task)
66
+ captured.add(row.task);
67
+ rows.push(projectBrowserToolRow(scope, row, row.task ? bindings.get(row.task) : undefined, row.task ? liveTasks.get(row.task) : undefined));
68
+ }
69
+ // Neither the capture tree nor the task index alone answers "which tasks exist".
70
+ // `tasks.json` is the live authority (and the only source of tabs); the task
71
+ // index additionally routes a task whose browser runs on ANOTHER device, which
72
+ // has no local live record. A task bound a second ago is live and closable with
73
+ // no capture to its name, and deriving rows from captures alone hid exactly that.
74
+ for (const task of new Set([...liveTasks.keys(), ...bindings.keys()])) {
75
+ if (captured.has(task))
76
+ continue;
77
+ const binding = bindings.get(task);
78
+ const live = liveTasks.get(task);
79
+ rows.push(projectBrowserToolRow(scope, boundBrowserRow(task, live ?? binding ?? {}), binding, live));
80
+ }
81
+ const computerRows = read(sources.computerRows ?? (() => buildComputerSessionRows({ limit: TOOL_COMPUTER_LIMIT, observer: scope })), []);
82
+ for (const row of computerRows)
83
+ rows.push(projectComputerToolRow(scope, row));
84
+ return { rows: sortToolRows(rows), complete };
85
+ }
86
+ /**
87
+ * Holds the last projected row set and answers "what changed?".
88
+ *
89
+ * Row identity is the projection's own `rowKey`, so a browser task that gains a
90
+ * capture upserts under the same key, and a closed task — gone from both the
91
+ * index and the capture tree — comes back as a remove.
92
+ */
93
+ export class ToolRowSet {
94
+ rows = new Map();
95
+ /** The diff from the current set to `next`, and adopt `next` as current. */
96
+ diff(next) {
97
+ const upserts = [];
98
+ const seen = new Set();
99
+ for (const row of next) {
100
+ seen.add(row.rowKey);
101
+ const serialized = JSON.stringify(row);
102
+ if (this.rows.get(row.rowKey) === serialized)
103
+ continue;
104
+ this.rows.set(row.rowKey, serialized);
105
+ upserts.push(row);
106
+ }
107
+ const removes = [];
108
+ for (const key of [...this.rows.keys()]) {
109
+ if (seen.has(key))
110
+ continue;
111
+ this.rows.delete(key);
112
+ removes.push(key);
113
+ }
114
+ return { upserts, removes };
115
+ }
116
+ /** Adopt `rows` as the current set without emitting a diff (a reset). */
117
+ reset(rows) {
118
+ this.rows.clear();
119
+ for (const row of rows)
120
+ this.rows.set(row.rowKey, JSON.stringify(row));
121
+ }
122
+ }
123
+ /**
124
+ * The directory roots whose contents back the tool rows.
125
+ *
126
+ * The standalone computer ledger is its OWN root: the engine writes there
127
+ * directly, without going through agents-cli, so nothing under the event-ledger
128
+ * or browser roots changes when an operator runs `computer` by hand. Omitting it
129
+ * meant those actions were only ever noticed on a sweep triggered by unrelated
130
+ * activity.
131
+ */
132
+ export function toolWatchRoots() {
133
+ return [getBrowserRuntimeDir(), getEventsDir(), standaloneComputerActionsDir()];
134
+ }
135
+ /**
136
+ * One profile's live task records, with the tabs each task addresses.
137
+ *
138
+ * THROWS on a read it cannot trust. An absent `tasks.json` is the ordinary "no
139
+ * live browser on this profile" case and returns nothing — but EACCES, EMFILE, a
140
+ * truncated file or malformed JSON are failures, and swallowing them returned an
141
+ * empty list that is indistinguishable from "every task closed". The caller then
142
+ * published a remove for every live row. Failing loud here is what lets
143
+ * `collectToolRows` mark the projection incomplete and PRESERVE the rows it has.
144
+ */
145
+ function readLiveTasksFor(profileDir) {
146
+ const file = path.join(profileDir, 'tasks.json');
147
+ let raw;
148
+ try {
149
+ raw = fs.readFileSync(file, 'utf8');
150
+ }
151
+ catch (error) {
152
+ // Only "it isn't there" is benign. Anything else is a read we cannot trust.
153
+ if (error.code === 'ENOENT')
154
+ return [];
155
+ throw error;
156
+ }
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(raw);
160
+ }
161
+ catch (error) {
162
+ // A JSON error is NOT benign: the browser rewrites this file in place, so a
163
+ // parse failure usually means we caught a write in progress — and the tasks
164
+ // are still very much alive.
165
+ throw new Error(`unreadable live task state at ${file}: ${error.message}`);
166
+ }
167
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
168
+ throw new Error(`unexpected live task state at ${file}: expected an object of tasks`);
169
+ }
170
+ const out = [];
171
+ for (const [name, value] of Object.entries(parsed)) {
172
+ if (!value || typeof value !== 'object')
173
+ continue;
174
+ const record = value;
175
+ // `tabs` maps the task's SHORT id -> the engine's target id. The short id is
176
+ // what `browser tab focus` takes and what stays stable across a reconnect,
177
+ // so it is the id published; the target id is never surfaced.
178
+ const borrowed = new Set(Array.isArray(record.borrowedTabs) ? record.borrowedTabs.filter((id) => typeof id === 'string') : []);
179
+ const tabs = [];
180
+ if (record.tabs && typeof record.tabs === 'object') {
181
+ for (const id of Object.keys(record.tabs)) {
182
+ tabs.push({ id, ...(record.currentTabId === id ? { current: true } : {}), ...(borrowed.has(id) ? { borrowed: true } : {}) });
183
+ }
184
+ }
185
+ out.push({
186
+ task: typeof record.name === 'string' ? record.name : name,
187
+ ...(typeof record.profile === 'string' ? { profile: record.profile } : {}),
188
+ ...(typeof record.label === 'string' ? { label: record.label } : {}),
189
+ tabs,
190
+ // The real persisted schema is `createdAt` + `lastActionAt` (`browser/types.ts`
191
+ // `Task`). An earlier revision read `startedAt`, which the DTO at
192
+ // `service.ts` uses but `tasks.json` never carries — so every zero-capture
193
+ // task reported no start time at all and sorted to the bottom.
194
+ ...(typeof record.createdAt === 'number' ? { startedAtMs: record.createdAt } : {}),
195
+ // `lastActionAt` is refreshed by every task-scoped action, which makes it
196
+ // the honest freshness key for a task that has produced no capture yet.
197
+ // Tasks written before RUSH-2622 carry none; `createdAt` is the fallback the
198
+ // browser's own reader normalizes them to.
199
+ ...(typeof record.lastActionAt === 'number' ? { lastActionAtMs: record.lastActionAt }
200
+ : typeof record.createdAt === 'number' ? { lastActionAtMs: record.createdAt } : {}),
201
+ ...(typeof record.sessionId === 'string' ? { sessionId: record.sessionId } : {}),
202
+ ...(typeof record.launchId === 'string' ? { launchId: record.launchId } : {}),
203
+ ...(typeof record.actor === 'string' ? { actor: record.actor } : {}),
204
+ });
205
+ }
206
+ return out;
207
+ }
208
+ /**
209
+ * Every live browser task on this machine, across every profile runtime dir.
210
+ *
211
+ * THROWS for the same reason {@link readLiveTasksFor} does. A runtime dir that
212
+ * does not exist means no browser has ever run here — genuinely no tasks. A
213
+ * readdir that fails for any other reason (EACCES, EMFILE) is a failure, and
214
+ * returning `[]` for it would tell the differ every task had closed.
215
+ */
216
+ export function readLiveBrowserTasks(root = getBrowserRuntimeDir()) {
217
+ let entries;
218
+ try {
219
+ entries = fs.readdirSync(root, { withFileTypes: true });
220
+ }
221
+ catch (error) {
222
+ if (error.code === 'ENOENT')
223
+ return [];
224
+ throw error;
225
+ }
226
+ const out = [];
227
+ for (const entry of entries) {
228
+ if (!entry.isDirectory() || entry.name === 'sessions')
229
+ continue;
230
+ out.push(...readLiveTasksFor(path.join(root, entry.name)));
231
+ }
232
+ return out;
233
+ }
234
+ /**
235
+ * Watch the tool roots and report diffs until `signal` aborts.
236
+ *
237
+ * `armed()` reports whether every root currently has a live watcher. It is a
238
+ * FUNCTION, not a flag captured at setup: a watcher can die later (its directory
239
+ * is removed and recreated, an inotify limit is hit), and a frozen `armed: true`
240
+ * meant the tick kept short-circuiting on `!dirty` from a watcher that would
241
+ * never report again — changes were then missed permanently, with the handle
242
+ * still claiming to be armed. Each tick re-arms whatever is missing and sweeps
243
+ * until everything is watched again.
244
+ */
245
+ export function watchToolActivity(options) {
246
+ const roots = options.roots ?? toolWatchRoots();
247
+ const set = new ToolRowSet();
248
+ if (options.initial)
249
+ set.reset(options.initial);
250
+ let dirty = false;
251
+ let stopped = false;
252
+ /** One entry per root; `undefined` means that root needs re-arming. */
253
+ const watchers = new Map(roots.map((root) => [root, undefined]));
254
+ const armRoot = (root) => {
255
+ if (stopped || watchers.get(root))
256
+ return;
257
+ try {
258
+ // A root that does not exist yet (no browser has ever run here) cannot be
259
+ // watched, and would never be retried. Creating it arms the watcher now.
260
+ fs.mkdirSync(root, { recursive: true });
261
+ // Recursive: a capture lands in <root>/<profile>/sessions/<task>/, several
262
+ // levels below the root, and a non-recursive watch never sees it.
263
+ const watcher = fs.watch(root, { recursive: true }, () => { dirty = true; });
264
+ watcher.on('error', () => {
265
+ watcher.close();
266
+ // Release the slot AND mark dirty: the events this watcher dropped
267
+ // between failing and being replaced have to be picked up by a sweep,
268
+ // or a change that landed inside that gap is lost for good.
269
+ if (watchers.get(root) === watcher)
270
+ watchers.set(root, undefined);
271
+ dirty = true;
272
+ });
273
+ watchers.set(root, watcher);
274
+ }
275
+ catch { /* reported by armed(); the sweep covers it until it arms */ }
276
+ };
277
+ for (const root of roots)
278
+ armRoot(root);
279
+ const armed = () => [...watchers.values()].every((watcher) => watcher !== undefined);
280
+ const reproject = () => {
281
+ const snapshot = collectToolRows(options.scope, options.sources);
282
+ // An incomplete read is not evidence a task closed. Keep the rows we have and
283
+ // stay dirty so the next tick retries — publishing removes here is what made
284
+ // live rows flicker out on a transient failure.
285
+ if (!snapshot.complete) {
286
+ dirty = true;
287
+ return;
288
+ }
289
+ const diff = set.diff(snapshot.rows);
290
+ if (diff.upserts.length > 0 || diff.removes.length > 0)
291
+ options.onDiff(diff);
292
+ };
293
+ const timer = setInterval(() => {
294
+ for (const root of roots)
295
+ armRoot(root);
296
+ // Fully-armed watchers mean a tick with nothing reported does NOTHING — no
297
+ // directory read, no projection. That is the warm-idle guarantee, and it is
298
+ // conditional on every root actually being watched right now.
299
+ if (armed() && !dirty)
300
+ return;
301
+ dirty = false;
302
+ reproject();
303
+ }, options.sweepMs ?? TOOL_SWEEP_MS);
304
+ const stop = () => {
305
+ stopped = true;
306
+ clearInterval(timer);
307
+ for (const watcher of watchers.values())
308
+ watcher?.close();
309
+ watchers.clear();
310
+ };
311
+ options.signal.addEventListener('abort', stop, { once: true });
312
+ return { armed, stop };
313
+ }
@@ -0,0 +1,198 @@
1
+ import type { BrowserSessionRow, ArtifactKind } from '../browser/sessions-list.js';
2
+ import type { ComputerRunRow } from '../computer/sessions-list.js';
3
+ /** Newest captures retained per row. A task with hundreds of screenshots must
4
+ * not turn one stream envelope into a megabyte. */
5
+ export declare const TOOL_CAPTURE_LIMIT = 20;
6
+ /** Newest actions retained per computer row, for the same reason. */
7
+ export declare const TOOL_ACTION_LIMIT = 50;
8
+ export type ToolKind = 'browser' | 'computer';
9
+ /** Why a row carries no owning session: `linked` resolved one, `unresolved` has
10
+ * an id that no indexed session matches, `unlinked` never had one. Mirrors the
11
+ * status both source modules already publish. */
12
+ export type ToolLinkStatus = 'linked' | 'unresolved' | 'unlinked';
13
+ /** One artifact a tool produced. Path only — never contents. */
14
+ export interface ToolCapture {
15
+ kind: ArtifactKind;
16
+ name: string;
17
+ /**
18
+ * Absolute path ON {@link ToolCapture.host}. A capture lives on the machine
19
+ * whose browser produced it, so a fleet reader on another box must not treat
20
+ * this as a local path — it has to open it through that host. Carrying the host
21
+ * per capture is what makes the path meaningful off-box at all.
22
+ */
23
+ path: string;
24
+ /** The device that holds this file. */
25
+ host: string;
26
+ bytes?: number;
27
+ atMs: number;
28
+ }
29
+ /**
30
+ * One tab a browser task has open, with the id the task itself addresses it by.
31
+ *
32
+ * `id` is the task's SHORT tab id (the key of `Task.tabs`), not the underlying
33
+ * CDP target id: the short id is what `agents browser tab focus <id>` accepts
34
+ * and what stays stable for the life of the tab, while the target id is an
35
+ * engine-internal handle that a reconnect can change.
36
+ */
37
+ export interface ToolTab {
38
+ id: string;
39
+ url?: string;
40
+ title?: string;
41
+ /** The tab URL-less verbs act on. */
42
+ current?: boolean;
43
+ /**
44
+ * The task drives this tab but did not open it, so no close path touches it.
45
+ * Surfaced so a UI does not offer to close someone else's tab.
46
+ */
47
+ borrowed?: boolean;
48
+ }
49
+ /**
50
+ * An argv a consumer may run verbatim, plus the device it must run ON.
51
+ *
52
+ * `runOn` is load-bearing and is NOT a `--device` flag. A browser task is bound
53
+ * to its device at `start`, and every later verb resolves that binding from the
54
+ * local task index — `agents browser done --task x --device y` is explicitly
55
+ * REJECTED (`browser/task-index.ts` `REJECT_DEVICE_MESSAGE`). So the way to act
56
+ * on a task observed from another box is to run the plain argv on the host that
57
+ * holds the binding, which is what this names.
58
+ */
59
+ export interface ToolCommand {
60
+ command: 'agents';
61
+ args: string[];
62
+ runOn: string;
63
+ }
64
+ /** The agent session that drove the tool, as a click-through target. */
65
+ export interface ToolOwner {
66
+ sessionId: string;
67
+ device: string;
68
+ label?: string;
69
+ agent?: string;
70
+ }
71
+ interface ToolRowBase {
72
+ kind: ToolKind;
73
+ /** Opaque, stable identity for this row within one device scope. */
74
+ rowKey: string;
75
+ /** The observing device that reported the row. */
76
+ scope: string;
77
+ /** The DRIVEN machine — for `--device` runs this differs from `scope`. */
78
+ device: string;
79
+ /** Is this a resource that still exists and can be acted on? */
80
+ live: boolean;
81
+ task?: string;
82
+ sessionId?: string;
83
+ launchId?: string;
84
+ agent?: string;
85
+ owner?: ToolOwner;
86
+ linkStatus: ToolLinkStatus;
87
+ startedAtMs: number;
88
+ updatedAtMs: number;
89
+ /** Newest first, bounded by {@link TOOL_CAPTURE_LIMIT}. */
90
+ captures: ToolCapture[];
91
+ captureCounts: Record<string, number>;
92
+ }
93
+ export interface BrowserToolRow extends ToolRowBase {
94
+ kind: 'browser';
95
+ profile: string;
96
+ /** Redacted by {@link redactToolUrl}; absent when the binding recorded none. */
97
+ url?: string;
98
+ /**
99
+ * Tabs the task has open, newest-known first. Absent — not empty — when this
100
+ * host holds no live task record to read them from (a task bound to another
101
+ * device, or one whose run already ended leaving only captures). Absent means
102
+ * "unknown here", `[]` means "genuinely none".
103
+ */
104
+ tabs?: ToolTab[];
105
+ /**
106
+ * Focus one of this task's tabs. Present only while `live` and only for a tab
107
+ * the task actually owns.
108
+ */
109
+ showCommand?: ToolCommand;
110
+ /**
111
+ * The command that closes this task. Present ONLY while `live` — a task the
112
+ * index no longer binds has nothing left to close, and offering the command
113
+ * anyway would fail loud at the operator instead of at this boundary.
114
+ */
115
+ closeCommand?: ToolCommand;
116
+ }
117
+ export interface ComputerToolRow extends ToolRowBase {
118
+ kind: 'computer';
119
+ /** Always false: see the module docblock. A run is history, not a session. */
120
+ live: false;
121
+ bundle?: string;
122
+ /** Newest first, bounded by {@link TOOL_ACTION_LIMIT}. */
123
+ actions: {
124
+ verb: string;
125
+ atMs: number;
126
+ host?: string;
127
+ bundle?: string;
128
+ }[];
129
+ actionCounts: Record<string, number>;
130
+ /** Total actions for a row whose per-verb detail the ledger already pruned. */
131
+ recoveredActionCount?: number;
132
+ }
133
+ export type ToolRow = BrowserToolRow | ComputerToolRow;
134
+ /**
135
+ * A task the local browser holds LIVE state for, read from its `tasks.json`.
136
+ *
137
+ * This is the only authority on a task's tabs: `tasks.json` is rewritten from
138
+ * the live task map, so an entry here means the task exists right now, and its
139
+ * `tabs` map is what `agents browser tab focus` addresses. A task whose run has
140
+ * ended is absent even though its captures remain, which is exactly the
141
+ * distinction `live` on a row reports.
142
+ */
143
+ export interface LiveBrowserTask {
144
+ task: string;
145
+ profile?: string;
146
+ label?: string;
147
+ tabs?: ToolTab[];
148
+ /** `Task.createdAt` — when the task was opened. */
149
+ startedAtMs?: number;
150
+ /** `Task.lastActionAt` — refreshed by every task-scoped action. */
151
+ lastActionAtMs?: number;
152
+ sessionId?: string;
153
+ launchId?: string;
154
+ /** `Task.actor` — who launched it, when the record carries one. */
155
+ actor?: string;
156
+ }
157
+ /** Stable identity for one tool row within one device scope. */
158
+ export declare function toolRowKey(scope: string, kind: ToolKind, identity: string): string;
159
+ /**
160
+ * A task URL safe to publish: userinfo removed and credential-shaped query
161
+ * parameters replaced. A string that does not parse as a URL is dropped
162
+ * entirely rather than published unexamined — it cannot be redacted safely.
163
+ */
164
+ export declare function redactToolUrl(raw: string | undefined): string | undefined;
165
+ /**
166
+ * A browser task the task index binds but that has produced no capture yet.
167
+ *
168
+ * `buildBrowserSessionRows` derives its rows from captures on disk, so a task
169
+ * that was just opened — bound, live, drivable, closable — had no row at all
170
+ * until its first screenshot landed. That is the window an operator most wants
171
+ * to see, and it is exactly when a Sessions pane showed nothing. This
172
+ * synthesizes the zero-capture row so it goes through the SAME projection rather
173
+ * than a second parallel one.
174
+ */
175
+ export declare function boundBrowserRow(task: string, binding: {
176
+ profile?: string;
177
+ }): BrowserSessionRow;
178
+ /**
179
+ * One browser task (or a profile's downloads bucket) as a tool row. Pure: the
180
+ * liveness verdict is passed in, because only the machine running the browser
181
+ * daemon holds the task index that answers it.
182
+ */
183
+ export declare function projectBrowserToolRow(scope: string, row: BrowserSessionRow, binding?: {
184
+ device?: string;
185
+ profile?: string;
186
+ url?: string;
187
+ createdAt?: number;
188
+ sessionId?: string;
189
+ launchId?: string;
190
+ }, live?: LiveBrowserTask): BrowserToolRow;
191
+ /**
192
+ * One computer run as a tool row. `live` is pinned false and no close/stop
193
+ * command is produced: the emitting CLI process is already gone.
194
+ */
195
+ export declare function projectComputerToolRow(scope: string, row: ComputerRunRow): ComputerToolRow;
196
+ /** Newest first across both kinds — the order a consumer renders. */
197
+ export declare function sortToolRows(rows: ToolRow[]): ToolRow[];
198
+ export {};