@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
package/dist/entry/app.js CHANGED
@@ -21,6 +21,8 @@ import { registerCommands } from '../orchestration/routing/commands/index.js';
21
21
  import { buildAuthRequiredLoginAction } from '../orchestration/routing/commands/login-notice.js';
22
22
  import { usageResetNoticeActions } from '../orchestration/routing/commands/usage-reset.js';
23
23
  import { recoverWaitpoints, startWaitpointSweep } from '../orchestration/waitpoint-sweep.js';
24
+ import { startCacheKeepWarm } from '../orchestration/cache-keep-warm.js';
25
+ import { startClaudeWindowWarmup } from '../orchestration/claude-window-warmup.js';
24
26
  import { projectStore } from '../domain/projects/index.js';
25
27
  import { sendStartupDmIfConfigured } from './startup-notify.js';
26
28
  import { installSigtermShutdown } from './shutdown.js';
@@ -107,9 +109,12 @@ import { registerAuthWatch } from '../domain/auth/auth-watch.js';
107
109
  import { onLoginSuccess } from '../domain/auth/login-flow.js';
108
110
  import { syncGatewayFromBackends } from '../domain/auth/gateway-sync.js';
109
111
  import { createSessionRetentionController } from '../orchestration/session-retention-controller.js';
112
+ import { ensureOwnBinsOnPath } from '../domain/system/own-bin-path.js';
113
+ import { defaultTerminalCliContext, syncTerminalCli } from '../domain/system/terminal-cli/index.js';
110
114
  // Static imports are evaluated before this line, so this is how long module loading took.
111
115
  const importsMs = Math.round(performance.now());
112
116
  loadRuntimeDotenv(path.join(CONFIG_DIR, '.env'));
117
+ ensureOwnBinsOnPath();
113
118
  await migrateEnvToSettings();
114
119
  // Ensure the WebSocket + webhook bearer tokens exist before either server starts. Generates
115
120
  // and persists them to .env on first run (fail-closed auth — see core/auth.ts). Must run after
@@ -164,6 +169,19 @@ async function runRetentionSweep(retentionDays, signal) {
164
169
  const attachmentsPruned = result.stopped ? 0 : await pruneInboundAttachments(retentionDays);
165
170
  log.info(`Retention sweep${result.stopped ? ' stopped early' : ''}: registry=${result.registryCommitted} history=${result.historyOrphanDeleted} pi=${result.piOrphanDeleted} capture=${result.claudeCaptureDeleted} toolImages=${result.toolImagesDeleted} attachments=${attachmentsPruned} errors=${result.errors.length} in ${Date.now() - startedAt}ms`);
166
171
  }
