@cortex-agent/server 2026.10.15-2 → 2026.10.21

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 (171) hide show
  1. package/README.md +70 -31
  2. package/defaults/board/board.css +140 -62
  3. package/defaults/board/scaffold.html +36 -13
  4. package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
  5. package/defaults/plugins/cortex-system/plugin.json +2 -2
  6. package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
  7. package/dist/agent-adapter/claude/adapter.d.ts +2 -5
  8. package/dist/agent-adapter/claude/adapter.js +6 -5
  9. package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
  10. package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
  11. package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
  12. package/dist/agent-adapter/claude/cache-refresh.js +145 -0
  13. package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
  14. package/dist/agent-adapter/claude/cache-touch.js +75 -0
  15. package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
  16. package/dist/agent-adapter/claude/event-parser.js +33 -17
  17. package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
  18. package/dist/agent-adapter/claude/event-translator.js +2 -0
  19. package/dist/agent-adapter/claude/session-options.d.ts +0 -4
  20. package/dist/agent-adapter/claude/session-options.js +0 -9
  21. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  22. package/dist/agent-adapter/claude/spawn-args.js +2 -5
  23. package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
  24. package/dist/agent-adapter/claude/transcript-clear.js +217 -0
  25. package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
  26. package/dist/agent-adapter/claude/turn-machine.js +21 -68
  27. package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
  28. package/dist/agent-adapter/claude/window-warmup.js +38 -0
  29. package/dist/agent-adapter/continuation-phase.js +3 -0
  30. package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
  31. package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
  32. package/dist/agent-adapter/pi/event-parser.js +43 -27
  33. package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
  34. package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
  35. package/dist/agent-adapter/pi/pi-session.js +15 -0
  36. package/dist/agent-adapter/pi/session-options.d.ts +2 -6
  37. package/dist/agent-adapter/pi/session-options.js +2 -11
  38. package/dist/agent-adapter/run-events.d.ts +10 -0
  39. package/dist/agent-adapter/run-events.js +2 -0
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/client-bundle/manifest.json +1 -1
  42. package/dist/core/locales/en.d.ts +1 -0
  43. package/dist/core/locales/slices/commands.d.ts +1 -0
  44. package/dist/core/locales/slices/commands.js +2 -0
  45. package/dist/core/settings-spec.d.ts +25 -0
  46. package/dist/core/settings-spec.js +34 -0
  47. package/dist/domain/agents/engine-selection.js +1 -1
  48. package/dist/domain/agents/subagent/registry.d.ts +2 -0
  49. package/dist/domain/agents/subagent/registry.js +8 -0
  50. package/dist/domain/agents/subagent/runner.js +0 -1
  51. package/dist/domain/browser/broker.d.ts +99 -0
  52. package/dist/domain/browser/broker.js +487 -0
  53. package/dist/domain/costs/claude-account.js +21 -0
  54. package/dist/domain/costs/rate-limit-throttle.js +3 -1
  55. package/dist/domain/costs/reset-account.d.ts +2 -0
  56. package/dist/domain/costs/usage-service.d.ts +1 -1
  57. package/dist/domain/costs/usage-service.js +20 -7
  58. package/dist/domain/mcp/tools/ui-file.js +1 -1
  59. package/dist/domain/remote/device-browser.js +1 -1
  60. package/dist/domain/remote/device-chrome-commands.js +2 -0
  61. package/dist/domain/remote/device-port.js +2 -2
  62. package/dist/domain/runs/builders.d.ts +2 -2
  63. package/dist/domain/runs/builders.js +2 -3
  64. package/dist/domain/runs/engine-spec.d.ts +5 -0
  65. package/dist/domain/runs/engine-spec.js +1 -2
  66. package/dist/domain/runs/request.d.ts +0 -1
  67. package/dist/domain/sessions/session-lifecycle.d.ts +0 -4
  68. package/dist/domain/sessions/session-lifecycle.js +1 -1
  69. package/dist/domain/system/own-bin-path.d.ts +13 -0
  70. package/dist/domain/system/own-bin-path.js +36 -0
  71. package/dist/domain/system/terminal-cli/index.d.ts +58 -0
  72. package/dist/domain/system/terminal-cli/index.js +100 -0
  73. package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
  74. package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
  75. package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
  76. package/dist/domain/system/terminal-cli/registrar.js +1 -0
  77. package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
  78. package/dist/domain/system/terminal-cli/shims.js +108 -0
  79. package/dist/domain/system/terminal-cli/state.d.ts +7 -0
  80. package/dist/domain/system/terminal-cli/state.js +36 -0
  81. package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
  82. package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
  83. package/dist/domain/tui-session/tui-session-service.js +1 -1
  84. package/dist/domain/tui-session/types.d.ts +1 -1
  85. package/dist/domain/ui-service/app-router.d.ts +17 -6
  86. package/dist/domain/ui-service/app-router.js +3 -1
  87. package/dist/domain/ui-service/assistant-snapshots.js +2 -0
  88. package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
  89. package/dist/domain/ui-service/inline-media-types.js +1 -0
  90. package/dist/domain/ui-service/input-schemas.d.ts +17 -17
  91. package/dist/domain/ui-service/input-schemas.js +9 -9
  92. package/dist/domain/ui-service/mutate/models.d.ts +3 -0
  93. package/dist/domain/ui-service/mutate/models.js +21 -2
  94. package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
  95. package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
  96. package/dist/domain/ui-service/mutate/sessions.js +1 -4
  97. package/dist/domain/ui-service/query/sessions.js +1 -1
  98. package/dist/domain/ui-service/types.d.ts +8 -10
  99. package/dist/domain/ui-service/ui-service.d.ts +9 -6
  100. package/dist/domain/ui-service/ui-service.js +4 -1
  101. package/dist/entry/app.js +23 -0
  102. package/dist/entry/browser-cli.d.ts +39 -0
  103. package/dist/entry/browser-cli.js +317 -0
  104. package/dist/entry/cli-help.d.ts +1 -0
  105. package/dist/entry/cli-help.js +30 -0
  106. package/dist/entry/cli.js +2 -0
  107. package/dist/entry/daemon.js +2 -0
  108. package/dist/entry/path-cli.d.ts +4 -0
  109. package/dist/entry/path-cli.js +65 -0
  110. package/dist/entry/shutdown.js +7 -0
  111. package/dist/entry/start-ui-http.js +8 -0
  112. package/dist/entry/ui-service-wiring.js +2 -0
  113. package/dist/events/event-types.d.ts +2 -1
  114. package/dist/orchestration/agent-runner.d.ts +2 -2
  115. package/dist/orchestration/agent-runner.js +6 -6
  116. package/dist/orchestration/browser-webhook.d.ts +11 -0
  117. package/dist/orchestration/browser-webhook.js +28 -0
  118. package/dist/orchestration/cache-keep-warm.d.ts +77 -0
  119. package/dist/orchestration/cache-keep-warm.js +213 -0
  120. package/dist/orchestration/claude-window-warmup.d.ts +40 -0
  121. package/dist/orchestration/claude-window-warmup.js +126 -0
  122. package/dist/orchestration/conversation-request.d.ts +4 -7
  123. package/dist/orchestration/conversation-request.js +1 -2
  124. package/dist/orchestration/delta-coalescer.d.ts +4 -2
  125. package/dist/orchestration/delta-coalescer.js +5 -5
  126. package/dist/orchestration/edit-retry.js +3 -6
  127. package/dist/orchestration/inline-media-eager.d.ts +13 -0
  128. package/dist/orchestration/inline-media-eager.js +58 -0
  129. package/dist/orchestration/inline-media.d.ts +22 -0
  130. package/dist/orchestration/inline-media.js +151 -0
  131. package/dist/orchestration/interactions/ask-user-resume.js +3 -7
  132. package/dist/orchestration/routing/commands/usage-format.js +3 -0
  133. package/dist/orchestration/routing/webhook.js +4 -0
  134. package/dist/orchestration/session-compact.js +5 -7
  135. package/dist/orchestration/session-events.d.ts +2 -1
  136. package/dist/orchestration/session-events.js +1 -0
  137. package/dist/orchestration/transcript-sink.d.ts +6 -0
  138. package/dist/orchestration/transcript-sink.js +21 -2
  139. package/dist/orchestration/turn/turn-prep.d.ts +0 -8
  140. package/dist/orchestration/turn/turn-prep.js +0 -51
  141. package/dist/orchestration/turn/turn.js +4 -0
  142. package/dist/platform/adapters/tui/ports.d.ts +1 -1
  143. package/dist/platform/adapters/tui/tui-transcript.js +2 -0
  144. package/dist/platform/browser/agent-browser.d.ts +50 -0
  145. package/dist/platform/browser/agent-browser.js +165 -0
  146. package/dist/platform/browser/managed-browser.d.ts +1 -11
  147. package/dist/platform/browser/managed-browser.js +4 -12
  148. package/dist/platform/ui-http/browser-stream.d.ts +110 -0
  149. package/dist/platform/ui-http/browser-stream.js +447 -0
  150. package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
  151. package/dist/platform/ui-http/ui-http-server.js +23 -6
  152. package/dist/store/conversation-history-reader.js +8 -0
  153. package/dist/store/conversation-history-repo.d.ts +8 -1
  154. package/dist/store/conversation-history-repo.js +5 -0
  155. package/dist/store/session-registry-journal.d.ts +0 -8
  156. package/dist/store/session-registry-journal.js +5 -17
  157. package/dist/store/session-registry-repo.d.ts +2 -3
  158. package/dist/store/session-registry-repo.js +0 -2
  159. package/package.json +4 -2
  160. package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
  161. package/web/dist/assets/index-CaSZPg_H.css +1 -0
  162. package/web/dist/assets/index-CzOR7Edh.js +522 -0
  163. package/web/dist/assets/{index-DaViXAg-.js → index-cIGFv27z.js} +1 -1
  164. package/web/dist/index.html +3 -2
  165. package/web/dist/theme.css +6 -0
  166. package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
  167. package/dist/agent-adapter/browser-mcp-server.js +0 -28
  168. package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
  169. package/dist/agent-adapter/claude/browser-mcp.js +0 -10
  170. package/web/dist/assets/index-Cgx3gdHV.css +0 -1
  171. package/web/dist/assets/index-CpZWBVHr.js +0 -494
