@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,447 @@
1
+ import * as crypto from 'crypto';
2
+ import { WebSocket, WebSocketServer } from 'ws';
3
+ import { timingSafeEqualStr } from '../../core/auth.js';
4
+ import { createLogger } from '../../core/log.js';
5
+ import { readJsonBody, sendError, sendJson, sendMethodNotAllowed } from './http-json.js';
6
+ const log = createLogger('browser-stream');
7
+ // The agent's browser, seen and driven from the app. Each Cortex session that holds a browser lease
8
+ // has an agent-browser daemon session, and that daemon serves a live JPEG stream plus an input
9
+ // channel on a loopback port. This module lists those sessions, proxies the stream to the app over
10
+ // the ui-http server, and lets a person take the page over from the agent.
11
+ //
12
+ // Authentication of the stream: a page cannot put `x-cortex-token` on a WebSocket handshake, and the
13
+ // cookie / Cloudflare Access legs would ride along on any cross-site handshake. So the socket is
14
+ // opened with a one-shot ticket instead: the app first POSTs for one through the ordinary gate (token,
15
+ // session cookie or Access JWT, plus the Origin check every state-changing request gets), then
16
+ // presents it on the handshake. A ticket names one session, lives for seconds and is spent on use.
17
+ //
18
+ // A takeover belongs to the app window that asked for it (its `client` id, which also rides on that
19
+ // window's stream ticket). Only that window's input reaches the page, and the page goes back to the
20
+ // agent by itself when the person is gone: once the window's stream has been closed for
21
+ // TAKEOVER_GRACE_MS without coming back (dock closed, page reloaded, network lost), or after
22
+ // TAKEOVER_IDLE_MS without a click, key or paste. The broker only knows on/off; the watch lives here.
23
+ export const BROWSER_SESSIONS_PATH = '/api/browser/sessions';
24
+ export const BROWSER_TICKET_PATH = '/api/browser/stream-ticket';
25
+ export const BROWSER_STREAM_PATH = '/api/browser/stream';
26
+ export const BROWSER_TAKEOVER_PATH = '/api/browser/takeover';
27
+ export const BROWSER_INSERT_TEXT_PATH = '/api/browser/insert-text';
28
+ /** The session has no stream to attach to (no lease, still starting, or its daemon went away). */
29
+ export const CLOSE_NO_STREAM = 4004;
30
+ /** The upstream stream ended underneath a live viewer. The app reconnects with a fresh ticket. */
31
+ export const CLOSE_UPSTREAM_GONE = 4010;
32
+ const TICKET_TTL_MS = 30_000;
33
+ const MAX_TICKETS = 256;
34
+ const MAX_STREAMS = 32;
35
+ const DEFAULT_FPS = 10;
36
+ const MAX_FPS = 15;
37
+ /** Input and acks are tiny; anything near this is not a client of ours. */
38
+ const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024;
39
+ /** Longest text the paste field may insert at once. */
40
+ export const MAX_INSERT_TEXT_CHARS = 4000;
41
+ /** A viewer this far behind is shed frames rather than buffered without bound. */
42
+ const MAX_DOWNSTREAM_BUFFER = 4 * 1024 * 1024;
43
+ const UPSTREAM_CONNECT_TIMEOUT_MS = 5_000;
44
+ /** How long a takeover survives its window's stream being gone, so a reload or a blip keeps it. */
45
+ export const TAKEOVER_GRACE_MS = 30_000;
46
+ /** How long a takeover lasts without any input from the person. */
47
+ export const TAKEOVER_IDLE_MS = 10 * 60_000;
48
+ /** Message the proxy adds to the stream whenever the takeover changes (and once on connect). */
49
+ export const TAKEOVER_MESSAGE = 'cortex_takeover';
50
+ /** An app window's id: opaque, not a credential — every caller is already authenticated. */
51
+ const CLIENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
52
+ // ── Pure helpers ─────────────────────────────────────────────────────────────
53
+ const INPUT_TYPES = new Set(['input_mouse', 'input_keyboard', 'input_touch']);
54
+ /**
55
+ * Decide what of a viewer's message reaches the page. Acks always pass (they only pace frames);
56
+ * input passes only from the window holding the page, so a watcher can never steer it by accident.
57
+ * Everything else (a `config` raising the frame rate, unknown types) is dropped. `input` marks the
58
+ * person's own activity, which keeps the takeover alive.
59
+ */
60
+ export function admitClientMessage(raw, holdsPage) {
61
+ let msg;
62
+ try {
63
+ msg = JSON.parse(raw);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (!msg || typeof msg !== 'object')
69
+ return null;
70
+ const type = msg.type;
71
+ if (type === 'ack') {
72
+ const seq = msg.seq;
73
+ return typeof seq === 'number' && Number.isFinite(seq) ? { message: JSON.stringify({ type: 'ack', seq }), input: false } : null;
74
+ }
75
+ if (typeof type === 'string' && INPUT_TYPES.has(type) && holdsPage)
76
+ return { message: raw, input: true };
77
+ return null;
78
+ }
79
+ /** A body's `client`: '' when absent, null when present but malformed. */
80
+ export function parseClientId(value) {
81
+ if (value === undefined || value === null || value === '')
82
+ return '';
83
+ return typeof value === 'string' && CLIENT_ID.test(value) ? value : null;
84
+ }
85
+ /** The frame-rate cap a viewer asked for, clamped to what the tunnel should carry. */
86
+ export function clampFps(raw) {
87
+ const n = Number(raw);
88
+ if (!raw || !Number.isFinite(n) || n <= 0)
89
+ return DEFAULT_FPS;
90
+ return Math.min(MAX_FPS, Math.max(1, Math.round(n)));
91
+ }
92
+ export function parseStreamTarget(rawUrl) {
93
+ let url;
94
+ try {
95
+ url = new URL(rawUrl, 'http://localhost');
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ const sessionId = url.searchParams.get('session') ?? '';
101
+ const ticket = url.searchParams.get('ticket') ?? '';
102
+ if (!sessionId || !ticket)
103
+ return null;
104
+ return { sessionId, ticket, fps: clampFps(url.searchParams.get('maxFps')) };
105
+ }
106
+ export function createTicketStore(now = Date.now) {
107
+ const tickets = new Map();
108
+ const prune = () => {
109
+ const t = now();
110
+ for (const [id, entry] of tickets)
111
+ if (entry.expiresAt <= t)
112
+ tickets.delete(id);
113
+ };
114
+ return {
115
+ mint(sessionId, client = '') {
116
+ prune();
117
+ // A burst past the cap drops the oldest: a ticket is cheap to ask for again.
118
+ while (tickets.size >= MAX_TICKETS)
119
+ tickets.delete(tickets.keys().next().value);
120
+ const id = crypto.randomBytes(32).toString('hex');
121
+ tickets.set(id, { sessionId, client, expiresAt: now() + TICKET_TTL_MS });
122
+ return id;
123
+ },
124
+ // A constant-time walk rather than a Map lookup, as the UI session store does: the ticket is a
125
+ // credential for a few seconds, and the set is a handful of entries.
126
+ redeem(ticket, sessionId) {
127
+ prune();
128
+ let hit = null;
129
+ for (const id of tickets.keys())
130
+ if (timingSafeEqualStr(id, ticket))
131
+ hit = id;
132
+ if (hit === null)
133
+ return null;
134
+ const entry = tickets.get(hit);
135
+ tickets.delete(hit);
136
+ return entry.sessionId === sessionId ? { client: entry.client } : null;
137
+ },
138
+ size: () => {
139
+ prune();
140
+ return tickets.size;
141
+ },
142
+ };
143
+ }
144
+ export function createTakeoverWatch(deps) {
145
+ const holds = new Map();
146
+ const stop = (hold) => {
147
+ if (hold.grace)
148
+ clearTimeout(hold.grace);
149
+ if (hold.idle)
150
+ clearTimeout(hold.idle);
151
+ hold.grace = null;
152
+ hold.idle = null;
153
+ };
154
+ const expire = (sessionId, hold, reason) => {
155
+ if (holds.get(sessionId) !== hold)
156
+ return;
157
+ stop(hold);
158
+ holds.delete(sessionId);
159
+ // The broker may already have dropped it (lease retired); then there is nothing to hand back.
160
+ if (deps.isTakenOver(sessionId))
161
+ deps.release(sessionId, reason);
162
+ };
163
+ // One timer per hold, checked lazily: input only moves the timestamp, the timer re-arms itself.
164
+ const armIdle = (sessionId, hold) => {
165
+ const wait = Math.max(0, hold.lastInputAt + deps.idleMs - deps.now());
166
+ hold.idle = setTimeout(() => {
167
+ hold.idle = null;
168
+ if (deps.now() - hold.lastInputAt >= deps.idleMs)
169
+ expire(sessionId, hold, 'idle');
170
+ else
171
+ armIdle(sessionId, hold);
172
+ }, wait);
173
+ hold.idle.unref?.();
174
+ };
175
+ const armGrace = (sessionId, hold) => {
176
+ if (hold.grace)
177
+ return;
178
+ hold.grace = setTimeout(() => {
179
+ hold.grace = null;
180
+ expire(sessionId, hold, 'disconnected');
181
+ }, deps.graceMs);
182
+ hold.grace.unref?.();
183
+ };
184
+ return {
185
+ begin(sessionId, client) {
186
+ const prev = holds.get(sessionId);
187
+ if (prev)
188
+ stop(prev);
189
+ const hold = { client, lastInputAt: deps.now(), grace: null, idle: null };
190
+ holds.set(sessionId, hold);
191
+ armIdle(sessionId, hold);
192
+ if (!deps.hasClient(sessionId, client))
193
+ armGrace(sessionId, hold);
194
+ },
195
+ end(sessionId) {
196
+ const hold = holds.get(sessionId);
197
+ if (!hold)
198
+ return;
199
+ stop(hold);
200
+ holds.delete(sessionId);
201
+ },
202
+ holder: (sessionId) => holds.get(sessionId)?.client ?? null,
203
+ connected(sessionId, client) {
204
+ const hold = holds.get(sessionId);
205
+ if (hold?.client === client && hold.grace) {
206
+ clearTimeout(hold.grace);
207
+ hold.grace = null;
208
+ }
209
+ },
210
+ disconnected(sessionId, client) {
211
+ const hold = holds.get(sessionId);
212
+ if (hold?.client === client && !deps.hasClient(sessionId, client))
213
+ armGrace(sessionId, hold);
214
+ },
215
+ input(sessionId) {
216
+ const hold = holds.get(sessionId);
217
+ if (hold)
218
+ hold.lastInputAt = deps.now();
219
+ },
220
+ close() {
221
+ for (const hold of holds.values())
222
+ stop(hold);
223
+ holds.clear();
224
+ },
225
+ };
226
+ }
227
+ // ── Routes ───────────────────────────────────────────────────────────────────
228
+ function publicView(s) {
229
+ return {
230
+ sessionId: s.sessionId,
231
+ device: s.device,
232
+ state: s.state,
233
+ ...(s.error ? { error: s.error } : {}),
234
+ ...(s.url ? { url: s.url } : {}),
235
+ ...(s.title ? { title: s.title } : {}),
236
+ takenOver: s.takenOver,
237
+ lastUsedAt: s.lastUsedAt,
238
+ };
239
+ }
240
+ /** `{ session }` from a POST body for a session that holds a browser, or null after answering. */
241
+ async function readSessionBody(req, res, deps) {
242
+ if (req.method !== 'POST') {
243
+ sendMethodNotAllowed(res, 'POST');
244
+ return null;
245
+ }
246
+ const body = await readJsonBody(req, res);
247
+ if (!body)
248
+ return null;
249
+ const sessionId = typeof body.session === 'string' ? body.session : '';
250
+ if (!sessionId) {
251
+ sendError(res, 400, 'missing-session', 'session is required');
252
+ return null;
253
+ }
254
+ if (!deps.listSessions().some((s) => s.sessionId === sessionId)) {
255
+ sendError(res, 404, 'no-browser', 'This session has no browser');
256
+ return null;
257
+ }
258
+ return { sessionId, body };
259
+ }
260
+ export function createBrowserStream(deps, opts = {}) {
261
+ const now = deps.now ?? Date.now;
262
+ const tickets = createTicketStore(now);
263
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_CLIENT_MESSAGE_BYTES });
264
+ const live = new Set();
265
+ const viewersOf = (sessionId) => [...live].filter((v) => v.sessionId === sessionId);
266
+ const holdsPage = (viewer) => viewer.client !== '' && deps.isTakenOver(viewer.sessionId) && watch.holder(viewer.sessionId) === viewer.client;
267
+ /** Tell each viewer of the session whether the page is held, and whether by its own window. */
268
+ const announce = (sessionId) => {
269
+ for (const viewer of viewersOf(sessionId)) {
270
+ if (viewer.ws.readyState !== WebSocket.OPEN)
271
+ continue;
272
+ viewer.ws.send(JSON.stringify({
273
+ type: TAKEOVER_MESSAGE, takenOver: deps.isTakenOver(sessionId), mine: holdsPage(viewer),
274
+ }));
275
+ }
276
+ };
277
+ const watch = createTakeoverWatch({
278
+ isTakenOver: deps.isTakenOver,
279
+ hasClient: (sessionId, client) => client !== '' && viewersOf(sessionId).some((v) => v.client === client),
280
+ now,
281
+ graceMs: opts.graceMs ?? TAKEOVER_GRACE_MS,
282
+ idleMs: opts.idleMs ?? TAKEOVER_IDLE_MS,
283
+ release: (sessionId, reason) => {
284
+ void (async () => {
285
+ try {
286
+ await deps.setTakeover(sessionId, false);
287
+ }
288
+ catch (err) {
289
+ log.warn(`could not hand ${sessionId} back: ${err.message}`);
290
+ return;
291
+ }
292
+ log.info(`browser handed back automatically (${reason === 'idle' ? 'no input' : 'window gone'}): ${sessionId}`);
293
+ announce(sessionId);
294
+ })();
295
+ },
296
+ });
297
+ const routes = {
298
+ [BROWSER_SESSIONS_PATH]: async (req, res) => {
299
+ if (req.method !== 'GET')
300
+ return sendMethodNotAllowed(res, 'GET');
301
+ sendJson(res, 200, { ok: true, data: { sessions: deps.listSessions().map(publicView) } }, { 'Cache-Control': 'no-store' });
302
+ },
303
+ [BROWSER_TICKET_PATH]: async (req, res) => {
304
+ const target = await readSessionBody(req, res, deps);
305
+ if (!target)
306
+ return;
307
+ const client = parseClientId(target.body.client);
308
+ if (client === null)
309
+ return sendError(res, 400, 'bad-client', 'client must be 1-64 letters, digits, _ or -');
310
+ sendJson(res, 200, { ok: true, data: { ticket: tickets.mint(target.sessionId, client) } }, { 'Cache-Control': 'no-store' });
311
+ },
312
+ [BROWSER_TAKEOVER_PATH]: async (req, res) => {
313
+ const target = await readSessionBody(req, res, deps);
314
+ if (!target)
315
+ return;
316
+ const on = target.body.on;
317
+ if (typeof on !== 'boolean')
318
+ return sendError(res, 400, 'bad-on', 'on must be a boolean');
319
+ const client = parseClientId(target.body.client);
320
+ // A takeover is held by a window, so taking one needs to say which.
321
+ if (client === null || (on && client === '')) {
322
+ return sendError(res, 400, 'bad-client', 'client must be 1-64 letters, digits, _ or -');
323
+ }
324
+ await deps.setTakeover(target.sessionId, on);
325
+ if (on)
326
+ watch.begin(target.sessionId, client);
327
+ else
328
+ watch.end(target.sessionId);
329
+ log.info(`browser ${on ? 'taken over' : 'handed back'}: ${target.sessionId}`);
330
+ announce(target.sessionId);
331
+ sendJson(res, 200, { ok: true, data: { takenOver: deps.isTakenOver(target.sessionId) } });
332
+ },
333
+ [BROWSER_INSERT_TEXT_PATH]: async (req, res) => {
334
+ const target = await readSessionBody(req, res, deps);
335
+ if (!target)
336
+ return;
337
+ const text = typeof target.body.text === 'string' ? target.body.text : '';
338
+ if (!text)
339
+ return sendError(res, 400, 'missing-text', 'text is required');
340
+ if (text.length > MAX_INSERT_TEXT_CHARS) {
341
+ return sendError(res, 400, 'text-too-long', `text exceeds ${MAX_INSERT_TEXT_CHARS} characters`);
342
+ }
343
+ // Typing into the page is the person's move, so it needs the page to be theirs.
344
+ if (!deps.isTakenOver(target.sessionId))
345
+ return sendError(res, 409, 'not-taken-over', 'Take over the browser first');
346
+ watch.input(target.sessionId);
347
+ try {
348
+ await deps.insertText(target.sessionId, text);
349
+ }
350
+ catch (err) {
351
+ return sendError(res, 502, 'insert-failed', err.message);
352
+ }
353
+ sendJson(res, 200, { ok: true, data: {} });
354
+ },
355
+ };
356
+ const attach = async (viewer, target) => {
357
+ const { ws } = viewer;
358
+ let port = null;
359
+ try {
360
+ port = await deps.streamPort(target.sessionId);
361
+ }
362
+ catch (err) {
363
+ log.warn(`stream port lookup failed for ${target.sessionId}: ${err.message}`);
364
+ }
365
+ if (ws.readyState !== WebSocket.OPEN)
366
+ return;
367
+ if (port === null) {
368
+ ws.close(CLOSE_NO_STREAM, 'no stream');
369
+ return;
370
+ }
371
+ // Ack pacing end to end: the app acks each frame once drawn, so a slow tunnel holds one frame in
372
+ // flight instead of a queue of stale ones.
373
+ const upstream = new WebSocket(`ws://127.0.0.1:${port}/?maxFps=${target.fps}&pacing=ack`, {
374
+ handshakeTimeout: UPSTREAM_CONNECT_TIMEOUT_MS,
375
+ });
376
+ let opened = false;
377
+ const finish = (code, reason) => {
378
+ if (upstream.readyState === WebSocket.OPEN || upstream.readyState === WebSocket.CONNECTING)
379
+ upstream.terminate();
380
+ if (ws.readyState === WebSocket.OPEN)
381
+ ws.close(code, reason);
382
+ };
383
+ upstream.on('open', () => {
384
+ opened = true;
385
+ });
386
+ upstream.on('message', (data, isBinary) => {
387
+ if (ws.readyState !== WebSocket.OPEN)
388
+ return;
389
+ if (ws.bufferedAmount > MAX_DOWNSTREAM_BUFFER)
390
+ return;
391
+ ws.send(data, { binary: isBinary });
392
+ });
393
+ upstream.on('close', () => finish(opened ? CLOSE_UPSTREAM_GONE : CLOSE_NO_STREAM, opened ? 'stream ended' : 'no stream'));
394
+ upstream.on('error', (err) => {
395
+ log.warn(`upstream stream error for ${target.sessionId}: ${err.message}`);
396
+ finish(opened ? CLOSE_UPSTREAM_GONE : CLOSE_NO_STREAM, opened ? 'stream ended' : 'no stream');
397
+ });
398
+ ws.on('message', (data, isBinary) => {
399
+ if (isBinary || upstream.readyState !== WebSocket.OPEN)
400
+ return;
401
+ const admitted = admitClientMessage(data.toString(), holdsPage(viewer));
402
+ if (!admitted)
403
+ return;
404
+ if (admitted.input)
405
+ watch.input(target.sessionId);
406
+ upstream.send(admitted.message);
407
+ });
408
+ ws.on('close', () => finish(1000, 'viewer closed'));
409
+ };
410
+ const handleUpgrade = (req, socket, head) => {
411
+ const target = parseStreamTarget(req.url ?? '');
412
+ const redeemed = target ? tickets.redeem(target.ticket, target.sessionId) : null;
413
+ if (!target || !redeemed) {
414
+ log.warn('browser stream refused: missing or invalid ticket');
415
+ socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
416
+ socket.destroy();
417
+ return;
418
+ }
419
+ if (live.size >= MAX_STREAMS) {
420
+ log.warn(`browser stream refused (${live.size} already open)`);
421
+ socket.write('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
422
+ socket.destroy();
423
+ return;
424
+ }
425
+ wss.handleUpgrade(req, socket, head, (ws) => {
426
+ const viewer = { ws, sessionId: target.sessionId, client: redeemed.client };
427
+ live.add(viewer);
428
+ watch.connected(viewer.sessionId, viewer.client);
429
+ ws.on('close', () => {
430
+ live.delete(viewer);
431
+ watch.disconnected(viewer.sessionId, viewer.client);
432
+ });
433
+ ws.on('error', () => ws.terminate());
434
+ // Before any frame: whether this window may steer the page.
435
+ ws.send(JSON.stringify({ type: TAKEOVER_MESSAGE, takenOver: deps.isTakenOver(viewer.sessionId), mine: holdsPage(viewer) }));
436
+ void attach(viewer, target);
437
+ });
438
+ };
439
+ const close = () => {
440
+ watch.close();
441
+ for (const viewer of live)
442
+ viewer.ws.terminate();
443
+ live.clear();
444
+ wss.close();
445
+ };
446
+ return { routes, handleUpgrade, close };
447
+ }
@@ -1,4 +1,5 @@
1
1
  import * as http from 'http';
2
+ import type { Duplex } from 'stream';
2
3
  import type { AnyRouter } from '@trpc/server';
3
4
  import type { AccessJwtVerifier } from './access-jwt.js';
4
5
  export interface UiHttpServerOptions {
@@ -43,6 +44,17 @@ export interface UiHttpServerOptions {
43
44
  * this host). Defaults to on; `CORTEX_PORT_FORWARD=0` at the call site turns it off.
44
45
  */
45
46
  portForward?: boolean;
47
+ /**
48
+ * WebSocket endpoints beyond the port forward, by exact path. Each authenticates its own handshake
49
+ * (a page cannot set `x-cortex-token` on one); the server only applies the Origin check first, the
50
+ * same one every state-changing request gets, and closes each route on shutdown.
51
+ */
52
+ upgradeRoutes?: Record<string, UpgradeRoute>;
53
+ }
54
+ /** A WebSocket endpoint mounted on the server's `upgrade` event. */
55
+ export interface UpgradeRoute {
56
+ handleUpgrade: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void;
57
+ close: () => void;
46
58
  }
47
59
  /** Handler for a custom API route mounted on the HTTP server. Receives the raw request
48
60
  * and response after the auth gate passes; responsible for the full lifecycle
@@ -258,20 +258,35 @@ export function createUiHttpServer(opts) {
258
258
  // `authorize(req)` here instead of `isAuthorized` would silently hand every logged-in page a raw
259
259
  // socket to any loopback service on this host. See plan/embedded-browser.md §10.
260
260
  const forward = opts.portForward === false ? null : createPortForward();
261
- if (forward) {
261
+ const upgradeRoutes = opts.upgradeRoutes ?? {};
262
+ if (forward || Object.keys(upgradeRoutes).length > 0) {
262
263
  server.on('upgrade', (req, socket, head) => {
263
264
  const pathname = (req.url ?? '').split('?')[0];
264
- if (pathname !== FORWARD_PATH) {
265
+ if (forward && pathname === FORWARD_PATH) {
266
+ if (!isAuthorized(req, opts.getToken)) {
267
+ log.warn(`forward auth rejected: ${req.url}`);
268
+ socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
269
+ socket.destroy();
270
+ return;
271
+ }
272
+ forward.handleUpgrade(req, socket, head);
273
+ return;
274
+ }
275
+ const route = Object.hasOwn(upgradeRoutes, pathname) ? upgradeRoutes[pathname] : undefined;
276
+ if (!route) {
265
277
  socket.destroy();
266
278
  return;
267
279
  }
268
- if (!isAuthorized(req, opts.getToken)) {
269
- log.warn(`forward auth rejected: ${req.url}`);
270
- socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
280
+ // A handshake carries cookies like any request, so a foreign page is refused before the route
281
+ // ever sees it.
282
+ const allowList = typeof opts.corsOrigins === 'function' ? opts.corsOrigins() : opts.corsOrigins;
283
+ if (!isTrustedOrigin(req, allowList)) {
284
+ log.warn(`ui-http cross-origin upgrade refused: ${pathname} from ${firstHeader(req.headers.origin)}`);
285
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
271
286
  socket.destroy();
272
287
  return;
273
288
  }
274
- forward.handleUpgrade(req, socket, head);
289
+ route.handleUpgrade(req, socket, head);
275
290
  });
276
291
  }
277
292
  server.listen(opts.port, host, () => {
@@ -281,6 +296,8 @@ export function createUiHttpServer(opts) {
281
296
  });
282
297
  const close = () => new Promise((resolve) => {
283
298
  forward?.close();
299
+ for (const route of Object.values(upgradeRoutes))
300
+ route.close();
284
301
  // Force-close keep-alive + live SSE sockets, else server.close() would hang on them.
285
302
  server.closeAllConnections?.();
286
303
  server.close(() => resolve());
@@ -229,6 +229,12 @@ function pushWorkerProgress(state, ev) {
229
229
  type: 'worker-progress', text: ev.text ?? '', worker: ev.worker, ts: ev.ts, turnIndex: turnFor(state),
230
230
  });
231
231
  }
232
+ function pushThinking(state, ev) {
233
+ pushEvent(state, {
234
+ type: 'thinking', text: ev.text ?? '', ts: ev.ts, turnIndex: turnFor(state),
235
+ ...(ev.blockId ? { blockId: ev.blockId } : {}),
236
+ });
237
+ }
232
238
  function mergeResolvedInteraction(prior, ev) {
233
239
  prior.status = ev.status;
234
240
  if (ev.result !== undefined)
@@ -292,6 +298,8 @@ function consumeParsedEvent(state, ev, chars) {
292
298
  return pushUser(state, ev);
293
299
  if (ev.type === 'assistant')
294
300
  return pushAssistant(state, ev);
301
+ if (ev.type === 'thinking')
302
+ return pushThinking(state, ev);
295
303
  if (ev.type === 'tool')
296
304
  return pushTool(state, ev, chars);
297
305
  if (ev.type === 'worker-progress')
@@ -8,7 +8,7 @@ import type { BoardActionRef } from '../core/board-action.js';
8
8
  export declare const CONVERSATION_HISTORY_DIR: string;
9
9
  /** `worker-progress`: a team worker's interim final reply, recorded in its LEAD's history for
10
10
  * display. It is not a user turn (no turn boundary) and never reaches the lead model. */
11
- export type HistoryEventType = 'user' | 'assistant' | 'tool' | 'interaction' | 'worker-progress';
11
+ export type HistoryEventType = 'user' | 'assistant' | 'thinking' | 'tool' | 'interaction' | 'worker-progress';
12
12
  /** Terminal state of one native subagent, as the backend's own task lifecycle reports it. */
13
13
  export type SubagentEndStatus = 'completed' | 'failed' | 'killed';
14
14
  export interface HistoryDebugDetails {
@@ -73,6 +73,7 @@ export interface HistoryEvent {
73
73
  type: HistoryEventType;
74
74
  /** user / assistant message text (omitted for tool events). */
75
75
  text?: string;
76
+ blockId?: string;
76
77
  /** User events only: this turn was authored by Cortex (resume signal, task/thread callback,
77
78
  * subtask question, backgrounded agent result), not typed by a human. Absent = human, which is
78
79
  * what every row written before this field existed reads as. */
@@ -150,6 +151,7 @@ export interface RawEvent {
150
151
  /** edit-marker lines only. */
151
152
  originalTs?: string;
152
153
  text?: string;
154
+ blockId?: string;
153
155
  /** user lines only: Cortex authored this turn rather than a human (see HistoryEvent). */
154
156
  systemOrigin?: SystemTurnOrigin;
155
157
  noticeLevel?: ChatNoticeLevel;
@@ -312,6 +314,11 @@ export declare class ConversationHistoryRepo {
312
314
  subagent?: SubagentRowRef;
313
315
  subagentSpawns?: SubagentSpawnRef[];
314
316
  }): Promise<void>;
317
+ appendThinking(sessionId: string, opts: {
318
+ text: string;
319
+ blockId?: string;
320
+ ts?: string;
321
+ }): Promise<void>;
315
322
  appendDecisionAction(sessionId: string, opts: {
316
323
  decisionId: string;
317
324
  action: DecisionActionKind;
@@ -324,6 +324,11 @@ export class ConversationHistoryRepo {
324
324
  ...subagentRowFields(opts.subagent),
325
325
  });
326
326
  }
327
+ appendThinking(sessionId, opts) {
328
+ return this.append(sessionId, {
329
+ type: 'thinking', text: opts.text, blockId: opts.blockId, ts: opts.ts ?? nowIso(),
330
+ });
331
+ }
327
332
  appendDecisionAction(sessionId, opts) {
328
333
  return this.append(sessionId, {
329
334
  type: 'decision-action', decisionId: opts.decisionId, action: opts.action,
@@ -9,13 +9,6 @@ export interface PendingSessionDelete {
9
9
  session: SessionRecord;
10
10
  cleanup: SessionDeleteCleanup;
11
11
  }
12
- /** Per-session browser opt-in (plan/embedded-browser.md §17). Absent/null means the session gets
13
- * ZERO browser tools — the whole point of making this opt-in is that ~24 Playwright tools are not
14
- * worth their context cost in a session that never browses. `device` names WHERE the browser runs;
15
- * only 'server' exists until the cortex-client reverse channel lands. */
16
- export interface SessionBrowserOption {
17
- device: string;
18
- }
19
12
  export interface SessionRecord {
20
13
  sessionId: string;
21
14
  projectId: string;
@@ -45,7 +38,6 @@ export interface SessionRecord {
45
38
  * the next turn; compaction clears it, because compaction drops the delivered copy. */
46
39
  boardBlockFor?: string | null;
47
40
  contextUsage?: unknown;
48
- browser?: SessionBrowserOption | null;
49
41
  /** Team mode: the lead session that owns this worker. Non-null means this session is a worker. */
50
42
  teamLeadId?: string | null;
51
43
  /** The worker's short name, unique within its lead's team. */