172
+ /** Deferred past startup: the first Windows install calls PowerShell synchronously. */
173
+ function syncTerminalCommand() {
174
+ setTimeout(() => {
175
+ try {
176
+ const result = syncTerminalCli(defaultTerminalCliContext(DATA_DIR));
177
+ if (result.files.length)
178
+ log.info(`Terminal command ${result.action}: ${result.files.join(', ')}`);
179
+ }
180
+ catch (error) {
181
+ log.warn(`Terminal command setup failed; retrying at next start: ${error.message}`);
182
+ }
183
+ }, 0);
184
+ }
167
185
  const retentionController = createSessionRetentionController({
168
186
  getRetentionDays: () => getSettings().sessionRetentionDays,
169
187
  onSettingsChange,
@@ -544,6 +562,10 @@ installSigtermShutdown(shutdownHandles);
544
562
  // S13: register hook-bridge event subscribers (bodies extracted to orch/routing/hook-bridge-subscribers.ts)
545
563
  registerHookBridgeSubscribers(bus, adapter, planApprovals);
546
564
  installTeamDelivery(bus);
565
+ // Claude prompt caches of idle sessions that still expect a wake, read before their hour runs out.
566
+ startCacheKeepWarm();
567
+ // Claude's five-hour window, reopened after it closes while Claude sits idle (when enabled).
568
+ startClaudeWindowWarmup();
547
569
  // Worker reports a restart kept from their leads: delivered now that sessions and the adapter are up.
548
570
  void flushTeamOutbox()
549
571
  .then((n) => { if (n > 0)
@@ -568,4 +590,5 @@ installSigtermShutdown(shutdownHandles);
568
590
  : 'provider setup required';
569
591
  log.info(`Cortex agent is running (${adapter.name}) — ${selectionSummary}`
570
592
  + ` · boot ${Math.round(performance.now())}ms (imports ${importsMs}ms)`);
593
+ syncTerminalCommand();
571
594
  })();
@@ -0,0 +1,39 @@
1
+ export interface ParsedBrowserArgs {
2
+ help: boolean;
3
+ device: string | null;
4
+ args: string[];
5
+ command: string | null;
6
+ }
7
+ export declare class BrowserUsageError extends Error {
8
+ }
9
+ export declare function parseBrowserArgs(argv: string[]): ParsedBrowserArgs;
10
+ /** Does this command run without a browser (help, version, bundled skills)? */
11
+ export declare function isLocalCommand(parsed: ParsedBrowserArgs): boolean;
12
+ /** Make the file arguments of file-writing commands absolute against the caller's directory. */
13
+ export declare function absolutizePaths(args: string[], cwd: string): string[];
14
+ export interface LeaseData {
15
+ device: string;
16
+ cdpEndpoint: string;
17
+ abSession: string;
18
+ bin: string;
19
+ env: Record<string, string>;
20
+ }
21
+ export interface BrowserCliOptions {
22
+ env?: NodeJS.ProcessEnv;
23
+ cwd?: string;
24
+ post?: (url: string, body: unknown, headers: Record<string, string>) => Promise<{
25
+ status: number;
26
+ body: any;
27
+ }>;
28
+ /** Run agent-browser with stdout passed through (discarded when `quiet`); resolves its exit code
29
+ * and captured stderr. */
30
+ exec?: (bin: string, args: string[], env: Record<string, string>, cwd: string, quiet?: boolean) => Promise<{
31
+ code: number;
32
+ stderr: string;
33
+ }>;
34
+ writeErr?: (text: string) => void;
35
+ /** Delay before telling the caller the browser is still starting. */
36
+ slowNoticeMs?: number;
37
+ }
38
+ export declare function runBrowserCli(argv: string[], options?: BrowserCliOptions): Promise<number>;
39
+ export declare function main(argv?: string[]): Promise<void>;
@@ -0,0 +1,317 @@
1
+ #!/usr/bin/env node
2
+ import * as path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { formatError, formatHelp } from '../core/cli-utils.js';
5
+ import { AUTH_HEADER } from '../core/auth.js';
6
+ import { isMainModule } from '../core/utils.js';
7
+ import { agentBrowserArgs, agentBrowserBaseEnv, agentBrowserCallEnv, isTabGone, resolveAgentBrowserBin, AgentBrowserMissingError, } from '../platform/browser/agent-browser.js';
8
+ /**
9
+ * `cortex-browser`: agent-browser, attached to the Chrome Cortex manages for this session.
10
+ *
11
+ * Each call leases the session's browser from the daemon (starting Chrome if needed), then runs
12
+ * agent-browser here so its output streams straight back. Every failure is an error with a reason;
13
+ * nothing quietly falls back to a different browser.
14
+ */
15
+ const HELP = {
16
+ name: 'cortex-browser',
17
+ description: [
18
+ "Drive a real browser from any Cortex session: agent-browser, attached to the session's own tab",
19
+ "in the Chrome Cortex manages on the server or on one of your devices.",
20
+ '',
21
+ 'Every argument except --device is passed to agent-browser. Full command guide:',
22
+ ' cortex-browser skills get core',
23
+ ].join('\n'),
24
+ usage: 'cortex-browser [--device <name>] <agent-browser command> [args...]',
25
+ options: [
26
+ { flag: '--device <name>', description: "Whose Chrome: 'server' or a connected device. Sticks for the session", default: "the session's last device, else server" },
27
+ { flag: '--help, -h', description: 'Show this help (agent-browser <command> --help for one command)' },
28
+ ],
29
+ examples: [
30
+ { description: 'Open a page and list what can be clicked', command: 'cortex-browser open http://127.0.0.1:5173 && cortex-browser snapshot -i' },
31
+ { description: 'Click a ref from the snapshot, then capture the result', command: 'cortex-browser click @e2 && cortex-browser screenshot ./after-click.png' },
32
+ { description: "Use the Chrome on the user's machine (its localhost, its logins)", command: 'cortex-browser --device my-pc open https://example.com' },
33
+ { description: 'Read the version-matched command reference', command: 'cortex-browser skills get core --full' },
34
+ ],
35
+ };
36
+ /** Flags that would point agent-browser at a different browser, daemon or tab than the lease. */
37
+ const RESERVED_FLAGS = new Set([
38
+ '--cdp', '--session', '--no-pin-tab', '--auto-connect', '--provider', '-p', '--namespace', '--engine',
39
+ '--executable-path',
40
+ ]);
41
+ /** Commands that need no browser and so no lease. */
42
+ const LOCAL_COMMANDS = new Set(['skills', 'help']);
43
+ /** Commands that would change the shared setup underneath every session. */
44
+ const BLOCKED_COMMANDS = {
45
+ connect: 'cortex-browser already connects each call to the session browser',
46
+ install: 'Chrome is managed by Cortex; agent-browser does not install its own',
47
+ upgrade: 'agent-browser is pinned to the version Cortex ships with',
48
+ dashboard: "watch the browser in the Cortex app's Agent browser tab instead",
49
+ mcp: 'call cortex-browser commands directly',
50
+ };
51
+ /** Global agent-browser flags that take a value, so the value is not mistaken for the command. */
52
+ const VALUE_FLAGS = new Set([
53
+ '--session', '--namespace', '--executable-path', '--extension', '--init-script', '--enable', '--args',
54
+ '--user-agent', '--proxy', '--proxy-bypass', '--ca-cert', '--hide-scrollbars', '--provider', '-p',
55
+ '--screenshot-dir', '--screenshot-quality', '--screenshot-format', '--input-mode', '--cdp',
56
+ '--color-scheme', '--download-path', '--max-output', '--allowed-domains', '--action-policy',
57
+ '--confirm-actions', '--idle-timeout', '--engine', '--model', '--config', '--profile',
58
+ '--restore-save', '--restore-check-url', '--restore-check-text', '--restore-check-fn', '--session-name',
59
+ '--state', '--headers', '--threshold', '--baseline', '-d', '--depth', '-s', '--selector',
60
+ ]);
61
+ /** Flags whose value is a directory or file wherever they appear. */
62
+ const PATH_FLAGS = new Set(['--screenshot-dir', '--download-path', '--baseline']);
63
+ /**
64
+ * Commands that write or read local files, and how many leading positionals are not files
65
+ * (`download <selector> <path>`). The daemon resolves a relative path against ITS working
66
+ * directory, not the caller's, so these are made absolute before they leave this process.
67
+ */
68
+ const FILE_COMMANDS = {
69
+ screenshot: 0, pdf: 0, download: 1, upload: 1, record: 0, trace: 0, profiler: 0, network: 0, har: 0,
70
+ state: 0, diff: 0,
71
+ };
72
+ const FILE_EXTENSIONS = /\.(png|jpe?g|webp|gif|pdf|webm|mp4|json|har|zip|txt|html?|csv|xml|md|log|cpuprofile)$/i;
73
+ export class BrowserUsageError extends Error {
74
+ }
75
+ /** The first token that is neither a flag nor a flag's value, with its index. */
76
+ function findCommand(args) {
77
+ for (let i = 0; i < args.length; i += 1) {
78
+ const token = args[i];
79
+ if (token.startsWith('-')) {
80
+ if (VALUE_FLAGS.has(token))
81
+ i += 1;
82
+ continue;
83
+ }
84
+ return { command: token, index: i };
85
+ }
86
+ return { command: null, index: -1 };
87
+ }
88
+ export function parseBrowserArgs(argv) {
89
+ let device = null;
90
+ const args = [];
91
+ for (let i = 0; i < argv.length; i += 1) {
92
+ const token = argv[i];
93
+ if (token === '--device' || token.startsWith('--device=')) {
94
+ const value = token === '--device' ? argv[i + 1] : token.slice('--device='.length);
95
+ if (!value || value.startsWith('-')) {
96
+ throw new BrowserUsageError(formatError('--device requires a device name', {
97
+ hint: "use 'server' for this machine, or a connected device name (cortex-browser --device my-pc open …)",
98
+ }));
99
+ }
100
+ device = value;
101
+ if (token === '--device')
102
+ i += 1;
103
+ continue;
104
+ }
105
+ const flag = token.split('=')[0];
106
+ if (RESERVED_FLAGS.has(flag)) {
107
+ throw new BrowserUsageError(formatError(`${flag} is set by cortex-browser and cannot be passed`, {
108
+ hint: 'cortex-browser attaches every call to this session\'s own tab; use --device to pick whose Chrome',
109
+ }));
110
+ }
111
+ if (token === '--pin-tab')
112
+ continue; // always on
113
+ args.push(token);
114
+ }
115
+ const { command } = findCommand(args);
116
+ // No command at all (`cortex-browser`, `cortex-browser --device x`) shows this help rather than
117
+ // leasing a browser just to print agent-browser's.
118
+ const help = command === null && !args.some((a) => a === '--version' || a === '-V');
119
+ if (command && Object.hasOwn(BLOCKED_COMMANDS, command)) {
120
+ throw new BrowserUsageError(formatError(`'${command}' is not available through cortex-browser`, {
121
+ hint: BLOCKED_COMMANDS[command],
122
+ }));
123
+ }
124
+ if (command === 'close' && args.includes('--all')) {
125
+ throw new BrowserUsageError(formatError("'close --all' would disconnect every other session's browser", {
126
+ hint: "use 'cortex-browser close' to close only this session's connection",
127
+ }));
128
+ }
129
+ return { help, device, args, command };
130
+ }
131
+ /** Does this command run without a browser (help, version, bundled skills)? */
132
+ export function isLocalCommand(parsed) {
133
+ if (parsed.command && LOCAL_COMMANDS.has(parsed.command))
134
+ return true;
135
+ if (parsed.args.some((a) => a === '--help' || a === '-h'))
136
+ return true;
137
+ return parsed.command === null && parsed.args.some((a) => a === '--version' || a === '-V');
138
+ }
139
+ function looksLikePath(token) {
140
+ if (!token || token.startsWith('-') || token.startsWith('@') || token.includes('://'))
141
+ return false;
142
+ if (/[*?{}[\]]/.test(token))
143
+ return false; // a URL pattern (`network route "*.png"`), not a file
144
+ if (path.isAbsolute(token))
145
+ return false;
146
+ return token.startsWith('./') || token.startsWith('../') || FILE_EXTENSIONS.test(token);
147
+ }
148
+ /** Make the file arguments of file-writing commands absolute against the caller's directory. */
149
+ export function absolutizePaths(args, cwd) {
150
+ const out = [...args];
151
+ for (let i = 0; i < out.length - 1; i += 1) {
152
+ if (PATH_FLAGS.has(out[i]) && !path.isAbsolute(out[i + 1]) && !out[i + 1].startsWith('-')) {
153
+ out[i + 1] = path.resolve(cwd, out[i + 1]);
154
+ }
155
+ }
156
+ const { command, index } = findCommand(out);
157
+ if (!command || !Object.hasOwn(FILE_COMMANDS, command))
158
+ return out;
159
+ let skip = FILE_COMMANDS[command];
160
+ for (let i = index + 1; i < out.length; i += 1) {
161
+ const token = out[i];
162
+ if (token.startsWith('-')) {
163
+ if (VALUE_FLAGS.has(token))
164
+ i += 1;
165
+ continue;
166
+ }
167
+ if (skip > 0) {
168
+ skip -= 1;
169
+ continue;
170
+ }
171
+ if (looksLikePath(token))
172
+ out[i] = path.resolve(cwd, token);
173
+ }
174
+ return out;
175
+ }
176
+ async function httpPost(url, body, headers) {
177
+ const response = await fetch(url, {
178
+ method: 'POST',
179
+ headers: { 'content-type': 'application/json', ...headers },
180
+ body: JSON.stringify(body),
181
+ // A device's first Chrome launch can take the device's own 90s budget plus the round trip.
182
+ signal: AbortSignal.timeout(180_000),
183
+ });
184
+ const text = await response.text();
185
+ let parsed = text;
186
+ try {
187
+ parsed = JSON.parse(text);
188
+ }
189
+ catch { /* non-JSON bodies surface as text */ }
190
+ return { status: response.status, body: parsed };
191
+ }
192
+ /** stdout passes straight through; stderr is held so a recoverable tab_gone can be retried
193
+ * without showing the agent an error that was already handled. */
194
+ function spawnExec(bin, args, env, cwd, quiet = false) {
195
+ return new Promise((resolve) => {
196
+ let stderr = '';
197
+ const child = spawn(bin, args, { env, cwd, stdio: [quiet ? 'ignore' : 'inherit', quiet ? 'ignore' : 'inherit', 'pipe'] });
198
+ child.stderr?.on('data', (chunk) => { stderr += String(chunk); });
199
+ child.on('error', (e) => resolve({ code: 127, stderr: `${stderr}cortex-browser: cannot run ${bin}: ${e.message}\n` }));
200
+ child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 128 : 1), stderr }));
201
+ });
202
+ }
203
+ class BrowserCliError extends Error {
204
+ exitCode;
205
+ constructor(message, exitCode = 1) {
206
+ super(message);
207
+ this.exitCode = exitCode;
208
+ }
209
+ }
210
+ async function lease(options, env, sessionId, device) {
211
+ const port = env.WEBHOOK_PORT || '3001';
212
+ const url = `http://127.0.0.1:${port}/webhook/browser`;
213
+ const notice = setTimeout(() => {
214
+ options.writeErr(`cortex-browser: starting the browser${device ? ` on ${device}` : ''}…\n`);
215
+ }, options.slowNoticeMs);
216
+ let response;
217
+ try {
218
+ response = await options.post(url, { action: 'lease', sessionId, device }, { [AUTH_HEADER]: env.CORTEX_WEBHOOK_TOKEN || '' });
219
+ }
220
+ catch (error) {
221
+ throw new BrowserCliError(formatError(`cannot reach the Cortex daemon at 127.0.0.1:${port}: ${error.message}`, {
222
+ hint: 'cortex-browser works inside Cortex sessions while the Cortex server is running',
223
+ }));
224
+ }
225
+ finally {
226
+ clearTimeout(notice);
227
+ }
228
+ if (response.status === 401) {
229
+ throw new BrowserCliError(formatError('the Cortex daemon rejected this call (bad or missing CORTEX_WEBHOOK_TOKEN)', {
230
+ hint: 'run cortex-browser from a Cortex session, which sets the token',
231
+ }));
232
+ }
233
+ if (response.status === 404) {
234
+ throw new BrowserCliError(formatError('this Cortex server has no browser endpoint yet', {
235
+ hint: 'the server needs a restart onto the version that ships cortex-browser',
236
+ }));
237
+ }
238
+ const body = response.body;
239
+ if (response.status !== 200 || !body?.success) {
240
+ const detail = typeof body === 'object' && body ? body.error : String(body ?? '');
241
+ throw new BrowserCliError(formatError(`browser unavailable: ${detail || `HTTP ${response.status}`}`, { hint: body?.hint }));
242
+ }
243
+ return body.data;
244
+ }
245
+ export async function runBrowserCli(argv, options = {}) {
246
+ const env = options.env ?? process.env;
247
+ const cwd = options.cwd ?? process.cwd();
248
+ const writeErr = options.writeErr ?? ((text) => { process.stderr.write(text); });
249
+ const exec = options.exec ?? spawnExec;
250
+ const post = options.post ?? httpPost;
251
+ let parsed;
252
+ try {
253
+ parsed = parseBrowserArgs(argv);
254
+ }
255
+ catch (error) {
256
+ if (error instanceof BrowserUsageError) {
257
+ writeErr(`${error.message}\n`);
258
+ return 2;
259
+ }
260
+ throw error;
261
+ }
262
+ if (parsed.help) {
263
+ process.stdout.write(`${formatHelp(HELP)}\n`);
264
+ return 0;
265
+ }
266
+ try {
267
+ if (isLocalCommand(parsed)) {
268
+ const bin = resolveAgentBrowserBin(env);
269
+ const run = await exec(bin, parsed.args, agentBrowserBaseEnv(env), cwd);
270
+ if (run.stderr)
271
+ writeErr(run.stderr);
272
+ return run.code;
273
+ }
274
+ const sessionId = env.CORTEX_SESSION_ID || env.CORTEX_EXECUTION_ID || '';
275
+ if (!sessionId) {
276
+ writeErr(`${formatError('no Cortex session (CORTEX_SESSION_ID is unset)', {
277
+ hint: 'cortex-browser leases a browser per Cortex session; run it from a session\'s shell',
278
+ })}\n`);
279
+ return 2;
280
+ }
281
+ const data = await lease({ post, writeErr, slowNoticeMs: options.slowNoticeMs ?? 2_000 }, env, sessionId, parsed.device);
282
+ const callEnv = agentBrowserCallEnv(data.env, env);
283
+ const args = absolutizePaths(parsed.args, cwd);
284
+ let run = await exec(data.bin, agentBrowserArgs(data.cdpEndpoint, data.abSession, args), callEnv, cwd);
285
+ if (run.code !== 0 && isTabGone(run.stderr)) {
286
+ // The tab this session was bound to is gone (Chrome was restarted, or someone closed it).
287
+ // The command never ran, so binding a fresh tab and running it once more is safe.
288
+ const rebound = await exec(data.bin, agentBrowserArgs(data.cdpEndpoint, data.abSession, ['tab', 'new']), callEnv, cwd, true);
289
+ if (rebound.code === 0) {
290
+ writeErr('cortex-browser: this session\'s previous tab is gone (closed after 10 idle minutes, or the browser restarted); continuing in a new blank tab\n');
291
+ run = await exec(data.bin, agentBrowserArgs(data.cdpEndpoint, data.abSession, args), callEnv, cwd);
292
+ }
293
+ }
294
+ if (run.stderr)
295
+ writeErr(run.stderr);
296
+ await post(`http://127.0.0.1:${env.WEBHOOK_PORT || '3001'}/webhook/browser`, { action: 'report', sessionId }, { [AUTH_HEADER]: env.CORTEX_WEBHOOK_TOKEN || '' }).catch(() => undefined);
297
+ return run.code;
298
+ }
299
+ catch (error) {
300
+ if (error instanceof BrowserCliError) {
301
+ writeErr(`${error.message}\n`);
302
+ return error.exitCode;
303
+ }
304
+ if (error instanceof AgentBrowserMissingError) {
305
+ writeErr(`${formatError(error.message, { hint: error.hint })}\n`);
306
+ return 1;
307
+ }
308
+ writeErr(`cortex-browser: ${error.message}\n`);
309
+ return 1;
310
+ }
311
+ }
312
+ export async function main(argv = process.argv.slice(2)) {
313
+ process.exitCode = await runBrowserCli(argv);
314
+ }
315
+ if (isMainModule(import.meta.url)) {
316
+ void main();
317
+ }
@@ -2,6 +2,7 @@ export declare function getInitHelp(): string;
2
2
  export declare function getSetupGatewayHelp(): string;