@@ -0,0 +1,487 @@
1
+ import { createLogger } from '../../core/log.js';
2
+ import { acquireBrowser, releaseBrowser, browserStatus, BROWSER_DEVICE_SERVER, } from '../../platform/browser/managed-browser.js';
3
+ import { agentBrowserArgs, agentBrowserBaseEnv, agentBrowserSessionName, isTabGone, resolveAgentBrowserBin, runAgentBrowserProcess, AgentBrowserMissingError, } from '../../platform/browser/agent-browser.js';
4
+ import { acquireDeviceBrowser, releaseDeviceBrowser } from '../remote/device-browser.js';
5
+ import { getOnlineDevices, isDeviceOnline } from '../remote/client-manager.js';
6
+ import { getMachineRegistry } from '../remote/machine-registry.js';
7
+ const log = createLogger('browser-broker');
8
+ /**
9
+ * Browser leases for `cortex-browser`, held per Cortex session rather than per turn.
10
+ *
11
+ * A lease ties one session to one device's shared Chrome (server-local, or a device's through the
12
+ * reverse channel) and to one agent-browser session pinned to its own tab there. It holds one
13
+ * reference on that Chrome, is renewed by every call, and is released, closing its tab, after
14
+ * {@link LEASE_IDLE_MS} without one. Page state survives between turns because nothing here is torn
15
+ * down per turn.
16
+ */
17
+ export const LEASE_IDLE_MS = 10 * 60_000;
18
+ /** How long a device endpoint is trusted before a call re-checks it through the tunnel. */
19
+ const DEVICE_VERIFY_MS = 15_000;
20
+ const VERIFY_TIMEOUT_MS = 5_000;
21
+ /** A lease failure meant for a human: what went wrong, and what to do about it. */
22
+ export class BrowserLeaseError extends Error {
23
+ code;
24
+ hint;
25
+ constructor(code, message, hint) {
26
+ super(message);
27
+ this.name = 'BrowserLeaseError';
28
+ this.code = code;
29
+ this.hint = hint;
30
+ }
31
+ }
32
+ function str(value) {
33
+ return typeof value === 'string' ? value.trim() : '';
34
+ }
35
+ /** Turn a device launch failure (often a bare marker from the launch script) into a sentence. */
36
+ export function describeDeviceFailure(device, raw) {
37
+ const text = raw.trim();
38
+ const other = `or run without --device to use the server's browser`;
39
+ if (text.includes('chrome-not-found')) {
40
+ return { message: `Chrome is not installed on ${device}`, hint: `install Google Chrome on ${device}, ${other}` };
41
+ }
42
+ if (text.includes('no-interactive-user')) {
43
+ return { message: `nobody is logged in to the desktop on ${device}`, hint: `log in on ${device}, ${other}` };
44
+ }
45
+ if (text.includes('interactive-user-mismatch')) {
46
+ return {
47
+ message: `the Cortex client on ${device} runs as a different user than the desktop session`,
48
+ hint: `run the Cortex client as the logged-in user on ${device}`,
49
+ };
50
+ }
51
+ if (text.includes('chrome-did-not-listen')) {
52
+ return {
53
+ message: `Chrome on ${device} did not open its debugging port in time`,
54
+ hint: `close any Chrome window still using the Cortex profile on ${device} and retry`,
55
+ };
56
+ }
57
+ if (/timed out/i.test(text)) {
58
+ return { message: `${device} did not answer while starting Chrome (${text})`, hint: `check that ${device} is awake and its Cortex client is connected` };
59
+ }
60
+ return { message: `could not start Chrome on ${device}: ${text || 'unknown error'}` };
61
+ }
62
+ export function createBrowserBroker(deps) {
63
+ const leases = new Map();
64
+ const sessionChains = new Map();
65
+ const deviceChains = new Map();
66
+ const lastVerified = new Map();
67
+ const listeners = new Set();
68
+ let runtime = null;
69
+ function notify() {
70
+ for (const fn of listeners) {
71
+ try {
72
+ fn();
73
+ }
74
+ catch (e) {
75
+ log.warn(`listener failed: ${e.message}`);
76
+ }
77
+ }
78
+ }
79
+ /** Run `fn` after every earlier call queued under `key` has settled. */
80
+ function serial(chains, key, fn) {
81
+ const prev = chains.get(key) ?? Promise.resolve();
82
+ const next = prev.catch(() => undefined).then(fn);
83
+ const tail = next.catch(() => undefined);
84
+ chains.set(key, tail);
85
+ void tail.then(() => { if (chains.get(key) === tail)
86
+ chains.delete(key); });
87
+ return next;
88
+ }
89
+ function getRuntime() {
90
+ if (runtime)
91
+ return runtime;
92
+ try {
93
+ runtime = { bin: deps.resolveBin(), env: deps.baseEnv() };
94
+ }
95
+ catch (e) {
96
+ if (e instanceof AgentBrowserMissingError)
97
+ throw new BrowserLeaseError('engine-missing', e.message, e.hint);
98
+ throw e;
99
+ }
100
+ return runtime;
101
+ }
102
+ function arm(lease) {
103
+ if (lease.idleTimer)
104
+ clearTimeout(lease.idleTimer);
105
+ lease.idleTimer = setTimeout(() => {
106
+ lease.idleTimer = null;
107
+ // A human mid-login can take a while; their session keeps the browser.
108
+ if (lease.takenOver) {
109
+ arm(lease);
110
+ return;
111
+ }
112
+ if (leases.get(lease.sessionId) !== lease)
113
+ return;
114
+ log.info(`${lease.sessionId}: browser idle for ${Math.round(deps.idleMs / 60_000)} min — releasing`);
115
+ void serial(sessionChains, lease.sessionId, async () => {
116
+ if (leases.get(lease.sessionId) === lease && !lease.takenOver)
117
+ await retire(lease);
118
+ });
119
+ }, deps.idleMs);
120
+ lease.idleTimer.unref?.();
121
+ }
122
+ function touch(lease) {
123
+ lease.lastUsedAt = deps.now();
124
+ arm(lease);
125
+ }
126
+ /**
127
+ * End a lease: drop its Chrome reference, close the session's tab and stop its agent-browser
128
+ * daemon. Closing the tab makes an idle release look the same as Chrome being reclaimed, and
129
+ * keeps a Chrome that other sessions hold open from collecting abandoned tabs. Logins live in
130
+ * the profile, not the tab. The next call in the session finds its tab gone and opens a new one.
131
+ *
132
+ * The reference goes first: if this was the last tab, Chrome exits, and with no reference left
133
+ * it is not restarted.
134
+ */
135
+ async function retire(lease) {
136
+ if (lease.idleTimer)
137
+ clearTimeout(lease.idleTimer);
138
+ lease.idleTimer = null;
139
+ if (leases.get(lease.sessionId) === lease)
140
+ leases.delete(lease.sessionId);
141
+ lastVerified.delete(lease);
142
+ if (lease.holdsRef) {
143
+ lease.holdsRef = false;
144
+ deps.release(lease.device);
145
+ }
146
+ notify();
147
+ if (!lease.cdpEndpoint || !runtime)
148
+ return;
149
+ // With --cdp even here: a call without it makes agent-browser launch a Chrome of its own.
150
+ for (const command of [['tab', 'close'], ['close']]) {
151
+ await deps.run(runtime.bin, agentBrowserArgs(lease.cdpEndpoint, lease.abSession, command), runtime.env)
152
+ .catch(() => undefined);
153
+ }
154
+ }
155
+ /** Record a failure on the lease and keep it listed, without a Chrome reference, until the next
156
+ * call retries or the idle timer drops it — so the UI can show why the browser is not there. */
157
+ function fail(lease, err) {
158
+ if (lease.holdsRef) {
159
+ lease.holdsRef = false;
160
+ deps.release(lease.device);
161
+ }
162
+ lastVerified.delete(lease);
163
+ lease.state = 'error';
164
+ lease.error = err.hint ? `${err.message} — ${err.hint}` : err.message;
165
+ lease.cdpEndpoint = null;
166
+ notify();
167
+ return err;
168
+ }
169
+ function checkDevice(device) {
170
+ if (device === BROWSER_DEVICE_SERVER)
171
+ return;
172
+ const { state, online } = deps.availability(device);
173
+ if (state === 'online')
174
+ return;
175
+ const known = online.length ? `online devices: ${['server', ...online].join(', ')}` : 'no devices are online';
176
+ if (state === 'offline') {
177
+ throw new BrowserLeaseError('device-offline', `device "${device}" is offline`, `start its Cortex client, or pick another device (${known})`);
178
+ }
179
+ throw new BrowserLeaseError('unknown-device', `unknown device "${device}"`, `use one of: server${online.length ? `, ${online.join(', ')}` : ''}`);
180
+ }
181
+ function chromeError(device, e) {
182
+ if (e instanceof BrowserLeaseError)
183
+ return e;
184
+ const raw = e?.message ?? String(e);
185
+ if (device === BROWSER_DEVICE_SERVER) {
186
+ return new BrowserLeaseError('chrome-failed', `could not start Chrome on the server: ${raw}`);
187
+ }
188
+ const { message, hint } = describeDeviceFailure(device, raw);
189
+ return new BrowserLeaseError('chrome-failed', message, hint);
190
+ }
191
+ function acquireOn(device) {
192
+ // Device launches are serialized: two concurrent first acquires would each launch and map.
193
+ return device === BROWSER_DEVICE_SERVER
194
+ ? deps.acquire(device)
195
+ : serial(deviceChains, device, () => deps.acquire(device));
196
+ }
197
+ async function start(lease) {
198
+ try {
199
+ checkDevice(lease.device);
200
+ getRuntime();
201
+ lease.cdpEndpoint = await acquireOn(lease.device);
202
+ lease.holdsRef = true;
203
+ lease.state = 'ready';
204
+ lease.error = undefined;
205
+ lastVerified.set(lease, deps.now());
206
+ log.info(`${lease.sessionId}: browser ready on ${lease.device} (${lease.abSession})`);
207
+ }
208
+ catch (e) {
209
+ throw fail(lease, chromeError(lease.device, e));
210
+ }
211
+ notify();
212
+ }
213
+ /** Make sure an existing ready lease still points at a live Chrome. */
214
+ async function revalidate(lease) {
215
+ const due = lease.device === BROWSER_DEVICE_SERVER
216
+ || deps.now() - (lastVerified.get(lease) ?? 0) >= DEVICE_VERIFY_MS;
217
+ if (!due || !lease.cdpEndpoint)
218
+ return;
219
+ try {
220
+ checkDevice(lease.device);
221
+ const endpoint = await (lease.device === BROWSER_DEVICE_SERVER
222
+ ? deps.refresh(lease.device, lease.cdpEndpoint)
223
+ : serial(deviceChains, lease.device, () => deps.refresh(lease.device, lease.cdpEndpoint)));
224
+ lastVerified.set(lease, deps.now());
225
+ if (endpoint !== lease.cdpEndpoint) {
226
+ log.info(`${lease.sessionId}: ${lease.device} browser moved to ${endpoint}`);
227
+ lease.cdpEndpoint = endpoint;
228
+ notify();
229
+ }
230
+ }
231
+ catch (e) {
232
+ throw fail(lease, chromeError(lease.device, e));
233
+ }
234
+ }
235
+ /** The session's lease on `device` (or its current device), created or renewed. */
236
+ function ensure(sessionId, device, refuseTakenOver) {
237
+ return serial(sessionChains, sessionId, async () => {
238
+ let lease = leases.get(sessionId);
239
+ if (refuseTakenOver && lease?.takenOver) {
240
+ throw new BrowserLeaseError('taken-over', 'the user is controlling this browser right now', 'wait for them to hand it back, or ask them; do not retry in a loop');
241
+ }
242
+ const target = device || lease?.device || BROWSER_DEVICE_SERVER;
243
+ if (lease && (lease.device !== target || lease.state === 'error')) {
244
+ const takenOver = lease.takenOver;
245
+ await retire(lease);
246
+ lease = undefined;
247
+ if (takenOver)
248
+ log.info(`${sessionId}: switching device ends the takeover`);
249
+ }
250
+ if (lease?.state === 'ready') {
251
+ await revalidate(lease);
252
+ touch(lease);
253
+ return lease;
254
+ }
255
+ const fresh = {
256
+ sessionId, device: target, abSession: agentBrowserSessionName(sessionId, target),
257
+ state: 'starting', cdpEndpoint: null, holdsRef: false, takenOver: false,
258
+ lastUsedAt: deps.now(), idleTimer: null, refreshing: false, refreshAgain: false,
259
+ };
260
+ leases.set(sessionId, fresh);
261
+ touch(fresh);
262
+ notify();
263
+ await start(fresh);
264
+ return fresh;
265
+ });
266
+ }
267
+ function existing(sessionId) {
268
+ const lease = leases.get(sessionId);
269
+ if (!lease)
270
+ throw new BrowserLeaseError('no-lease', `session ${sessionId} has no browser`);
271
+ return lease;
272
+ }
273
+ function ready(sessionId) {
274
+ const lease = existing(sessionId);
275
+ if (lease.state !== 'ready' || !lease.cdpEndpoint) {
276
+ throw new BrowserLeaseError('no-lease', `the browser for session ${sessionId} is ${lease.state}`);
277
+ }
278
+ return lease;
279
+ }
280
+ async function exec(lease, args) {
281
+ const rt = getRuntime();
282
+ const run = () => deps.run(rt.bin, agentBrowserArgs(lease.cdpEndpoint, lease.abSession, args), rt.env);
283
+ const first = await run();
284
+ if (first.code === 0 || !isTabGone(first.stderr))
285
+ return first;
286
+ // The Chrome behind the binding was replaced or the tab closed: bind a fresh tab, once.
287
+ log.info(`${lease.sessionId}: bound tab is gone — opening a new one`);
288
+ const rebound = await deps.run(rt.bin, agentBrowserArgs(lease.cdpEndpoint, lease.abSession, ['tab', 'new']), rt.env);
289
+ if (rebound.code !== 0)
290
+ return first;
291
+ return run();
292
+ }
293
+ async function refreshInfo(lease) {
294
+ if (lease.refreshing) {
295
+ lease.refreshAgain = true;
296
+ return;
297
+ }
298
+ lease.refreshing = true;
299
+ try {
300
+ do {
301
+ lease.refreshAgain = false;
302
+ if (leases.get(lease.sessionId) !== lease || lease.state !== 'ready' || !runtime)
303
+ return;
304
+ const read = async (what) => {
305
+ const r = await deps.run(runtime.bin, agentBrowserArgs(lease.cdpEndpoint, lease.abSession, ['--json', 'get', what]), runtime.env);
306
+ if (r.code !== 0)
307
+ return undefined;
308
+ try {
309
+ return str(JSON.parse(r.stdout)?.data?.[what]) || undefined;
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ };
315
+ const [url, title] = [await read('url'), await read('title')];
316
+ if (url !== lease.url || title !== lease.title) {
317
+ lease.url = url;
318
+ lease.title = title;
319
+ notify();
320
+ }
321
+ } while (lease.refreshAgain);
322
+ }
323
+ finally {
324
+ lease.refreshing = false;
325
+ }
326
+ }
327
+ function parseJson(stdout) {
328
+ try {
329
+ return JSON.parse(stdout);
330
+ }
331
+ catch {
332
+ return null;
333
+ }
334
+ }
335
+ return {
336
+ async leaseBrowser({ sessionId, device }) {
337
+ const sid = str(sessionId);
338
+ if (!sid) {
339
+ throw new BrowserLeaseError('bad-request', 'no session id', 'cortex-browser must run inside a Cortex session (CORTEX_SESSION_ID is unset)');
340
+ }
341
+ const lease = await ensure(sid, str(device) || null, true);
342
+ return { device: lease.device, cdpEndpoint: lease.cdpEndpoint, abSession: lease.abSession };
343
+ },
344
+ listBrowserSessions() {
345
+ return [...leases.values()]
346
+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt)
347
+ .map((l) => ({
348
+ sessionId: l.sessionId, device: l.device, abSession: l.abSession, state: l.state,
349
+ ...(l.error ? { error: l.error } : {}),
350
+ ...(l.url ? { url: l.url } : {}),
351
+ ...(l.title ? { title: l.title } : {}),
352
+ takenOver: l.takenOver, lastUsedAt: l.lastUsedAt,
353
+ }));
354
+ },
355
+ async runAgentBrowser(sessionId, args) {
356
+ const lease = await ensure(sessionId, null, false);
357
+ const result = await exec(lease, args);
358
+ void refreshInfo(lease);
359
+ return result;
360
+ },
361
+ async streamPort(sessionId) {
362
+ const lease = leases.get(sessionId);
363
+ if (!lease || lease.state !== 'ready')
364
+ return null;
365
+ const status = parseJson((await exec(lease, ['--json', 'stream', 'status'])).stdout);
366
+ if (status?.data?.enabled && typeof status.data.port === 'number')
367
+ return status.data.port;
368
+ const enabled = parseJson((await exec(lease, ['--json', 'stream', 'enable'])).stdout);
369
+ return typeof enabled?.data?.port === 'number' ? enabled.data.port : null;
370
+ },
371
+ setTakeover(sessionId, on) {
372
+ const lease = existing(sessionId);
373
+ if (lease.takenOver === on)
374
+ return;
375
+ lease.takenOver = on;
376
+ touch(lease);
377
+ log.info(`${sessionId}: browser ${on ? 'taken over by the user' : 'handed back to the agent'}`);
378
+ notify();
379
+ },
380
+ isTakenOver(sessionId) {
381
+ return leases.get(sessionId)?.takenOver ?? false;
382
+ },
383
+ async insertText(sessionId, text) {
384
+ const lease = ready(sessionId);
385
+ const result = await exec(lease, ['keyboard', 'inserttext', text]);
386
+ if (result.code !== 0) {
387
+ throw new Error(result.stderr.trim() || `agent-browser exited ${result.code}`);
388
+ }
389
+ },
390
+ noteBrowserCommand(sessionId) {
391
+ const lease = leases.get(str(sessionId));
392
+ if (!lease)
393
+ return;
394
+ touch(lease);
395
+ void refreshInfo(lease);
396
+ },
397
+ agentBrowserRuntime() {
398
+ return getRuntime();
399
+ },
400
+ onBrowserSessionsChanged(listener) {
401
+ listeners.add(listener);
402
+ return () => { listeners.delete(listener); };
403
+ },
404
+ shutdown() {
405
+ for (const lease of leases.values()) {
406
+ if (lease.idleTimer)
407
+ clearTimeout(lease.idleTimer);
408
+ }
409
+ leases.clear();
410
+ listeners.clear();
411
+ },
412
+ };
413
+ }
414
+ async function endpointAlive(cdpEndpoint) {
415
+ try {
416
+ const res = await fetch(`${cdpEndpoint}/json/version`, { signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS) });
417
+ return res.ok;
418
+ }
419
+ catch {
420
+ return false;
421
+ }
422
+ }
423
+ export function defaultBrokerDeps() {
424
+ return {
425
+ async acquire(device) {
426
+ return device === BROWSER_DEVICE_SERVER
427
+ ? (await acquireBrowser()).cdpEndpoint
428
+ : (await acquireDeviceBrowser(device)).cdpEndpoint;
429
+ },
430
+ release(device) {
431
+ if (device === BROWSER_DEVICE_SERVER)
432
+ releaseBrowser();
433
+ else
434
+ releaseDeviceBrowser(device);
435
+ },
436
+ async refresh(device, cdpEndpoint) {
437
+ if (device === BROWSER_DEVICE_SERVER) {
438
+ // The managed browser restarts itself after a crash while references remain; only a
439
+ // browser that gave up needs a fresh start, and acquire+release leaves our one reference.
440
+ const live = browserStatus().browser?.cdpEndpoint;
441
+ if (live)
442
+ return live;
443
+ const endpoint = (await acquireBrowser()).cdpEndpoint;
444
+ releaseBrowser();
445
+ return endpoint;
446
+ }
447
+ if (await endpointAlive(cdpEndpoint))
448
+ return cdpEndpoint;
449
+ // A dead endpoint: the next acquire drops the stale entry, our reference with it, and the
450
+ // reference it hands back is ours.
451
+ return (await acquireDeviceBrowser(device)).cdpEndpoint;
452
+ },
453
+ availability(device) {
454
+ const online = getOnlineDevices().map((d) => d.device).sort();
455
+ if (isDeviceOnline(device))
456
+ return { state: 'online', online };
457
+ return { state: Object.hasOwn(getMachineRegistry(), device) ? 'offline' : 'unknown', online };
458
+ },
459
+ resolveBin: () => resolveAgentBrowserBin(),
460
+ baseEnv: () => agentBrowserBaseEnv(),
461
+ run: (bin, args, env) => runAgentBrowserProcess(bin, args, { env }),
462
+ now: () => Date.now(),
463
+ idleMs: LEASE_IDLE_MS,
464
+ };
465
+ }
466
+ let broker = null;
467
+ function instance() {
468
+ broker ??= createBrowserBroker(defaultBrokerDeps());
469
+ return broker;
470
+ }
471
+ /** Test seam: swap the process-wide broker (pass null to rebuild it from the real deps). */
472
+ export function _setBrowserBroker(next) {
473
+ broker = next;
474
+ }
475
+ export const leaseBrowser = (input) => instance().leaseBrowser(input);
476
+ export const listBrowserSessions = () => instance().listBrowserSessions();
477
+ export const runAgentBrowser = (sid, args) => instance().runAgentBrowser(sid, args);
478
+ export const streamPort = (sid) => instance().streamPort(sid);
479
+ export const setTakeover = (sid, on) => instance().setTakeover(sid, on);
480
+ export const isTakenOver = (sid) => instance().isTakenOver(sid);
481
+ export const insertText = (sid, text) => instance().insertText(sid, text);
482
+ export const noteBrowserCommand = (sid) => instance().noteBrowserCommand(sid);
483
+ export const agentBrowserRuntime = () => instance().agentBrowserRuntime();
484
+ export const onBrowserSessionsChanged = (fn) => instance().onBrowserSessionsChanged(fn);
485
+ export function shutdownBrowserBroker() {
486
+ broker?.shutdown();
487
+ }
@@ -9,6 +9,9 @@ const RESET_PROGRAM = 'cedar_ember';
9
9
  const GRANT_ID = /^[a-z0-9_-]{1,40}$/;
