@cortex-agent/server 2026.10.15 → 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.
- package/README.md +76 -50
- package/defaults/board/board.css +140 -62
- package/defaults/board/scaffold.html +36 -13
- package/defaults/config/environments/creative.json +0 -1
- package/defaults/config/environments/main.json +1 -2
- package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
- package/defaults/plugins/cortex-system/plugin.json +2 -2
- package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
- package/dist/agent-adapter/claude/adapter.d.ts +2 -5
- package/dist/agent-adapter/claude/adapter.js +6 -5
- package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
- package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
- package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
- package/dist/agent-adapter/claude/cache-refresh.js +145 -0
- package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
- package/dist/agent-adapter/claude/cache-touch.js +75 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
- package/dist/agent-adapter/claude/event-parser.js +33 -17
- package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
- package/dist/agent-adapter/claude/event-translator.js +2 -0
- package/dist/agent-adapter/claude/session-options.d.ts +6 -13
- package/dist/agent-adapter/claude/session-options.js +2 -13
- package/dist/agent-adapter/claude/spawn-args.d.ts +4 -21
- package/dist/agent-adapter/claude/spawn-args.js +17 -24
- package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
- package/dist/agent-adapter/claude/transcript-clear.js +217 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
- package/dist/agent-adapter/claude/turn-machine.js +21 -68
- package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
- package/dist/agent-adapter/claude/window-warmup.js +38 -0
- package/dist/agent-adapter/continuation-phase.js +3 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
- package/dist/agent-adapter/pi/adapter.d.ts +0 -1
- package/dist/agent-adapter/pi/adapter.js +5 -13
- package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
- package/dist/agent-adapter/pi/event-parser.js +43 -27
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
- package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
- package/dist/agent-adapter/pi/pi-session.js +15 -0
- package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
- package/dist/agent-adapter/pi/providers-config.js +1 -1
- package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
- package/dist/agent-adapter/pi/quota-sink.js +3 -3
- package/dist/agent-adapter/pi/runtime.js +6 -1
- package/dist/agent-adapter/pi/session-options.d.ts +9 -13
- package/dist/agent-adapter/pi/session-options.js +12 -25
- package/dist/agent-adapter/run-events.d.ts +11 -10
- package/dist/agent-adapter/run-events.js +2 -0
- package/dist/agent-adapter/types.d.ts +5 -4
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/codex-quota.d.ts +1 -1
- package/dist/core/codex-quota.js +1 -1
- package/dist/core/gateway-generator.d.ts +9 -11
- package/dist/core/gateway-generator.js +31 -58
- package/dist/core/locales/en.d.ts +51 -77
- package/dist/core/locales/slices/commands.d.ts +26 -31
- package/dist/core/locales/slices/commands.js +54 -64
- package/dist/core/locales/slices/init.d.ts +8 -19
- package/dist/core/locales/slices/init.js +17 -53
- package/dist/core/locales/slices/interactions.d.ts +3 -3
- package/dist/core/locales/slices/interactions.js +6 -6
- package/dist/core/locales/slices/notices.d.ts +1 -3
- package/dist/core/locales/slices/notices.js +2 -6
- package/dist/core/locales/slices/scheduling.d.ts +9 -9
- package/dist/core/locales/slices/scheduling.js +18 -18
- package/dist/core/locales/slices/status.d.ts +0 -4
- package/dist/core/locales/slices/status.js +0 -8
- package/dist/core/locales/slices/tui.d.ts +0 -1
- package/dist/core/locales/slices/tui.js +0 -2
- package/dist/core/locales/slices/uimsg.d.ts +4 -7
- package/dist/core/locales/slices/uimsg.js +9 -15
- package/dist/core/models-generator.d.ts +29 -0
- package/dist/core/models-generator.js +82 -0
- package/dist/core/paths.d.ts +1 -1
- package/dist/core/paths.js +1 -1
- package/dist/core/settings-spec.d.ts +25 -0
- package/dist/core/settings-spec.js +34 -0
- package/dist/core/status-format.d.ts +3 -2
- package/dist/core/status-format.js +2 -2
- package/dist/core/types/environment-types.d.ts +0 -2
- package/dist/domain/agents/agent-state.d.ts +11 -56
- package/dist/domain/agents/agent-state.js +48 -115
- package/dist/domain/agents/agent-switch.d.ts +2 -24
- package/dist/domain/agents/agent-switch.js +9 -72
- package/dist/domain/agents/config.d.ts +11 -61
- package/dist/domain/agents/config.js +47 -154
- package/dist/domain/agents/engine-selection.d.ts +21 -0
- package/dist/domain/agents/engine-selection.js +37 -0
- package/dist/domain/agents/environments/registry.js +2 -1
- package/dist/domain/agents/environments/resolve.js +0 -1
- package/dist/domain/agents/environments/schema.d.ts +0 -1
- package/dist/domain/agents/environments/schema.js +0 -1
- package/dist/domain/agents/index.d.ts +2 -1
- package/dist/domain/agents/index.js +3 -7
- package/dist/domain/agents/model-selection.d.ts +18 -70
- package/dist/domain/agents/model-selection.js +100 -150
- package/dist/domain/agents/models.d.ts +12 -0
- package/dist/domain/agents/models.js +94 -0
- package/dist/domain/agents/subagent/registry.d.ts +2 -0
- package/dist/domain/agents/subagent/registry.js +8 -0
- package/dist/domain/agents/subagent/runner.d.ts +5 -5
- package/dist/domain/agents/subagent/runner.js +12 -35
- package/dist/domain/auth/auth-status.d.ts +4 -4
- package/dist/domain/auth/auth-status.js +17 -28
- package/dist/domain/auth/gateway-sync.d.ts +6 -26
- package/dist/domain/auth/gateway-sync.js +31 -75
- package/dist/domain/benchmark/identity.d.ts +3 -5
- package/dist/domain/benchmark/identity.js +0 -1
- package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
- package/dist/domain/benchmark/production-attempt-identity.js +32 -35
- package/dist/domain/benchmark/session-evidence.d.ts +2 -1
- package/dist/domain/benchmark/session-evidence.js +8 -1
- package/dist/domain/browser/broker.d.ts +99 -0
- package/dist/domain/browser/broker.js +487 -0
- package/dist/domain/costs/claude-account.js +21 -0
- package/dist/domain/costs/rate-limit-throttle.js +3 -1
- package/dist/domain/costs/reset-account.d.ts +2 -0
- package/dist/domain/costs/usage-service.d.ts +1 -1
- package/dist/domain/costs/usage-service.js +20 -7
- package/dist/domain/mcp/tools/context.d.ts +5 -6
- package/dist/domain/mcp/tools/context.js +17 -3
- package/dist/domain/mcp/tools/subagent.js +1 -1
- package/dist/domain/mcp/tools/ui-file.js +1 -1
- package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
- package/dist/domain/pi-providers/custom-provider-model.js +1 -1
- package/dist/domain/remote/device-browser.js +1 -1
- package/dist/domain/remote/device-chrome-commands.js +2 -0
- package/dist/domain/remote/device-port.js +2 -2
- package/dist/domain/runs/attempt.d.ts +3 -3
- package/dist/domain/runs/attempt.js +2 -3
- package/dist/domain/runs/builders.d.ts +4 -4
- package/dist/domain/runs/builders.js +4 -5
- package/dist/domain/runs/compact.d.ts +4 -17
- package/dist/domain/runs/compact.js +14 -56
- package/dist/domain/runs/config-resolver.d.ts +15 -83
- package/dist/domain/runs/config-resolver.js +24 -150
- package/dist/domain/runs/engine-spec.d.ts +8 -8
- package/dist/domain/runs/engine-spec.js +15 -31
- package/dist/domain/runs/events.d.ts +1 -1
- package/dist/domain/runs/fallback.d.ts +6 -38
- package/dist/domain/runs/fallback.js +10 -72
- package/dist/domain/runs/notices.d.ts +1 -11
- package/dist/domain/runs/notices.js +3 -30
- package/dist/domain/runs/request.d.ts +4 -3
- package/dist/domain/runs/retryable-errors.d.ts +0 -13
- package/dist/domain/runs/retryable-errors.js +0 -17
- package/dist/domain/runs/run.d.ts +12 -42
- package/dist/domain/runs/run.js +40 -147
- package/dist/domain/runs/service.d.ts +1 -1
- package/dist/domain/runs/service.js +8 -3
- package/dist/domain/runs/spec-loader.d.ts +1 -1
- package/dist/domain/runs/spend.d.ts +1 -1
- package/dist/domain/runs/spend.js +1 -1
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +25 -19
- package/dist/domain/scheduling/schedule-ops.d.ts +0 -1
- package/dist/domain/scheduling/schedule-ops.js +2 -5
- package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
- package/dist/domain/scheduling/schedule-selection.js +16 -0
- package/dist/domain/scheduling/schedule-spec.d.ts +6 -5
- package/dist/domain/scheduling/schedule-spec.js +6 -6
- package/dist/domain/scheduling/scheduler.d.ts +3 -1
- package/dist/domain/scheduling/scheduler.js +22 -21
- package/dist/domain/sessions/session-hooks.d.ts +5 -4
- package/dist/domain/sessions/session-hooks.js +15 -33
- package/dist/domain/sessions/session-lifecycle.d.ts +19 -51
- package/dist/domain/sessions/session-lifecycle.js +34 -96
- package/dist/domain/system/doctor.d.ts +3 -3
- package/dist/domain/system/doctor.js +22 -26
- package/dist/domain/system/own-bin-path.d.ts +13 -0
- package/dist/domain/system/own-bin-path.js +36 -0
- package/dist/domain/system/terminal-cli/index.d.ts +58 -0
- package/dist/domain/system/terminal-cli/index.js +100 -0
- package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
- package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
- package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
- package/dist/domain/system/terminal-cli/registrar.js +1 -0
- package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
- package/dist/domain/system/terminal-cli/shims.js +108 -0
- package/dist/domain/system/terminal-cli/state.d.ts +7 -0
- package/dist/domain/system/terminal-cli/state.js +36 -0
- package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
- package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
- package/dist/domain/tui-session/tui-session-service.js +1 -1
- package/dist/domain/tui-session/types.d.ts +2 -2
- package/dist/domain/ui-service/app-router.d.ts +49 -71
- package/dist/domain/ui-service/app-router.js +9 -13
- package/dist/domain/ui-service/assistant-snapshots.js +2 -0
- package/dist/domain/ui-service/contract.parity.d.ts +19 -0
- package/dist/domain/ui-service/contract.parity.js +1 -0
- package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
- package/dist/domain/ui-service/inline-media-types.js +1 -0
- package/dist/domain/ui-service/input-schemas.d.ts +52 -115
- package/dist/domain/ui-service/input-schemas.js +38 -84
- package/dist/domain/ui-service/mutate/auth.d.ts +1 -1
- package/dist/domain/ui-service/mutate/auth.js +3 -2
- package/dist/domain/ui-service/mutate/config.d.ts +0 -8
- package/dist/domain/ui-service/mutate/config.js +0 -22
- package/dist/domain/ui-service/mutate/models.d.ts +13 -0
- package/dist/domain/ui-service/mutate/models.js +137 -0
- package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
- package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
- package/dist/domain/ui-service/mutate/sessions.d.ts +2 -2
- package/dist/domain/ui-service/mutate/sessions.js +29 -126
- package/dist/domain/ui-service/query/config.js +22 -42
- package/dist/domain/ui-service/query/models.js +2 -2
- package/dist/domain/ui-service/query/schedules.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -13
- package/dist/domain/ui-service/types.d.ts +51 -177
- package/dist/domain/ui-service/ui-service.d.ts +23 -49
- package/dist/domain/ui-service/ui-service.js +8 -6
- package/dist/entry/app.js +42 -19
- package/dist/entry/browser-cli.d.ts +39 -0
- package/dist/entry/browser-cli.js +317 -0
- package/dist/entry/cli-help.d.ts +1 -0
- package/dist/entry/cli-help.js +37 -6
- package/dist/entry/cli.js +16 -14
- package/dist/entry/daemon.js +2 -0
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.d.ts +7 -8
- package/dist/entry/init.js +89 -249
- package/dist/entry/path-cli.d.ts +4 -0
- package/dist/entry/path-cli.js +65 -0
- package/dist/entry/schedule-cli.js +13 -6
- package/dist/entry/shutdown.d.ts +1 -1
- package/dist/entry/shutdown.js +8 -1
- package/dist/entry/start-ui-http.js +8 -0
- package/dist/entry/ui-service-wiring.js +8 -10
- package/dist/events/event-types.d.ts +3 -2
- package/dist/orchestration/agent-runner.d.ts +2 -2
- package/dist/orchestration/agent-runner.js +10 -9
- package/dist/orchestration/benchmark-session-webhook.js +13 -1
- package/dist/orchestration/browser-webhook.d.ts +11 -0
- package/dist/orchestration/browser-webhook.js +28 -0
- package/dist/orchestration/cache-keep-warm.d.ts +77 -0
- package/dist/orchestration/cache-keep-warm.js +213 -0
- package/dist/orchestration/claude-window-warmup.d.ts +40 -0
- package/dist/orchestration/claude-window-warmup.js +126 -0
- package/dist/orchestration/conversation-request.d.ts +6 -10
- package/dist/orchestration/conversation-request.js +5 -23
- package/dist/orchestration/delta-coalescer.d.ts +4 -2
- package/dist/orchestration/delta-coalescer.js +5 -5
- package/dist/orchestration/edit-retry.js +9 -11
- package/dist/orchestration/inline-media-eager.d.ts +13 -0
- package/dist/orchestration/inline-media-eager.js +58 -0
- package/dist/orchestration/inline-media.d.ts +22 -0
- package/dist/orchestration/inline-media.js +151 -0
- package/dist/orchestration/interactions/ask-user-resume.js +3 -7
- package/dist/orchestration/interactions/interaction-handlers.js +6 -6
- package/dist/orchestration/mid-turn-inject.d.ts +2 -1
- package/dist/orchestration/mid-turn-inject.js +1 -1
- package/dist/orchestration/pending-injection-recovery.d.ts +2 -1
- package/dist/orchestration/pending-injection-recovery.js +1 -1
- package/dist/orchestration/routing/commands/index.js +4 -4
- package/dist/orchestration/routing/commands/mode.d.ts +5 -44
- package/dist/orchestration/routing/commands/mode.js +98 -272
- package/dist/orchestration/routing/commands/schedule.js +29 -18
- package/dist/orchestration/routing/commands/session.js +9 -9
- package/dist/orchestration/routing/commands/status.js +1 -1
- package/dist/orchestration/routing/commands/usage-format.js +3 -0
- package/dist/orchestration/routing/webhook.js +4 -0
- package/dist/orchestration/session-compact.d.ts +0 -1
- package/dist/orchestration/session-compact.js +5 -7
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/status-helpers.d.ts +0 -4
- package/dist/orchestration/status-helpers.js +0 -18
- package/dist/orchestration/subagent-webhook.js +9 -34
- package/dist/orchestration/team-webhook.d.ts +8 -9
- package/dist/orchestration/team-webhook.js +16 -42
- package/dist/orchestration/transcript-sink.d.ts +6 -0
- package/dist/orchestration/transcript-sink.js +21 -2
- package/dist/orchestration/turn/terminal.js +7 -7
- package/dist/orchestration/turn/turn-prep.d.ts +0 -8
- package/dist/orchestration/turn/turn-prep.js +0 -51
- package/dist/orchestration/turn/turn-tracking.d.ts +2 -2
- package/dist/orchestration/turn/turn-tracking.js +8 -5
- package/dist/orchestration/turn/turn.d.ts +0 -2
- package/dist/orchestration/turn/turn.js +13 -15
- package/dist/platform/adapters/tui/ports.d.ts +1 -1
- package/dist/platform/adapters/tui/tui-transcript.js +2 -0
- package/dist/platform/browser/agent-browser.d.ts +50 -0
- package/dist/platform/browser/agent-browser.js +165 -0
- package/dist/platform/browser/managed-browser.d.ts +1 -11
- package/dist/platform/browser/managed-browser.js +4 -12
- package/dist/platform/ui-http/browser-stream.d.ts +110 -0
- package/dist/platform/ui-http/browser-stream.js +447 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
- package/dist/platform/ui-http/ui-http-server.js +23 -6
- package/dist/store/conversation-history-reader.js +8 -0
- package/dist/store/conversation-history-repo.d.ts +8 -1
- package/dist/store/conversation-history-repo.js +5 -0
- package/dist/store/conversation-ledger-repo.d.ts +6 -6
- package/dist/store/conversation-ledger-repo.js +4 -4
- package/dist/store/models-repo.d.ts +18 -0
- package/dist/store/models-repo.js +74 -0
- package/dist/store/pending-injection-repo.d.ts +2 -1
- package/dist/store/pending-injection-repo.js +3 -1
- package/dist/store/retire-profiles-migration.d.ts +28 -0
- package/dist/store/retire-profiles-migration.js +335 -0
- package/dist/store/schedule-repo.d.ts +2 -1
- package/dist/store/session-registry-import.js +3 -2
- package/dist/store/session-registry-journal.d.ts +10 -13
- package/dist/store/session-registry-journal.js +48 -25
- package/dist/store/session-registry-repo.d.ts +4 -4
- package/dist/store/session-registry-repo.js +4 -5
- package/dist/store/version-migrations.d.ts +2 -3
- package/dist/store/version-migrations.js +19 -3
- package/dist/tui/slash-commands.js +2 -2
- package/dist/tui/turn-status.js +1 -1
- package/package.json +6 -4
- package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
- package/web/dist/assets/index-CaSZPg_H.css +1 -0
- package/web/dist/assets/index-CzOR7Edh.js +522 -0
- package/web/dist/assets/{index-CndZZ1IQ.js → index-cIGFv27z.js} +1 -1
- package/web/dist/index.html +3 -2
- package/web/dist/theme.css +6 -0
- package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
- package/dist/agent-adapter/browser-mcp-server.js +0 -28
- package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
- package/dist/agent-adapter/claude/browser-mcp.js +0 -10
- package/dist/core/profile-generator.d.ts +0 -79
- package/dist/core/profile-generator.js +0 -215
- package/dist/domain/agents/profile-manager.d.ts +0 -103
- package/dist/domain/agents/profile-manager.js +0 -286
- package/dist/domain/agents/profile-switch.d.ts +0 -49
- package/dist/domain/agents/profile-switch.js +0 -62
- package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
- package/dist/domain/ui-service/mutate/profiles.js +0 -151
- package/dist/store/profile-repo.d.ts +0 -20
- package/dist/store/profile-repo.js +0 -97
- package/web/dist/assets/index-B76ueW3q.js +0 -494
- package/web/dist/assets/index-C8O0yxg8.css +0 -1
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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
|
-
|
|
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,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type SessionRegistryRepo } from './session-registry-repo.js';
|
|
2
|
+
import type { EngineSelection } from '../domain/agents/engine-selection.js';
|
|
2
3
|
import type { TurnRecord, TurnStatus } from './session-registry-journal.js';
|
|
3
4
|
export type { TurnStatus };
|
|
4
5
|
/** The ledger's turn IS the registry's turn record — one definition, no drift. */
|
|
@@ -6,9 +7,8 @@ export type LedgerTurn = TurnRecord;
|
|
|
6
7
|
export interface ChannelConversation {
|
|
7
8
|
sessionId: string | null;
|
|
8
9
|
backend: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
profileName: string | null;
|
|
10
|
+
/** Materialized engine choice retained across resume and hook turns. */
|
|
11
|
+
selection: EngineSelection | null;
|
|
12
12
|
turns: LedgerTurn[];
|
|
13
13
|
updatedAt: string;
|
|
14
14
|
}
|
|
@@ -25,7 +25,7 @@ export declare class ConversationLedgerRepo {
|
|
|
25
25
|
initConversation(channel: string, opts: {
|
|
26
26
|
sessionId: string | null;
|
|
27
27
|
backend: string;
|
|
28
|
-
|
|
28
|
+
selection?: EngineSelection | null;
|
|
29
29
|
}): Promise<ChannelConversation>;
|
|
30
30
|
updateSessionId(channel: string, sessionId: string): Promise<void>;
|
|
31
31
|
beginTurn(channel: string, opts: {
|
|
@@ -50,7 +50,7 @@ export declare class ConversationLedgerRepo {
|
|
|
50
50
|
switchSession(channel: string, opts: {
|
|
51
51
|
sessionId: string;
|
|
52
52
|
backend: string;
|
|
53
|
-
|
|
53
|
+
selection?: EngineSelection | null;
|
|
54
54
|
}): Promise<void>;
|
|
55
55
|
/**
|
|
56
56
|
* Atomic init-if-missing + beginTurn. Captures the turn index under one lock
|
|
@@ -60,7 +60,7 @@ export declare class ConversationLedgerRepo {
|
|
|
60
60
|
initAndBeginTurn(channel: string, opts: {
|
|
61
61
|
sessionId: string | null;
|
|
62
62
|
backend: string;
|
|
63
|
-
|
|
63
|
+
selection?: EngineSelection | null;
|
|
64
64
|
userMessageTs: string;
|
|
65
65
|
userMessageText: string;
|
|
66
66
|
statusMessageTs: string;
|
|
@@ -21,7 +21,7 @@ function toChannelConversation(header, turns) {
|
|
|
21
21
|
return {
|
|
22
22
|
sessionId: header.sessionId,
|
|
23
23
|
backend: header.backend,
|
|
24
|
-
|
|
24
|
+
selection: header.selection,
|
|
25
25
|
turns,
|
|
26
26
|
updatedAt: deriveUpdatedAt(header, turns),
|
|
27
27
|
};
|
|
@@ -56,7 +56,7 @@ export class ConversationLedgerRepo {
|
|
|
56
56
|
const header = {
|
|
57
57
|
sessionId: opts.sessionId,
|
|
58
58
|
backend: opts.backend,
|
|
59
|
-
|
|
59
|
+
selection: opts.selection ?? null,
|
|
60
60
|
updatedAt: now,
|
|
61
61
|
};
|
|
62
62
|
await this.registry.batch(async (ops) => {
|
|
@@ -161,7 +161,7 @@ export class ConversationLedgerRepo {
|
|
|
161
161
|
const header = {
|
|
162
162
|
sessionId: opts.sessionId,
|
|
163
163
|
backend: opts.backend,
|
|
164
|
-
|
|
164
|
+
selection: opts.selection ?? null,
|
|
165
165
|
updatedAt: nowIso(),
|
|
166
166
|
};
|
|
167
167
|
await this.registry.batch(async (ops) => {
|
|
@@ -180,7 +180,7 @@ export class ConversationLedgerRepo {
|
|
|
180
180
|
await ops.setConversation(channel, {
|
|
181
181
|
sessionId: opts.sessionId,
|
|
182
182
|
backend: opts.backend,
|
|
183
|
-
|
|
183
|
+
selection: opts.selection ?? null,
|
|
184
184
|
updatedAt: nowIso(),
|
|
185
185
|
});
|
|
186
186
|
}
|