3
3
  export declare function getTuiHelp(): string;
4
4
  export declare function getUiHelp(): string;
5
+ export declare function getPathHelp(): string;
5
6
  export declare function getClientHelp(): string;
6
7
  export declare function getMemoryHelp(): string;
7
8
  export declare function getScheduleHelp(): string;
@@ -71,6 +71,34 @@ export function getUiHelp() {
71
71
  ],
72
72
  });
73
73
  }
74
+ export function getPathHelp() {
75
+ return formatHelp({
76
+ name: 'cortex path',
77
+ description: 'Make this install\'s commands (cortex, cortex-signal, …) available in new terminals',
78
+ usage: 'cortex path <install|remove|status> [--home <path>] [--dry-run] [--json]',
79
+ commands: [
80
+ {
81
+ name: 'install',
82
+ description: 'Write launchers that use this install\'s Node into <home>/runtime/bin and put that '
83
+ + 'directory on PATH (shell profiles on Linux/macOS, the user Path on Windows)',
84
+ },
85
+ { name: 'remove', description: 'Delete the launchers and undo the PATH change' },
86
+ { name: 'status', description: 'Show whether the launchers exist, are current, and are on PATH' },
87
+ ],
88
+ options: [
89
+ { flag: '--home <path>', description: 'CORTEX_HOME the launchers belong to', default: '$CORTEX_HOME or ~/.cortex' },
90
+ { flag: '--dry-run', description: 'Report what install or remove would change and change nothing' },
91
+ { flag: '--json', description: 'Print the result as JSON' },
92
+ { flag: '--help, -h', description: 'Show this help' },
93
+ ],
94
+ examples: [
95
+ { description: 'Add cortex to new terminals', command: 'cortex path install' },
96
+ { description: 'Preview the change', command: 'cortex path install --dry-run --json' },
97
+ { description: 'Check the current state', command: 'cortex path status' },
98
+ { description: 'Undo it', command: 'cortex path remove' },
99
+ ],
100
+ });
101
+ }
74
102
  export function getClientHelp() {
75
103
  return formatHelp({
76
104
  name: 'cortex client',
@@ -181,6 +209,7 @@ function getCliCommands() {
181
209
  { name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + models.json' },
182
210
  { name: 'ui enable', description: 'Enable the local Web UI endpoint the desktop app connects to' },
183
211
  { name: 'client remove', description: 'Unregister a remote machine and uninstall its cortex-client' },
212
+ { name: 'path install', description: 'Make cortex available in new terminals (remove / status to undo or check)' },
184
213
  { name: 'schedule', description: 'List, add, edit, pause, resume and remove scheduled tasks' },
185
214
  { name: 'memory', description: 'Rebuild project memory indexes; report knowledge lifecycle findings' },
186
215
  { name: 'tui', description: 'Start the Terminal UI (TUI) client for local interaction' },
@@ -198,6 +227,7 @@ function getCliExamples() {
198
227
  { description: 'Re-generate gateway config', command: 'cortex setup-gateway' },
199
228
  { description: 'Enable the local Web UI endpoint', command: 'cortex ui enable' },
200
229
  { description: 'Remove a remote machine and its client', command: 'cortex client remove --device trainer' },
230
+ { description: 'Add cortex to new terminals', command: 'cortex path install' },
201
231
  { description: 'List scheduled tasks', command: 'cortex schedule list' },
202
232
  { description: 'Rebuild every project memory index', command: 'cortex memory regen' },
203
233
  { description: 'Start the server', command: 'cortex start' },
package/dist/entry/cli.js CHANGED
@@ -20,6 +20,7 @@ import { runAuthCli } from './auth-cli.js';
20
20
  import { getCliHelp, getInitHelp, getSetupGatewayHelp, getTuiHelp, } from './cli-help.js';
21
21
  import { runUiCli } from './ui-cli.js';
22
22
  import { runClientCli } from './client-cli.js';
23
+ import { runPathCli } from './path-cli.js';
23
24
  import { LoginCliError } from './auth-login-cli.js';
24
25
  import { t } from '../core/i18n.js';
25
26
  // ─── Paths ──────────────────────────────────────────────────────
@@ -448,6 +449,7 @@ const CLI_HANDLERS = {
448
449
  'setup-gateway': (args) => runSetupGatewayCli(args),
449
450
  ui: (args) => runUiCli(args),
450
451
  client: (args) => runClientCli(args),
452
+ path: (args) => runPathCli(args),
451
453
  install: (args) => runInstallCli(args),
452
454
  schedule: async (args) => (await import('./schedule-cli.js')).runScheduleCli(args),
453
455
  memory: async (args) => (await import('./memory-cli.js')).runMemoryCli(args),
@@ -79,6 +79,7 @@ import { isMainModule, moduleDir, withServerNpmPrefix } from '../core/utils.js';
79
79
  import { DATA_DIR, CONFIG_DIR, INSTALL_ROOT, DAEMON_PID_FILE, DAEMON_CHILD_PID_FILE, RESTART_TRIGGER_FILE, } from '../core/paths.js';
80
80
  import { planFastInstall, applyFastInstall } from './fast-install.js';
81
81
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
82
+ import { ensureOwnBinsOnPath } from '../domain/system/own-bin-path.js';
82
83
  import { finishRebuildStep, planRebuildProgress, settleRebuildProgress, startRebuildStep, writeRebuildProgress, } from '../core/rebuild-progress.js';
83
84
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
84
85
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
@@ -884,6 +885,7 @@ function main() {
884
885
  acquireSingletonLock();
885
886
  process.on('exit', releaseSingletonLock);
886
887
  log.info('Cortex Daemon starting...');
888
+ ensureOwnBinsOnPath();
887
889
  setupShutdown();
888
890
  startChild();
889
891
  watchMonitors = setupWatchers();
@@ -0,0 +1,4 @@
1
+ import { type CliResult } from '../core/cli-utils.js';
2
+ import { defaultTerminalCliContext } from '../domain/system/terminal-cli/index.js';
3
+ /** `cortex path install|remove|status` — make this install's commands reachable from terminals. */
4
+ export declare function runPathCli(args: string[], makeContext?: typeof defaultTerminalCliContext): CliResult;
@@ -0,0 +1,65 @@
1
+ import { formatError } from '../core/cli-utils.js';
2
+ import { getResolvedPaths } from './init.js';
3
+ import { getPathHelp } from './cli-help.js';
4
+ import { defaultTerminalCliContext, installTerminalCli, removeTerminalCli, terminalCliStatus, } from '../domain/system/terminal-cli/index.js';
5
+ const SUBCOMMANDS = ['install', 'remove', 'status'];
6
+ function optionValue(args, flag) {
7
+ const index = args.indexOf(flag);
8
+ return index !== -1 && args[index + 1] ? args[index + 1] : undefined;
9
+ }
10
+ const fail = (message) => ({
11
+ exitCode: 1, stdout: '', stderr: formatError(message, { validValues: SUBCOMMANDS, hint: 'cortex path --help' }),
12
+ });
13
+ function targetsLine(report, key, label) {
14
+ const hits = report.path_targets.filter((t) => t[key]).map((t) => t.target);
15
+ return `${label}: ${hits.length ? hits.join(', ') : 'none'}`;
16
+ }
17
+ function installText(report) {
18
+ const lines = [
19
+ `${report.dry_run ? 'Would install' : 'Installed'} terminal commands in ${report.dir}`,
20
+ targetsLine(report, 'changed', report.dry_run ? 'PATH would change in' : 'PATH updated in'),
21
+ 'Open a new terminal to use `cortex`.',
22
+ ];
23
+ if (report.shadowed.length)
24
+ lines.push(`New terminals will use this install instead of: ${report.shadowed.join(', ')}`);
25
+ if (process.env.SHELL?.endsWith('fish'))
26
+ lines.push(`fish is not configured automatically; run: fish_add_path ${report.dir}`);
27
+ return lines;
28
+ }
29
+ function removeText(report) {
30
+ return [
31
+ `${report.dry_run ? 'Would remove' : 'Removed'} ${report.removed.length} command file(s) from ${report.dir}`,
32
+ targetsLine(report, 'changed', report.dry_run ? 'PATH would change in' : 'PATH restored in'),
33
+ ];
34
+ }
35
+ function statusText(report) {
36
+ return [
37
+ `Terminal commands: ${report.installed ? 'installed' : 'not installed'} (${report.dir})`,
38
+ ...(report.stale.length ? [`Out of date: ${report.stale.join(', ')} — rerun cortex path install`] : []),
39
+ targetsLine(report, 'registered', 'On PATH via'),
40
+ ];
41
+ }
42
+ const ACTIONS = {
43
+ install: (ctx, dryRun) => { const report = installTerminalCli(ctx, dryRun); return { report, text: installText(report) }; },
44
+ remove: (ctx, dryRun) => { const report = removeTerminalCli(ctx, dryRun); return { report, text: removeText(report) }; },
45
+ status: (ctx) => { const report = terminalCliStatus(ctx); return { report, text: statusText(report) }; },
46
+ };
47
+ /** `cortex path install|remove|status` — make this install's commands reachable from terminals. */
48
+ export function runPathCli(args, makeContext = defaultTerminalCliContext) {
49
+ if (args.includes('--help') || args.includes('-h'))
50
+ return { exitCode: 0, stdout: getPathHelp(), stderr: '' };
51
+ if (args.length === 0)
52
+ return fail("Missing subcommand for 'path'.");
53
+ const action = ACTIONS[args[0]];
54
+ if (!action)
55
+ return fail(`Unknown subcommand: '${args[0]}'.`);
56
+ try {
57
+ const ctx = makeContext(getResolvedPaths(optionValue(args, '--home')).DATA_DIR);
58
+ const { report, text } = action(ctx, args.includes('--dry-run'));
59
+ const stdout = args.includes('--json') ? `${JSON.stringify(report, null, 2)}\n` : `${text.join('\n')}\n`;
60
+ return { exitCode: 0, stdout, stderr: '' };
61
+ }
62
+ catch (error) {
63
+ return { exitCode: 1, stdout: '', stderr: `cortex path ${args[0]} failed: ${error?.message ?? String(error)}\n` };
64
+ }
65
+ }
@@ -9,11 +9,14 @@ import { stopClientManager } from '../domain/remote/client-manager.js';
9
9
  import { stopMachineRegistryWatcher } from '../domain/remote/machine-registry.js';
10
10
  import { stopAllDevicePorts } from '../domain/remote/device-port.js';
11
11
  import { forgetDeviceBrowsers } from '../domain/remote/device-browser.js';
12
+ import { shutdownBrowserBroker } from '../domain/browser/broker.js';
12
13
  import { stopDiskMonitor } from '../domain/monitor/disk-monitor.js';
13
14
  import { stopEventLoopMonitor } from '../domain/monitor/event-loop-monitor.js';
14
15
  import { stopGateway } from '../domain/costs/gateway-manager.js';
15
16
  import { stopBrowser } from '../platform/browser/managed-browser.js';
16
17
  import { stopWaitpointSweep } from '../orchestration/waitpoint-sweep.js';
18
+ import { stopCacheKeepWarm } from '../orchestration/cache-keep-warm.js';
19
+ import { stopClaudeWindowWarmup } from '../orchestration/claude-window-warmup.js';
17
20
  const log = createLogger('shutdown');
18
21
  function serviceSteps(h) {
19
22
  return [
@@ -26,6 +29,8 @@ function serviceSteps(h) {
26
29
  { name: 'machine watcher', run: stopMachineRegistryWatcher },
27
30
  { name: 'models watcher', run: () => h.stopModelsWatcher?.() },
28
31
  { name: 'board watcher', run: () => h.stopBoardWatcher?.() },
32
+ // Leases first: their timers would otherwise fire against a browser that is already gone.
33
+ { name: 'browser leases', run: shutdownBrowserBroker },
29
34
  // A Chrome that outlives the daemon keeps the profile locked, so the next launch would attach to
30
35
  // an instance nothing is supervising.
31
36
  { name: 'browser', run: stopBrowser },
@@ -45,6 +50,8 @@ function drainSteps(h) {
45
50
  // its store's flush resolved, losing that write.
46
51
  { name: 'scheduler', run: () => h.scheduler.stop() },
47
52
  { name: 'waitpoint sweep', run: stopWaitpointSweep },
53
+ { name: 'cache keep-warm', run: stopCacheKeepWarm },
54
+ { name: 'claude window warm-up', run: stopClaudeWindowWarmup },
48
55
  // Pending WAL entries survive on disk for the next startup.
49
56
  { name: 'outbound drain loop', run: () => h.outboundQueue.stop() },
50
57
  // SIGTERM landing between `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves
@@ -11,6 +11,8 @@ import { isUpdateDevMode } from '../domain/system/server-update-check.js';
11
11
  import { createForwardRoutes } from '../platform/ui-http/port-forward.js';
12
12
  import { createDevicePortRoutes } from '../platform/ui-http/device-ports.js';
13
13
  import { createFileRoutes } from '../platform/ui-http/file-routes.js';
14
+ import { BROWSER_STREAM_PATH, createBrowserStream } from '../platform/ui-http/browser-stream.js';
15
+ import { insertText, isTakenOver, listBrowserSessions, setTakeover, streamPort, } from '../domain/browser/broker.js';
14
16
  import { getOnlineDevices, sendCommand } from '../domain/remote/client-manager.js';
15
17
  import { openDevicePort, closeDevicePort, listDevicePorts } from '../domain/remote/device-port.js';
16
18
  import { accessVerifierFromEnv } from '../platform/ui-http/access-jwt.js';
@@ -99,6 +101,10 @@ export function startUiHttpServer(opts) {
99
101
  : undefined;
100
102
  const verifySession = sessionStore ? (sid) => sessionStore.verify(sid) : undefined;
101
103
  const authorize = createAuthorizer({ getToken, verifySession, verifyAccessJwt });
104
+ // The agent's browser, live in the app: session list, takeover, typed text, and the stream itself.
105
+ const browserStream = createBrowserStream({
106
+ listSessions: listBrowserSessions, streamPort, setTakeover, isTakenOver, insertText,
107
+ });
102
108
  log.info(`Web UI enabled — starting tRPC HTTP+SSE on 127.0.0.1:${port}` +
103
109
  (spaDir ? ` (SPA: ${spaDir})` : ' (SPA: not built — non-tRPC paths 404)') +
104
110
  (initialCorsOrigins.length > 0 ? ` (CORS allow-list: ${initialCorsOrigins.join(', ')})` : '') +
@@ -152,7 +158,9 @@ export function startUiHttpServer(opts) {
152
158
  closeDevicePort,
153
159
  listDevicePorts,
154
160
  }),
161
+ ...browserStream.routes,
155
162
  },
163
+ upgradeRoutes: { [BROWSER_STREAM_PATH]: browserStream },
156
164
  portForward: env.CORTEX_PORT_FORWARD !== '0',
157
165
  });
158
166
  }