10
10
  /** The account windows the gateway quota path also reports, so both sources fill one row. */
11
11
  const WINDOW_TYPES = ['five_hour', 'seven_day'];
12
+ /** Claude Code reads its rate-limit header `seven_day_overage_included` as this per-model weekly
13
+ * limit, so the reading takes that type to share the throttle's window and policy. */
14
+ const SCOPED_WEEKLY_TYPE = 'seven_day_overage_included';
12
15
  const CLAIM_STATUS = {
13
16
  reset: 'reset',
14
17
  already_used: 'already_redeemed',
@@ -41,6 +44,21 @@ function usageWindow(raw, type) {
41
44
  return null;
42
45
  return { type, utilization: used / 100, resetsAt: isoSeconds(raw.resets_at) };
43
46
  }
47
+ function scopedModelName(raw) {
48
+ const model = isRecord(raw.scope) && isRecord(raw.scope.model) ? raw.scope.model : null;
49
+ return typeof model?.display_name === 'string' && model.display_name ? model.display_name : null;
50
+ }
51
+ /** The first `limits[]` entry scoped to one model's weekly use (e.g. Fable). */
52
+ function scopedWeeklyWindow(limits) {
53
+ for (const raw of Array.isArray(limits) ? limits : []) {
54
+ const label = isRecord(raw) && raw.kind === 'weekly_scoped' ? scopedModelName(raw) : null;
55
+ if (!label)
56
+ continue;
57
+ const window = usageWindow({ utilization: raw.percent, resets_at: raw.resets_at }, SCOPED_WEEKLY_TYPE);
58
+ return window ? { ...window, label } : null;
59
+ }
60
+ return null;
61
+ }
44
62
  function usableGrant(raw) {
45
63
  if (!isRecord(raw) || typeof raw.id !== 'string' || !GRANT_ID.test(raw.id))
46
64
  return null;
@@ -84,6 +102,9 @@ export function parseClaudeUsage(payload) {
84
102
  });
85
103
  if (windows.length === 0)
86
104
  throw new Error('Claude usage response has no rate-limit window');
105
+ const scoped = scopedWeeklyWindow(payload.limits);
106
+ if (scoped)
107
+ windows.push(scoped);
87
108
  const status = isRecord(payload.cedar_ember) ? payload.cedar_ember : null;
88
109
  return { windows, resetCredits: status ? resetCredits(status) : null };
89
110
  }
@@ -18,6 +18,7 @@ const DEFAULT_THRESHOLD = 0.90;
18
18
  const RESUME_BUFFER_MS = 5_000;
19
19
  const EXPIRY_RETRY_DELAY_MS = 5_000;
20
20
  const OUTAGE_WINDOW_TYPE = 'outage';
21
+ const MODEL_SCOPED_WINDOW_TYPE = 'model_scoped';
21
22
  let _adapter = null;
22
23
  let _persistence = null;
23
24
  let _onResume = null;
@@ -109,8 +110,9 @@ function canonicalProvider(provider) {
109
110
  const trimmed = provider?.trim();
110
111
  return trimmed ? trimmed : null;
111
112
  }
113
+ /** A label is part of the identity only for a model-scoped window; elsewhere it is display text. */
112
114
  function sameWindowIdentity(type, label, candidate) {
113
- return candidate.type === type && candidate.label === label;
115
+ return candidate.type === type && (type !== MODEL_SCOPED_WINDOW_TYPE || candidate.label === label);
114
116
  }
115
117
  function resolveProviderPolicy(provider, type, label) {
116
118
  const override = getSettings().providerRateLimits[provider];
@@ -12,6 +12,8 @@ export type ResetStatus = 'reset' | 'nothing_to_reset' | 'no_credit' | 'already_
12
12
  * time yet. */
13
13
  export interface AccountWindow {
14
14
  type: string;
15
+ /** Provider display name for a window scoped to one model. */
16
+ label?: string;
15
17
  utilization: number;
16
18
  /** Epoch seconds. */
17
19
  resetsAt: number | null;
@@ -55,7 +55,7 @@ export declare class UsageService {
55
55
  private carryQuotaFromPrior;
56
56
  /**
57
57
  * Deleting a row is only safe when spend collection actually answered. If the gateway is
58
- * unreachable, fall back to "add but never remove" so a transient outage cannot wipe history.
58
+ * unreachable, retain history, except empty Anthropic placeholders that never held any data.
59
59
  */
60
60
  private guardDeletions;
61
61
  /**
@@ -332,6 +332,17 @@ function applyCodexRecord(draft, record) {
332
332
  if (record.resetCredits)
333
333
  draft.resetCredits = record.resetCredits;
334
334
  }
335
+ /** Legacy rows without billing can carry quota, but metered rows never establish a subscription. */
336
+ function isAnthropicQuotaRow(record) {
337
+ return record.provider === ANTHROPIC_PROVIDER && record.billing !== 'api';
338
+ }
339
+ function hasQuotaEvidence(record) {
340
+ return record.windows.length > 0 || record.observedAt !== null || record.resetCredits !== undefined;
341
+ }
342
+ /** Default modes and failure notes alone were enough to persist these old placeholders. */
343
+ function isEmptyAnthropicPlaceholder(record) {
344
+ return isAnthropicQuotaRow(record) && !hasQuotaEvidence(record) && record.spend === undefined;
345
+ }
335
346
  function staleCopy(record, note) {
336
347
  const { note: _priorNote, ...retained } = record;
337
348
  // 'unsupported' means the row has no quota concept at all, so ageing it to 'never'
@@ -427,15 +438,17 @@ export class UsageService {
427
438
  applyAnthropicQuota(drafts, result, anthropicModes, prior) {
428
439
  if (anthropicModes.length === 0) {
429
440
  const existing = drafts.get(draftKey(ANTHROPIC_PROVIDER, 'subscription'));
430
- if (existing)
431
- existing.notes.push(t('ux.usage.anthropicDisabled'));
441
+ existing?.notes.push(t('ux.usage.anthropicDisabled'));
432
442
  return;
433
443
  }
434
444
  const quota = settledAnthropicQuota(result);
445
+ const inUse = drafts.has(draftKey(ANTHROPIC_PROVIDER, 'subscription'))
446
+ || prior.some((row) => isAnthropicQuotaRow(row) && hasQuotaEvidence(row));
447
+ if (!quota.snapshot && !inUse)
448
+ return;
435
449
  const draft = ensureDraft(drafts, ANTHROPIC_PROVIDER, 'subscription');
436
450
  draft.quotaPolled = true;
437
- for (const mode of anthropicModes)
438
- draft.modes.add(mode);
451
+ anthropicModes.forEach((mode) => draft.modes.add(mode));
439
452
  draft.notes.push(...quota.notes);
440
453
  if (quota.snapshot) {
441
454
  draft.windows = quota.snapshot.windows;
@@ -443,7 +456,7 @@ export class UsageService {
443
456
  draft.freshness = quota.snapshot.live ? 'live' : 'stale';
444
457
  }
445
458
  else {
446
- this.carryQuotaFromPrior(draft, prior);
459
+ this.carryQuotaFromPrior(draft, prior.filter((row) => !isEmptyAnthropicPlaceholder(row)));
447
460
  }
448
461
  draft.resetCredits = anthropicResets(quota, prior);
449
462
  }
@@ -478,7 +491,7 @@ export class UsageService {
478
491
  }
479
492
  /**
480
493
  * Deleting a row is only safe when spend collection actually answered. If the gateway is
481
- * unreachable, fall back to "add but never remove" so a transient outage cannot wipe history.
494
+ * unreachable, retain history, except empty Anthropic placeholders that never held any data.
482
495
  */
483
496
  guardDeletions(composed, prior, today, month) {
484
497
  if (today.status === 'fulfilled' && month.status === 'fulfilled')
@@ -487,7 +500,7 @@ export class UsageService {
487
500
  const note = t('ux.usage.gatewayFailed', { error: errorMessage(reason) });
488
501
  const seen = new Set(composed.map(usageRecordKey));
489
502
  const retained = prior
490
- .filter((row) => !seen.has(usageRecordKey(row)))
503
+ .filter((row) => !seen.has(usageRecordKey(row)) && !isEmptyAnthropicPlaceholder(row))
491
504
  .map((row) => staleCopy(row, note));
492
505
  return [...composed.map((row) => (row.note ? row : { ...row, note })), ...retained];
493
506
  }
@@ -50,7 +50,7 @@ async function sendFiles(ctx, input) {
50
50
  return sentSummary(Array.isArray(body.data) ? body.data : [body.data], input.device);
51
51
  }
52
52
  export function registerUiFileTools(server, ctx) {
53
- server.tool('send_file', 'Share produced files as downloadable chat cards (images preview inline). Send one file or an ordered group with a shared caption. Supports local or remote-device files.', {
53
+ server.tool('send_file', 'Share produced files as downloadable chat cards (images preview inline). Send one file or an ordered group with a shared caption. Supports local or remote-device files. Embed images or videos in reply text with ![alt](src), using a local absolute/~/relative path, workspace/... path, registered-device:/absolute/path (or device:C:/path on Windows), or https:// URL.', {
54
54
  file_path: z.string().optional().describe(`${FILE_PATH_DESC} Use this OR \`files\`.`),
55
55
  file_name: z.string().optional().describe('Display filename override for file_path.'),
56
56
  files: z.array(z.object({
@@ -13,7 +13,7 @@ const log = createLogger('device-browser');
13
13
  * channel maps it onto a loopback port here.
14
14
  */
15
15
  /** Chrome's own startup, plus the device round trip. Generous: a cold Chrome on a busy laptop is
16
- * slow, and the alternative to waiting is a turn with no browser tools. */
16
+ * slow, and the alternative to waiting is a failed `cortex-browser` call. */
17
17
  const LAUNCH_TIMEOUT_MS = 90_000;
18
18
  /** One HTTP GET through the tunnel. If this is slow, the tunnel is broken, not the browser. */
19
19
  const VERIFY_TIMEOUT_MS = 5_000;
@@ -82,6 +82,8 @@ function unixChromeLaunchCommand(platform) {
82
82
  '[ -n "$CHROME" ] || { echo "chrome-not-found" >&2; exit 3; }',
83
83
  'nohup "$CHROME" --remote-debugging-port=0 --remote-debugging-address=127.0.0.1'
84
84
  + ' --user-data-dir="$PROFILE" --no-first-run --no-default-browser-check'
85
+ // Linux only (macOS ignores it): skip the keyring D-Bus probe that stalls the first page ~25s.
86
+ + ' --password-store=basic'
85
87
  + ' about:blank >/dev/null 2>&1 &',
86
88
  'for _ in $(seq 1 60); do [ -s "$PORTFILE" ] && break; sleep 0.5; done',
87
89
  '[ -s "$PORTFILE" ] || { echo "chrome-did-not-listen" >&2; exit 4; }', 'head -1 "$PORTFILE"',
@@ -4,8 +4,8 @@ import { requestStream } from './reverse-stream.js';
4
4
  import { sendControlMessage } from './client-manager.js';
5
5
  const log = createLogger('device-port');
6
6
  /**
7
- * Why a real local socket at all (plan/embedded-browser.md §18.1): the consumer is Playwright,
8
- * which takes a `--cdp-endpoint` URL, does `GET /json/version`, then opens a WebSocket. It needs
7
+ * Why a real local socket at all (plan/embedded-browser.md §18.1): the consumer is agent-browser,
8
+ * which takes a `--cdp` URL, does `GET /json/version`, then opens a WebSocket. It needs
9
9
  * something it can dial. So the server binds a loopback port and every byte written to it comes
10
10
  * out of a TCP connection on the device — no CDP awareness anywhere in the path, which is what
11
11
  * makes the same tunnel serve TensorBoard, Jupyter and dashboards for free.