Files
openchamber/packages/web/server/index.js
T
Bohdan Triapitsyn 61a4a23add feat: native iOS & Android mobile apps (Capacitor) (#1954)
* feat(mobile): add Capacitor native shell

* docs: add serve-sim workflow guidance

* docs(mobile): add implementation handoff

* chore(mobile): clean up generated defaults

* feat(mobile): add connection onboarding

* feat(mobile): manage saved instances

* feat(mobile): refine connection management UI

* chore(mobile): upgrade Capacitor 8

* fix(mobile): reliable saved-instance auth with secure token storage

- store client tokens in the OS secure store (iOS Keychain / Android Keystore)
  per instance URL via direct native plugin calls; keep only token-less metadata
  in localStorage. Bound every secure call so a stalled bridge can't hang unlock.
- bypass the secure-storage JS wrapper's lazy platform load (which stalled in the
  webview) by calling internalSetItem/internalGetItem/internalRemoveItem directly.
- harden the shared connect/unlock controller (health + session + progressive
  password) and drop the heavy pre-connect hydration that stalled no-token hosts.
- await token persistence before switching runtime endpoints (no fire-and-forget).
- sync native iOS/Android projects + Keyboard/StatusBar config for Capacitor 8.

* fix(mobile): keep UI stable across connection churn (no transport hardcoding)

The "reload every ~10s" was a UX bug, not a transport one:
- MobileSurfaceShell received a fresh inline onClose each parent render, so any
  re-render (e.g. an SSE/WS event) re-ran the focus effect and refocused the first
  element — stealing focus from the active input and collapsing the keyboard
  mid-edit. onClose now lives in a ref so the focus/keydown effect depends only on
  `open`. Fixes all sheets (Instances/Files/Changes/Settings).
- Gate the mobile shell on connectionPhase, not the live isConnected flag, so a
  transient reconnect keeps MobileShell mounted instead of flashing the loader.
- Instances form: populate fields imperatively on edit/cancel/save instead of via
  an effect keyed on the derived connection, so list churn can't wipe input.

Transport stays on `auto` (WS-first with SSE fallback) — no hardcoded override, so
WS-only Quick Tunnels and SSE-capable proxies both keep working.

* feat(mobile): add native QR pairing-code scanner

Wire the connection onboarding + Instances scan buttons to a real native
scanner via @capacitor-mlkit/barcode-scanning, which registers as the
BarcodeScanner plugin the existing mobileQrScan helper already resolves at
runtime. Add NSCameraUsageDescription and bump the iOS deployment target to
15.5 (GoogleMLKit 8 requirement).

* fix(cli): repair connect-url host resolution

Define the missing isWildcardBindHost helper that connect-url called but was
never declared, which crashed any link generation that reached host
resolution. Also treat a full http(s) --host value as a public server URL so
'--host https://example.com' produces a correct link instead of
'http://https://example.com:port'.

* fix(mobile): make input follow the keyboard across all surfaces

Switch the native Capacitor Keyboard plugin to resize: 'none' and drive the
layout from an --oc-keyboard-inset CSS variable set on keyboardWillShow, which
fires at the start of the iOS keyboard animation. A transition tuned to the
native keyboard curve/duration (0.25s, cubic-bezier(0.38, 0.7, 0.125, 1)) makes
the layout rise together with the keyboard instead of snapping into place after
the built-in 'native' resize finished (~1.5s lag).

The inset is consumed by every surface that can hold a focused input:
- chat shell shrinks its height;
- portal sheets/overlays raise their bottom edge;
- the full-screen connect/login view caps its height so it actually scrolls
  (and is now generally scrollable for long saved-connection lists).

* feat(mobile): rounder chat composer + native bottom safe area

Round the mobile chat composer corners a touch more (1rem), and reserve a small
app-level bottom safe area for the native shell via the --oc-app-bottom-safe
token so controls clear the phone's rounded hardware corners. The reservation
folds into the keyboard inset (no gap above the keyboard), and the composer's
own bottom padding tightens while the keyboard is open.

* fix(mobile): remove iOS 26 dark status-bar band; polish composer

The dark band behind the status bar in system Dark Mode was iOS 26's automatic
scroll edge effect (Liquid Glass) dimming the WebView's top edge beneath the
status bar — appearance-coloured, so it tracked the system theme regardless of
the in-app theme. Hide it via UIScrollView.topEdgeEffect/bottomEdgeEffect on the
WebView's scroll view (iOS 26+), and make the WebView non-opaque so the themed
web background shows under the overlaid status bar.

Also: re-assert the status-bar overlay on resume, paint the document canvas with
the theme background in the native shell, round the composer corners to 1.5rem,
and enlarge the app-level bottom safe area so controls clear the rounded corners.

* feat(mobile): logo splash until first paint is final (no FOUT / layout shift)

Cold start flashed the fallback font and then reflowed once the real font and
persisted appearance prefs landed, and text jumped a frame after mount because the
mobile typography classes were applied from a hook effect. Fix it on three fronts:

- apply device classes (device-mobile / mobile-pointer) synchronously in
  renderMobileApp before the first React paint, so mobile --text-* sizes are in
  effect from the start;
- hold a logo splash (useFontsReady) until the UI web font has loaded;
- gate that splash on appBootReady too, resolved once async appearance/typography
  preferences are applied, plus a double rAF so styles commit before reveal.

All under a 2.5s safety timeout so a slow/offline CDN can't block startup.

* feat(mobile): native local notifications; APNs implemented but frozen

The native app now delivers agent ready/error/question/permission events as iOS
(and Android) Local Notifications: a native notifications API backed by
@capacitor/local-notifications replaces the Web Notifications API (which doesn't
display in a WKWebView), driven by the notification SSE stream now subscribed in
the mobile app. Tapping a notification opens its session. Also fix the settings
toggle, which treated the Capacitor app as a browser and gated 'Enable
Notifications' on the absent Web Notification permission, leaving it un-toggleable.

Remote APNs push is implemented end-to-end (dependency-free HTTP/2 + ES256 JWT
server runtime, token routes, client registration, iOS native config) but kept
dormant: config-gated so it never fires, client registration not wired, and the
aps-environment entitlement / background mode removed so the app builds with no
Apple push setup. It will be reused once OpenChamber ships its own encrypted
relay so users don't each configure APNs. See notifications/APNS.md.

WKWebView can't use web push (unlike an installed PWA), so true
background-when-suspended delivery on native requires APNs via that relay.

* feat(mobile): APNs relay-mode background push

Deliver native iOS background push through the central relay: the server posts
device tokens + generic, model-based text to api.openchamber.dev/v1/push/send
(default), which holds the single APNs key and signs+sends; dead tokens (410)
are dropped from the per-session store. Direct APNs (HTTP/2 + ES256 JWT) stays
as a fallback when OPENCHAMBER_PUSH_RELAY_DISABLED=true. The mobile push payload
is generic only (model + scenario) so no session content crosses the relay.

Re-enable the client token registration (useNativePushRegistration) and the
aps-environment entitlement (alert pushes need no background mode). Wired into
the same fanout as web push; focus-suppressed and only when tokens exist.

* fix(mobile): APNs-only native notifications, generic templates, no foreground

Make APNs the single notification channel for the native app and fix delivery:

- Remove local notifications entirely (the @capacitor/local-notifications plugin
  and the SSE-driven path). A WKWebView can't tell foreground from background
  (document.hasFocus() is unreliable), so local notifications leaked while the app
  was open; the in-app dispatch is no-op'd on native.
- Stop gating APNs on UI visibility — a backgrounded WebView can't report 'hidden'
  before iOS suspends it, which dropped background push. Instead always send and let
  iOS suppress the foreground banner (PushNotifications presentationOptions: []).
- Fix a ReferenceError (out-of-scope 'variables') that crashed maybeSendPushForTrigger
  before any push was sent.
- Mobile push text is generic: a scenario title ('Agent response is ready' / 'needs
  your input' / 'needs permission' / 'hit an error') + the session name, no model or
  message content.
- Hide the focus toggle, templates, and test button in mobile notification settings.

* feat(push): sign relay requests + bind tokens per server

Each OpenChamber server now auto-generates an ECDSA P-256 keypair (persisted in settings,
like the VAPID keys) and uses it to:
- bind every newly-seen device token to the server on the relay
  (POST /v1/push/register-token, signed), and
- sign every push send (publicKeyJwk + ts + signature over ts.sortedTokens.title).

The relay derives serverId = SHA-256(publicKey), verifies the signature + timestamp, and
only delivers to tokens bound to that server. Result: a leaked device token alone can no
longer be used to push to a device — the sender also needs the server's private key. Stays
zero-config (the keypair generates on first use). Drops the soft PUSH_RELAY_TOKEN bearer.

* docs(push): describe relay data-confidentiality model

Document that the push payload is not application-encrypted (TLS-in-transit only), what the
relay and Apple can see (generic scenario title + session name, plus token/sessionId), that
the signature is authentication rather than encryption, and what an end-to-end encrypted
payload would require.

* fix: invalid skill description

* feat(push): app-icon badge for native notifications

Send an absolute aps.badge with each native push = the count of distinct
collapse-ids (tag) pushed since the app was last foregrounded, mirroring the
lock-screen banner stack. Cleared server-side on user engagement (session view,
message-sent, visibility beacon) and on-device via sceneDidBecomeActive.

* feat(mobile): auto-connect last instance on launch + notification deep-links

Cold launch silently reconnects to the most-recent saved instance (when reachable
and a token is saved), holding the splash instead of flashing the connect screen;
falls back to the connect screen when there's no saved instance, it's unreachable,
or it needs a re-login. Notification-tap deep-links are now captured unconditionally
(even before connect / on cold launch) and applied once the app is ready, so a tap
opens the target session instead of being lost on the login screen.

* fix(mobile): resolve theme background before first paint on cold launch

The mobile shell entry (mobile.html) had no pre-paint theme step, so a cold
launch flashed the WebView's default light canvas, then the baked
design-system default (.dark { --background: #151313 }) via body.bg-background,
before React's theme system injected the real theme vars. Add a blocking script
that resolves dark/light from the persisted theme + system preference and sets
--background (plus color-scheme and the element background) inline on the root,
so the very first paint matches the resolved theme. Falls back to the default
flexoki backgrounds when no theme has been persisted yet.

* feat(mobile): openchamber:// deep-link foundation + arm64 simulator build

Add a typed deep-link vocabulary (deepLinks.ts: parse/build + DeepLinkIntent)
and a single native navigation layer (deepLinkNavigation.ts) that handles both
the openchamber:// URL scheme (App.appUrlOpen — widgets, Live Activities,
external links) and notification taps, normalising each into an intent. Session
and new-session resolve against the store; shell surfaces (sessions/settings/
views/changes) register handlers. Cold-launch intents stash until the app is
ready. Replaces the push-only useNativePushDeepLink and keeps backwards
compatibility with bare sessionId payloads.

Register the openchamber:// scheme in Info.plist.

Dev tooling: with-mobile-env now honours xcode-select (-p) instead of hardcoding
Xcode.app, so an Xcode beta is used. build:ios:simulator runs a new
ios-sim-build script that temporarily drops the MLKit barcode-scanning pod
(no arm64-simulator slice) so the app builds an arm64 binary installable on
Apple Silicon simulators, then restores the Podfile + Pods for device builds.
QR scanning already degrades cleanly when the native plugin is absent.

* feat(mobile): iOS home/lock/Control Center widgets + push-driven refresh

Add a Widget Extension (OpenChamberWidget) and a Notification Service Extension
(OpenChamberNotificationService), wired into the Xcode project, sharing an App
Group with the app.

Widgets:
- Overview (medium): recent sessions with read/unread dots + four quick actions
  (new, status, instances, settings).
- Sessions (large): session list with per-session project label, attention count
  and a new-session button in the header.
- Quick Actions (small): New chat pill + status/instances.
- Lock Screen (accessoryCircular x2): brand logo to new session, attention counter.
- Control Center control: brand logo (custom SF Symbol) to new session.

Data: the app writes a session-overview snapshot (attention count + recent
sessions with project labels) to the App Group on scene activate/resign; the NSE
refreshes it from each push (aps.badge + sessionId) so widgets update even when
the app is closed (needs aps mutable-content, added to the server + relay).

Deep links: add openchamber://status (session status panel) and reuse
view/instances; all widget taps route through the existing deep-link channel.

* feat(mobile): large Sessions widget lists 6 sessions with project labels

* feat(mobile): edge-swipe to switch sessions with directional slide+fade

* fix(mobile): keep widgets in sync via reload-on-change + periodic refresh

Widgets sharing the app's WidgetKit reload budget refreshed unevenly, leaving the
large Sessions widget stale (no unread dot / attention count) while medium updated.
Drop the per-call updatedAt from the snapshot, only write + reloadAllTimelines when
the session overview actually changed (so we don't burn the budget on every scene
activate/resign), and give each widget a periodic timeline refresh so a missed
reload self-corrects.

* feat(mobile): Android support — chrome fixes, SSE lock, icon, QR scan

Cosmetics:
- Status bar: on Android inset the WebView below the bar (overlay:false) and
  paint it with the resolved theme background + correct content Style, since
  Android doesn't feed env(safe-area-inset-top) to CSS.
- Keyboard: skip the manual --oc-keyboard-inset on Android (the window resizes
  natively, so applying it double-counted and floated the composer); declare
  windowSoftInputMode=adjustResize and disable the shell height transition on
  Android so the header no longer bounces on keyboard open.

Transport: lock Capacitor apps to SSE — native WebSocket streaming is unreliable
on Android (events only arrive once a run finishes). Forced in sync-context and
the other options are disabled in the Chat settings UI.

Push: gate APNs registration to iOS only; on Android @capacitor/push-notifications
register() needs Firebase/FCM (not configured) and crashes at launch.

QR pairing: declare CAMERA permission + the ML Kit barcode_ui dependency, and
install/await the Google barcode scanner module (with a post-install retry) before
scanning so the first scan works without a manual retry.

Icon: Android adaptive launcher icon generated from the cube logo (full-bleed
white background, no edge artifact on One UI). Source assets under mobile/assets.

Tooling: adb-based android-device.mjs + android:* scripts for device deploy.

* feat(notifications): presence-aware push routing (don't spam the phone)

Only push to a device when the notification would otherwise be missed there. A
notification is suppressed on devices where the user is already present.

- Tag every client's visibility beacon and web-push subscription with a platform
  ('ios' | 'android' | 'vscode' | 'desktop' | 'web') via getClientPlatform().
- Server tracks visibility per client (keyed by oc_ui_session) with the platform,
  and exposes isAnyInteractiveClientVisible() = any visible non-mobile client.
- Native push (APNs) and mobile PWA web-push are now suppressed when an
  interactive (desktop/web/vscode) client is visible — it already shows the
  in-app notification. Gated on the desktop's visibility (reliable), never the
  phone's own (a backgrounded WKWebView can't report "hidden").
- Desktop/web web-push keeps the any-visible gate (a visible client absorbs it).
- Skipping APNs also skips the badge increment so it doesn't drift.

Fixes the case where every session on a shared instance pushed to the phone even
while the user was actively working on desktop.

* feat(mobile): Android FCM push notifications

Enable native background push on Android via Firebase Cloud Messaging, in parallel
with the existing iOS APNs path.

- Add google-services.json + declare POST_NOTIFICATIONS (Android 13+). The Google
  Services Gradle plugin is applied when the file is present, so register() returns
  an FCM token instead of crashing.
- Un-gate native push registration to iOS OR Android, and tag the registered token
  with its platform ('ios' | 'android') so the relay routes it to APNs vs FCM.
- Server stores the platform per device token and binds it to the relay (platform
  included in the signed register message).
- Notification small icon: monochrome cube silhouette with a mark on the top face,
  set as the FCM default_notification_icon so the status-bar icon reads as the logo.

Relay-side FCM sending ships in openchamber-website.

* docs(mobile): refresh HANDOFF with current state, dev/deploy process, and CI gap

* chore(mobile): iOS store-review prerequisites (privacy manifest, encryption flag)

- Add the app's PrivacyInfo.xcprivacy (no tracking; required-reason UserDefaults for the App
  Group snapshot shared with the widget + notification service extension) and wire it into the
  App target's resources — Apple requires an app-level privacy manifest.
- Set ITSAppUsesNonExemptEncryption=false to skip the per-build export-compliance prompt.
- HANDOFF: add a store-review-readiness checklist (in-repo vs release-time console/infra items).

Verified: plist lint, xcodebuild parse, and an iOS simulator build with PrivacyInfo.xcprivacy
bundled into App.app.

* refactor(mobile): dedupe capacitor detection + make beacon guard explicit

Addresses non-blocking PR review notes:
- Consolidate the repeated Capacitor-native check (mobileConnections, deepLinkNavigation,
  usePushVisibilityBeacon each redefined it) onto the single isCapacitorApp() in lib/platform.
- usePushVisibilityBeacon now guards on isWebRuntime() OR isCapacitorApp() instead of relying on
  isWebRuntime() being true for Capacitor, so the beacon can't silently stop if that changes.
2026-07-01 09:55:41 +03:00

1425 lines
56 KiB
JavaScript

import 'reflect-metadata';
import express from 'express';
import compression from 'compression';
import path from 'path';
import { spawn, spawnSync } from 'child_process';
import fs from 'fs';
import http from 'http';
import net from 'net';
import { fileURLToPath } from 'url';
import os from 'os';
import crypto from 'crypto';
import http2 from 'node:http2';
import { createUiAuth } from './lib/ui-auth/ui-auth.js';
import { createTunnelAuth } from './lib/opencode/tunnel-auth.js';
import { createManagedTunnelConfigRuntime } from './lib/tunnels/managed-config.js';
import { createTunnelProviderRegistry } from './lib/tunnels/registry.js';
import { createCloudflareTunnelProvider } from './lib/tunnels/providers/cloudflare.js';
import { createNgrokTunnelProvider } from './lib/tunnels/providers/ngrok.js';
import { createRequestSecurityRuntime } from './lib/security/request-security.js';
import {
getUnauthenticatedLanErrorMessage,
isNetworkExposedBindHost,
isUnsafeUnauthenticatedLanAllowed,
} from './lib/security/bind-host.js';
import {
TUNNEL_MODE_MANAGED_LOCAL,
TUNNEL_MODE_MANAGED_REMOTE,
TUNNEL_MODE_QUICK,
TUNNEL_PROVIDER_CLOUDFLARE,
TunnelServiceError,
isSupportedTunnelMode,
normalizeOptionalPath,
normalizeTunnelStartRequest,
normalizeTunnelMode,
normalizeTunnelProvider,
} from './lib/tunnels/types.js';
import { prepareNotificationLastMessage } from './lib/notifications/index.js';
import { registerTtsRoutes } from './lib/tts/routes.js';
import { detectSayTtsCapability } from './lib/tts/capability-runtime.js';
import { createTerminalRuntime } from './lib/terminal/runtime.js';
import {
createGlobalUiEventBroadcaster,
createGlobalMessageStreamHub,
createMessageStreamWsRuntime,
DEFAULT_UPSTREAM_STALL_TIMEOUT_MS,
UPSTREAM_STALL_TIMEOUT_CONCURRENT_MS,
} from './lib/event-stream/index.js';
import { createFsSearchRuntime as createFsSearchRuntimeFactory } from './lib/fs/search.js';
import { createOpenCodeLifecycleRuntime } from './lib/opencode/lifecycle.js';
import { createOpenCodeEnvRuntime } from './lib/opencode/env-runtime.js';
import { resolveOpenCodeEnvConfig } from './lib/opencode/env-config.js';
import { createHmrStateRuntime } from './lib/opencode/hmr-state-runtime.js';
import { createOpenCodeNetworkRuntime } from './lib/opencode/network-runtime.js';
import { createOpenCodeAuthStateRuntime } from './lib/opencode/auth-state-runtime.js';
import { createProjectDirectoryRuntime } from './lib/opencode/project-directory-runtime.js';
import { createSettingsNormalizationRuntime } from './lib/opencode/settings-normalization-runtime.js';
import { createSettingsHelpers } from './lib/opencode/settings-helpers.js';
import { createThemeRuntime } from './lib/opencode/theme-runtime.js';
import { createFeatureRoutesRuntime } from './lib/opencode/feature-routes-runtime.js';
import { parseServeCliOptions } from './lib/opencode/cli-options.js';
import {
registerAuthAndAccessRoutes,
registerCommonRequestMiddleware,
registerServerStatusRoutes,
} from './lib/opencode/core-routes.js';
import { registerOpenChamberRoutes } from './lib/opencode/openchamber-routes.js';
import { createServerUtilsRuntime } from './lib/opencode/server-utils-runtime.js';
import { createStaticRoutesRuntime } from './lib/opencode/static-routes-runtime.js';
import { createSettingsRuntime } from './lib/opencode/settings-runtime.js';
import { createOpenCodeResolutionRuntime } from './lib/opencode/opencode-resolution-runtime.js';
import { createBootstrapRuntime } from './lib/opencode/bootstrap-runtime.js';
import { createSessionRuntime } from './lib/opencode/session-runtime.js';
import { createOpenCodeWatcherRuntime } from './lib/opencode/watcher.js';
import { createScheduledTasksRuntime } from './lib/scheduled-tasks/runtime.js';
import { createServerStartupRuntime } from './lib/opencode/server-startup-runtime.js';
import { createTunnelWiringRuntime } from './lib/opencode/tunnel-wiring-runtime.js';
import { createStartupPipelineRuntime } from './lib/opencode/startup-pipeline-runtime.js';
import { runCliEntryIfMain } from './lib/opencode/cli-entry-runtime.js';
import { registerNotificationRoutes } from './lib/notifications/routes.js';
import { createNotificationEmitterRuntime } from './lib/notifications/emitter-runtime.js';
import { createNotificationTriggerRuntime } from './lib/notifications/runtime.js';
import { createPushRuntime } from './lib/notifications/push-runtime.js';
import { createApnsRuntime } from './lib/notifications/apns-runtime.js';
import { createNotificationTemplateRuntime } from './lib/notifications/template-runtime.js';
import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
import { createProjectConfigRuntime } from './lib/projects/project-config.js';
import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
import { createPreviewProxyRuntime } from './lib/preview/proxy-runtime.js';
import { attachRealtimeProxy } from './lib/realtime-proxy.js';
import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
import webPush from 'web-push';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DEFAULT_PORT = 3000;
const DESKTOP_NOTIFY_PREFIX = '[OpenChamberDesktopNotify] ';
const uiNotificationClients = new Set();
const uiNotificationWsClients = new Set();
const uiOpenChamberEventClients = new Set();
const HEALTH_CHECK_INTERVAL = 15000;
const SHUTDOWN_TIMEOUT = 10000;
const MODELS_DEV_API_URL = 'https://models.dev/api.json';
const MODELS_METADATA_CACHE_TTL = 5 * 60 * 1000;
const CLIENT_RELOAD_DELAY_MS = 800;
const OPEN_CODE_READY_GRACE_MS = 12000;
const LONG_REQUEST_TIMEOUT_MS = 4 * 60 * 1000;
const TUNNEL_BOOTSTRAP_TTL_DEFAULT_MS = 30 * 60 * 1000;
const TUNNEL_BOOTSTRAP_TTL_MIN_MS = 60 * 1000;
const TUNNEL_BOOTSTRAP_TTL_MAX_MS = 24 * 60 * 60 * 1000;
const TUNNEL_SESSION_TTL_DEFAULT_MS = 8 * 60 * 60 * 1000;
const TUNNEL_SESSION_TTL_MIN_MS = 5 * 60 * 1000;
const TUNNEL_SESSION_TTL_MAX_MS = 30 * 24 * 60 * 60 * 1000;
function headerIncludesEventStream(value) {
if (typeof value === 'string') {
return value.toLowerCase().includes('text/event-stream');
}
if (Array.isArray(value)) {
return value.some((entry) => typeof entry === 'string' && entry.toLowerCase().includes('text/event-stream'));
}
return false;
}
/**
* SSE endpoint paths that must never be compressed by the compression middleware.
*
* The compression middleware filter runs before route handlers, so
* `res.getHeader('Content-Type')` is still undefined at that point.
* This means the Accept-header check alone is not sufficient for
* non-standard clients (e.g. curl, fetch) that omit Accept.
* Path-based exclusion acts as a deterministic fallback.
*/
const SSE_PATH_PREFIXES = [
'/api/event',
'/api/global/event',
'/api/notifications/stream',
'/api/openchamber/events',
'/api/openchamber/realtime-proxy/sse',
];
function shouldSkipCompression(req, res) {
if (process.env.OPENCHAMBER_RUNTIME === 'desktop') {
return true;
}
if (headerIncludesEventStream(req.headers.accept)) {
return true;
}
const pathname = req.path || req.url || '';
if ((pathname === '/api' || pathname.startsWith('/api/')) && shouldSkipApiCompression()) {
return true;
}
if (pathname.startsWith('/api/terminal/') && pathname.endsWith('/stream')) {
return true;
}
for (const prefix of SSE_PATH_PREFIXES) {
if (pathname === prefix) {
return true;
}
}
return headerIncludesEventStream(res.getHeader('Content-Type'));
}
const OPENCHAMBER_VERSION = (() => {
try {
const packagePath = path.resolve(__dirname, '..', 'package.json');
const raw = fs.readFileSync(packagePath, 'utf8');
const pkg = JSON.parse(raw);
if (pkg && typeof pkg.version === 'string' && pkg.version.trim().length > 0) {
return pkg.version.trim();
}
} catch {
}
return 'unknown';
})();
const isEnvFlagEnabled = (value) => {
if (value === true || value === 1) return true;
if (typeof value !== 'string') return false;
const normalized = value.trim().toLowerCase();
return normalized === '1' || normalized === 'true';
};
const isEnvFlagDisabled = (value) => {
if (value === false || value === 0) return true;
if (typeof value !== 'string') return false;
const normalized = value.trim().toLowerCase();
return normalized === '0' || normalized === 'false';
};
const shouldSkipApiCompression = () => {
if (isEnvFlagEnabled(process.env.OPENCHAMBER_SKIP_API_COMPRESSION)) return true;
if (isEnvFlagEnabled(process.env.OPENCHAMBER_COMPRESS_API)) return false;
if (isEnvFlagDisabled(process.env.OPENCHAMBER_COMPRESS_API)) return true;
return process.env.OPENCHAMBER_RUNTIME === 'desktop';
};
const OPENCHAMBER_VERBOSE_REQUEST_LOGS = isEnvFlagEnabled(process.env.OPENCHAMBER_VERBOSE_REQUEST_LOGS);
const PLAN_MODE_EXPERIMENT_ENABLED =
isEnvFlagEnabled(process.env.OPENCODE_EXPERIMENTAL_PLAN_MODE)
|| isEnvFlagEnabled(process.env.OPENCODE_EXPERIMENTAL);
const fsPromises = fs.promises;
const settingsNormalizationRuntime = createSettingsNormalizationRuntime({
os,
path,
processLike: process,
realpathSync: fs.realpathSync,
tunnelBootstrapTtlDefaultMs: TUNNEL_BOOTSTRAP_TTL_DEFAULT_MS,
tunnelBootstrapTtlMinMs: TUNNEL_BOOTSTRAP_TTL_MIN_MS,
tunnelBootstrapTtlMaxMs: TUNNEL_BOOTSTRAP_TTL_MAX_MS,
tunnelSessionTtlDefaultMs: TUNNEL_SESSION_TTL_DEFAULT_MS,
tunnelSessionTtlMinMs: TUNNEL_SESSION_TTL_MIN_MS,
tunnelSessionTtlMaxMs: TUNNEL_SESSION_TTL_MAX_MS,
});
const normalizeDirectoryPath = (...args) => settingsNormalizationRuntime.normalizeDirectoryPath(...args);
const normalizePathForPersistence = (...args) => settingsNormalizationRuntime.normalizePathForPersistence(...args);
const normalizeSettingsPaths = (...args) => settingsNormalizationRuntime.normalizeSettingsPaths(...args);
const normalizeTunnelBootstrapTtlMs = (...args) => settingsNormalizationRuntime.normalizeTunnelBootstrapTtlMs(...args);
const normalizeTunnelSessionTtlMs = (...args) => settingsNormalizationRuntime.normalizeTunnelSessionTtlMs(...args);
const normalizeManagedRemoteTunnelHostname = (...args) =>
settingsNormalizationRuntime.normalizeManagedRemoteTunnelHostname(...args);
const normalizeManagedRemoteTunnelPresets = (...args) =>
settingsNormalizationRuntime.normalizeManagedRemoteTunnelPresets(...args);
const normalizeManagedRemoteTunnelPresetTokens = (...args) =>
settingsNormalizationRuntime.normalizeManagedRemoteTunnelPresetTokens(...args);
const isUnsafeSkillRelativePath = (...args) => settingsNormalizationRuntime.isUnsafeSkillRelativePath(...args);
const sanitizeTypographySizesPartial = (...args) =>
settingsNormalizationRuntime.sanitizeTypographySizesPartial(...args);
const normalizeStringArray = (...args) => settingsNormalizationRuntime.normalizeStringArray(...args);
const sanitizeModelRefs = (...args) => settingsNormalizationRuntime.sanitizeModelRefs(...args);
const sanitizeSkillCatalogs = (...args) => settingsNormalizationRuntime.sanitizeSkillCatalogs(...args);
const sanitizeProjects = (...args) => settingsNormalizationRuntime.sanitizeProjects(...args);
const OPENCHAMBER_USER_CONFIG_ROOT = path.join(os.homedir(), '.config', 'openchamber');
const OPENCHAMBER_USER_THEMES_DIR = path.join(OPENCHAMBER_USER_CONFIG_ROOT, 'themes');
const OPENCHAMBER_PROJECTS_CONFIG_DIR = path.join(OPENCHAMBER_USER_CONFIG_ROOT, 'projects');
const MAX_THEME_JSON_BYTES = 512 * 1024;
const themeRuntime = createThemeRuntime({
fsPromises,
path,
themesDir: OPENCHAMBER_USER_THEMES_DIR,
maxThemeJsonBytes: MAX_THEME_JSON_BYTES,
logger: console,
});
const readCustomThemesFromDisk = (...args) => themeRuntime.readCustomThemesFromDisk(...args);
let notificationTemplateRuntime = null;
const createTimeoutSignal = (...args) => notificationTemplateRuntime.createTimeoutSignal(...args);
const formatProjectLabel = (...args) => notificationTemplateRuntime.formatProjectLabel(...args);
const resolveNotificationTemplate = (...args) => notificationTemplateRuntime.resolveNotificationTemplate(...args);
const shouldApplyResolvedTemplateMessage = (...args) => notificationTemplateRuntime.shouldApplyResolvedTemplateMessage(...args);
const fetchFreeZenModels = (...args) => notificationTemplateRuntime.fetchFreeZenModels(...args);
const extractTextFromParts = (...args) => notificationTemplateRuntime.extractTextFromParts(...args);
const extractLastMessageText = (...args) => notificationTemplateRuntime.extractLastMessageText(...args);
const fetchLastAssistantMessageText = (...args) => notificationTemplateRuntime.fetchLastAssistantMessageText(...args);
const maybeCacheSessionInfoFromEvent = (...args) => notificationTemplateRuntime.maybeCacheSessionInfoFromEvent(...args);
const buildTemplateVariables = (...args) => notificationTemplateRuntime.buildTemplateVariables(...args);
const getCachedZenModels = (...args) => notificationTemplateRuntime.getCachedZenModels(...args);
const OPENCHAMBER_DATA_DIR = process.env.OPENCHAMBER_DATA_DIR
? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
: path.join(os.homedir(), '.config', 'openchamber');
const SETTINGS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'settings.json');
const PUSH_SUBSCRIPTIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'push-subscriptions.json');
const APNS_TOKENS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'apns-tokens.json');
const REMOTE_CLIENTS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'remote-clients.json');
const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-managed-remote-tunnels.json');
const CLOUDFLARE_LEGACY_NAMED_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-named-tunnels.json');
const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_VERSION = 1;
const managedTunnelConfigRuntime = createManagedTunnelConfigRuntime({
fsPromises,
path,
normalizeManagedRemoteTunnelHostname,
normalizeManagedRemoteTunnelPresets,
constants: {
CLOUDFLARE_MANAGED_REMOTE_TUNNELS_FILE_PATH,
CLOUDFLARE_LEGACY_NAMED_TUNNELS_FILE_PATH,
CLOUDFLARE_MANAGED_REMOTE_TUNNELS_VERSION,
},
});
const readManagedRemoteTunnelConfigFromDisk = (...args) => managedTunnelConfigRuntime.readManagedRemoteTunnelConfigFromDisk(...args);
const syncManagedRemoteTunnelConfigWithPresets = (...args) => managedTunnelConfigRuntime.syncManagedRemoteTunnelConfigWithPresets(...args);
const upsertManagedRemoteTunnelToken = (...args) => managedTunnelConfigRuntime.upsertManagedRemoteTunnelToken(...args);
const resolveManagedRemoteTunnelToken = (...args) => managedTunnelConfigRuntime.resolveManagedRemoteTunnelToken(...args);
const settingsHelpers = createSettingsHelpers({
normalizePathForPersistence,
normalizeDirectoryPath,
normalizeTunnelBootstrapTtlMs,
normalizeTunnelSessionTtlMs,
normalizeTunnelProvider,
normalizeTunnelMode,
normalizeOptionalPath,
normalizeManagedRemoteTunnelHostname,
normalizeManagedRemoteTunnelPresets,
normalizeManagedRemoteTunnelPresetTokens,
sanitizeTypographySizesPartial,
normalizeStringArray,
sanitizeModelRefs,
sanitizeSkillCatalogs,
sanitizeProjects,
});
const normalizePwaAppName = (...args) => settingsHelpers.normalizePwaAppName(...args);
const normalizePwaOrientation = (...args) => settingsHelpers.normalizePwaOrientation(...args);
const sanitizeSettingsUpdate = (...args) => settingsHelpers.sanitizeSettingsUpdate(...args);
const mergePersistedSettings = (...args) => settingsHelpers.mergePersistedSettings(...args);
const formatSettingsResponse = (...args) => settingsHelpers.formatSettingsResponse(...args);
const projectDirectoryRuntime = createProjectDirectoryRuntime({
fsPromises,
path,
normalizeDirectoryPath,
getReadSettingsFromDiskMigrated: () => readSettingsFromDiskMigrated,
sanitizeProjects,
});
const resolveDirectoryCandidate = (...args) => projectDirectoryRuntime.resolveDirectoryCandidate(...args);
const validateDirectoryPath = (...args) => projectDirectoryRuntime.validateDirectoryPath(...args);
const resolveProjectDirectory = (...args) => projectDirectoryRuntime.resolveProjectDirectory(...args);
const resolveOptionalProjectDirectory = (...args) => projectDirectoryRuntime.resolveOptionalProjectDirectory(...args);
const settingsRuntime = createSettingsRuntime({
fsPromises,
path,
crypto,
SETTINGS_FILE_PATH,
sanitizeProjects,
sanitizeSettingsUpdate,
mergePersistedSettings,
normalizeSettingsPaths,
normalizeStringArray,
formatSettingsResponse,
resolveDirectoryCandidate,
normalizeManagedRemoteTunnelHostname,
normalizeManagedRemoteTunnelPresets,
normalizeManagedRemoteTunnelPresetTokens,
syncManagedRemoteTunnelConfigWithPresets,
upsertManagedRemoteTunnelToken,
});
const readSettingsFromDiskMigrated = (...args) => settingsRuntime.readSettingsFromDiskMigrated(...args);
const readSettingsFromDisk = (...args) => settingsRuntime.readSettingsFromDisk(...args);
const writeSettingsToDisk = (...args) => settingsRuntime.writeSettingsToDisk(...args);
const persistSettings = (...args) => settingsRuntime.persistSettings(...args);
const requestSecurityRuntime = createRequestSecurityRuntime({
readSettingsFromDiskMigrated,
});
const getUiSessionTokenFromRequest = (...args) => requestSecurityRuntime.getUiSessionTokenFromRequest(...args);
const pushRuntime = createPushRuntime({
fsPromises,
path,
webPush,
PUSH_SUBSCRIPTIONS_FILE_PATH,
readSettingsFromDiskMigrated,
writeSettingsToDisk,
});
const getOrCreateVapidKeys = (...args) => pushRuntime.getOrCreateVapidKeys(...args);
const addOrUpdatePushSubscription = (...args) => pushRuntime.addOrUpdatePushSubscription(...args);
const removePushSubscription = (...args) => pushRuntime.removePushSubscription(...args);
const sendPushToAllUiSessions = (...args) => pushRuntime.sendPushToAllUiSessions(...args);
// Set once the notification trigger runtime exists (declared later). When a UI
// client reports it became visible, reset the native push badge set — the same
// moment the device zeroes its icon badge on becomeActive, keeping them in sync.
let clearPendingPushBadge = () => {};
const updateUiVisibility = (token, visible, platform) => {
if (visible === true) clearPendingPushBadge();
return pushRuntime.updateUiVisibility(token, visible, platform);
};
const isAnyUiVisible = (...args) => pushRuntime.isAnyUiVisible(...args);
const isAnyInteractiveClientVisible = (...args) => pushRuntime.isAnyInteractiveClientVisible(...args);
const isUiVisible = (...args) => pushRuntime.isUiVisible(...args);
const ensurePushInitialized = (...args) => pushRuntime.ensurePushInitialized(...args);
const setPushInitialized = (...args) => pushRuntime.setPushInitialized(...args);
const apnsRuntime = createApnsRuntime({
fsPromises,
path,
crypto,
http2,
APNS_TOKENS_FILE_PATH,
readSettingsFromDiskMigrated,
writeSettingsToDisk,
});
const addOrUpdateApnsToken = (...args) => apnsRuntime.addOrUpdateApnsToken(...args);
const removeApnsToken = (...args) => apnsRuntime.removeApnsToken(...args);
const sendApnsToAllUiSessions = (...args) => apnsRuntime.sendApnsToAllUiSessions(...args);
const TERMINAL_INPUT_WS_MAX_REBINDS_PER_WINDOW = 128;
const TERMINAL_INPUT_WS_REBIND_WINDOW_MS = 60 * 1000;
const TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS = 15 * 1000;
const rejectWebSocketUpgrade = (...args) => requestSecurityRuntime.rejectWebSocketUpgrade(...args);
const isRequestOriginAllowed = (...args) => requestSecurityRuntime.isRequestOriginAllowed(...args);
const notificationEmitterRuntime = createNotificationEmitterRuntime({
process,
getDesktopNotifyEnabled: () => ENV_DESKTOP_NOTIFY,
desktopNotifyPrefix: DESKTOP_NOTIFY_PREFIX,
getUiNotificationClients: () => uiNotificationClients,
getBroadcastGlobalUiEvent: () => broadcastGlobalUiEvent,
});
const writeSseEvent = (...args) => notificationEmitterRuntime.writeSseEvent(...args);
const emitDesktopNotification = (...args) => notificationEmitterRuntime.emitDesktopNotification(...args);
const broadcastGlobalUiEvent = createGlobalUiEventBroadcaster({
sseClients: uiNotificationClients,
wsClients: uiNotificationWsClients,
writeSseEvent,
});
const broadcastUiNotification = (...args) => notificationEmitterRuntime.broadcastUiNotification(...args);
const sessionRuntime = createSessionRuntime({
writeSseEvent,
getNotificationClients: () => uiNotificationClients,
broadcastEvent: broadcastGlobalUiEvent,
});
const getActiveSessionCount = () => {
const snapshot = sessionRuntime.getSessionActivitySnapshot();
return Object.values(snapshot).filter((entry) => entry.type === 'busy').length;
};
const getUpstreamStallTimeoutMs = () => (
getActiveSessionCount() > 1
? UPSTREAM_STALL_TIMEOUT_CONCURRENT_MS
: DEFAULT_UPSTREAM_STALL_TIMEOUT_MS
);
const projectConfigRuntime = createProjectConfigRuntime({
fsPromises,
path,
projectsDirPath: OPENCHAMBER_PROJECTS_CONFIG_DIR,
});
// HMR-persistent state via globalThis
// These values survive Vite HMR reloads to prevent zombie OpenCode processes
const hmrStateRuntime = createHmrStateRuntime({
globalThisLike: globalThis,
os,
processLike: process,
stateKey: '__openchamberHmrState',
});
const hmrState = hmrStateRuntime.getOrCreateHmrState();
hmrStateRuntime.ensureUserProvidedOpenCodePassword(hmrState);
// Non-HMR state (safe to reset on reload)
let healthCheckInterval = null;
let server = null;
let expressApp = null;
let currentRestartPromise = null;
let isRestartingOpenCode = false;
let openCodeApiPrefix = '';
let openCodeApiPrefixDetected = true;
let openCodeApiDetectionTimer = null;
let lastOpenCodeError = null;
let lastOpenCodeLaunchDiagnostics = null;
let isOpenCodeReady = false;
let openCodeNotReadySince = 0;
let isExternalOpenCode = false;
let exitOnShutdown = true;
let uiAuthController = null;
let activeTunnelController = null;
let globalWatcherStartPromise = null;
const tunnelProviderRegistry = createTunnelProviderRegistry([
createCloudflareTunnelProvider(),
createNgrokTunnelProvider(),
]);
tunnelProviderRegistry.seal();
const tunnelAuthController = createTunnelAuth();
let runtimeManagedRemoteTunnelToken = '';
let runtimeManagedRemoteTunnelHostname = '';
let terminalRuntime = null;
let messageStreamRuntime = null;
const userProvidedOpenCodePassword = hmrStateRuntime.getUserProvidedOpenCodePassword(hmrState);
const initialOpenCodeAuthState = hmrStateRuntime.resolveOpenCodeAuthFromState({
hmrState,
userProvidedOpenCodePassword,
});
let openCodeAuthPassword = initialOpenCodeAuthState.openCodeAuthPassword;
let openCodeAuthSource = initialOpenCodeAuthState.openCodeAuthSource;
// Sync helper - call after modifying any HMR state variable
const syncToHmrState = () => {
hmrStateRuntime.syncStateFromRuntime(hmrState, {
openCodeProcess,
openCodePort,
openCodeBaseUrl,
isShuttingDown,
signalsAttached,
openCodeWorkingDirectory,
openCodeAuthPassword,
openCodeAuthSource,
});
};
// Sync helper - call to restore state from HMR (e.g., on module reload)
const syncFromHmrState = () => {
const restored = hmrStateRuntime.restoreRuntimeFromState({
hmrState,
userProvidedOpenCodePassword,
});
openCodeProcess = restored.openCodeProcess;
openCodePort = restored.openCodePort;
openCodeBaseUrl = restored.openCodeBaseUrl;
isShuttingDown = restored.isShuttingDown;
signalsAttached = restored.signalsAttached;
openCodeWorkingDirectory = restored.openCodeWorkingDirectory;
openCodeAuthPassword = restored.openCodeAuthPassword;
openCodeAuthSource = restored.openCodeAuthSource;
};
// Module-level variables that shadow HMR state
// These are synced to/from hmrState to survive HMR reloads
let openCodeProcess = hmrState.openCodeProcess;
let openCodePort = hmrState.openCodePort;
let openCodeBaseUrl = hmrState.openCodeBaseUrl ?? null;
let isShuttingDown = hmrState.isShuttingDown;
let signalsAttached = hmrState.signalsAttached;
let openCodeWorkingDirectory = hmrState.openCodeWorkingDirectory;
const {
configuredOpenCodePort: ENV_CONFIGURED_OPENCODE_PORT,
configuredOpenCodeHost: ENV_CONFIGURED_OPENCODE_HOST,
effectivePort: ENV_EFFECTIVE_PORT,
configuredOpenCodeHostname: ENV_CONFIGURED_OPENCODE_HOSTNAME,
} = resolveOpenCodeEnvConfig({
env: process.env,
logger: console,
});
const ENV_SKIP_OPENCODE_START = process.env.OPENCODE_SKIP_START === 'true' ||
process.env.OPENCHAMBER_SKIP_OPENCODE_START === 'true';
const ENV_DESKTOP_NOTIFY = (() => {
if (process.env.OPENCHAMBER_DESKTOP_NOTIFY === 'true') {
return true;
}
if (process.env.OPENCHAMBER_RUNTIME === 'desktop') {
return true;
}
const argv0 = typeof process.argv?.[0] === 'string' ? process.argv[0] : '';
const argv1 = typeof process.argv?.[1] === 'string' ? process.argv[1] : '';
return /openchamber-server/i.test(argv0) || /openchamber-server/i.test(argv1);
})();
const openCodeAuthStateRuntime = createOpenCodeAuthStateRuntime({
crypto,
process,
getAuthPassword: () => openCodeAuthPassword,
setAuthPassword: (value) => {
openCodeAuthPassword = value;
},
getAuthSource: () => openCodeAuthSource,
setAuthSource: (value) => {
openCodeAuthSource = value;
},
getUserProvidedPassword: () => userProvidedOpenCodePassword,
syncToHmrState,
});
const getOpenCodeAuthHeaders = (...args) => openCodeAuthStateRuntime.getOpenCodeAuthHeaders(...args);
const isOpenCodeConnectionSecure = (...args) => openCodeAuthStateRuntime.isOpenCodeConnectionSecure(...args);
const ensureLocalOpenCodeServerPassword = (...args) => openCodeAuthStateRuntime.ensureLocalOpenCodeServerPassword(...args);
const openCodeNetworkState = {};
Object.defineProperties(openCodeNetworkState, {
openCodePort: { get: () => openCodePort, set: (value) => { openCodePort = value; } },
openCodeBaseUrl: { get: () => openCodeBaseUrl, set: (value) => { openCodeBaseUrl = value; } },
openCodeApiPrefix: { get: () => openCodeApiPrefix, set: (value) => { openCodeApiPrefix = value; } },
openCodeApiPrefixDetected: { get: () => openCodeApiPrefixDetected, set: (value) => { openCodeApiPrefixDetected = value; } },
openCodeApiDetectionTimer: { get: () => openCodeApiDetectionTimer, set: (value) => { openCodeApiDetectionTimer = value; } },
});
const openCodeNetworkRuntime = createOpenCodeNetworkRuntime({
state: openCodeNetworkState,
getOpenCodeAuthHeaders,
});
const waitForReady = (...args) => openCodeNetworkRuntime.waitForReady(...args);
const normalizeApiPrefix = (...args) => openCodeNetworkRuntime.normalizeApiPrefix(...args);
const setDetectedOpenCodeApiPrefix = (...args) => openCodeNetworkRuntime.setDetectedOpenCodeApiPrefix(...args);
const buildOpenCodeUrl = (...args) => openCodeNetworkRuntime.buildOpenCodeUrl(...args);
const ensureOpenCodeApiPrefix = (...args) => openCodeNetworkRuntime.ensureOpenCodeApiPrefix(...args);
const scheduleOpenCodeApiDetection = (...args) => openCodeNetworkRuntime.scheduleOpenCodeApiDetection(...args);
const ENV_CONFIGURED_API_PREFIX = normalizeApiPrefix(
process.env.OPENCODE_API_PREFIX || process.env.OPENCHAMBER_API_PREFIX || ''
);
if (ENV_CONFIGURED_API_PREFIX && ENV_CONFIGURED_API_PREFIX !== '') {
console.warn('Ignoring configured OpenCode API prefix; API runs at root.');
}
let cachedLoginShellEnvSnapshot;
let resolvedOpencodeBinary = null;
let resolvedOpencodeBinarySource = null;
let resolvedNodeBinary = null;
let resolvedBunBinary = null;
let resolvedGitBinary = null;
let useWslForOpencode = false;
let resolvedWslBinary = null;
let resolvedWslOpencodePath = null;
let resolvedWslDistro = null;
const openCodeEnvState = {};
Object.defineProperties(openCodeEnvState, {
cachedLoginShellEnvSnapshot: { get: () => cachedLoginShellEnvSnapshot, set: (value) => { cachedLoginShellEnvSnapshot = value; } },
resolvedOpencodeBinary: { get: () => resolvedOpencodeBinary, set: (value) => { resolvedOpencodeBinary = value; } },
resolvedOpencodeBinarySource: { get: () => resolvedOpencodeBinarySource, set: (value) => { resolvedOpencodeBinarySource = value; } },
resolvedNodeBinary: { get: () => resolvedNodeBinary, set: (value) => { resolvedNodeBinary = value; } },
resolvedBunBinary: { get: () => resolvedBunBinary, set: (value) => { resolvedBunBinary = value; } },
resolvedGitBinary: { get: () => resolvedGitBinary, set: (value) => { resolvedGitBinary = value; } },
useWslForOpencode: { get: () => useWslForOpencode, set: (value) => { useWslForOpencode = value; } },
resolvedWslBinary: { get: () => resolvedWslBinary, set: (value) => { resolvedWslBinary = value; } },
resolvedWslOpencodePath: { get: () => resolvedWslOpencodePath, set: (value) => { resolvedWslOpencodePath = value; } },
resolvedWslDistro: { get: () => resolvedWslDistro, set: (value) => { resolvedWslDistro = value; } },
});
const openCodeEnvRuntime = createOpenCodeEnvRuntime({
state: openCodeEnvState,
normalizeDirectoryPath,
readSettingsFromDiskMigrated,
});
const applyLoginShellEnvSnapshot = (...args) => openCodeEnvRuntime.applyLoginShellEnvSnapshot(...args);
const getLoginShellEnvSnapshot = (...args) => openCodeEnvRuntime.getLoginShellEnvSnapshot(...args);
const ensureOpencodeCliEnv = (...args) => openCodeEnvRuntime.ensureOpencodeCliEnv(...args);
const applyOpencodeBinaryFromSettings = (...args) => openCodeEnvRuntime.applyOpencodeBinaryFromSettings(...args);
const resolveOpencodeCliPath = (...args) => openCodeEnvRuntime.resolveOpencodeCliPath(...args);
const isExecutable = (...args) => openCodeEnvRuntime.isExecutable(...args);
const searchPathFor = (...args) => openCodeEnvRuntime.searchPathFor(...args);
const resolveGitBinaryForSpawn = (...args) => openCodeEnvRuntime.resolveGitBinaryForSpawn(...args);
const resolveManagedOpenCodeLaunchSpec = (...args) => openCodeEnvRuntime.resolveManagedOpenCodeLaunchSpec(...args);
const clearResolvedOpenCodeBinary = (...args) => openCodeEnvRuntime.clearResolvedOpenCodeBinary(...args);
const openCodeResolutionRuntime = createOpenCodeResolutionRuntime({
path,
resolveOpencodeCliPath,
applyOpencodeBinaryFromSettings,
ensureOpencodeCliEnv,
resolveManagedOpenCodeLaunchSpec,
getResolvedState: () => ({
resolvedOpencodeBinary,
resolvedOpencodeBinarySource,
useWslForOpencode,
resolvedWslBinary,
resolvedWslOpencodePath,
resolvedWslDistro,
resolvedNodeBinary,
resolvedBunBinary,
}),
setResolvedOpencodeBinarySource: (value) => {
resolvedOpencodeBinarySource = value;
},
});
const getOpenCodeResolutionSnapshot = (...args) =>
openCodeResolutionRuntime.getOpenCodeResolutionSnapshot(...args);
applyLoginShellEnvSnapshot();
notificationTemplateRuntime = createNotificationTemplateRuntime({
readSettingsFromDisk,
persistSettings,
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
resolveGitBinaryForSpawn,
});
const notificationTriggerRuntime = createNotificationTriggerRuntime({
readSettingsFromDisk,
prepareNotificationLastMessage,
buildTemplateVariables,
extractLastMessageText,
fetchLastAssistantMessageText,
resolveNotificationTemplate,
shouldApplyResolvedTemplateMessage,
emitDesktopNotification,
broadcastUiNotification,
sendPushToAllUiSessions,
sendApnsToAllUiSessions,
isAnyInteractiveClientVisible,
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
});
const maybeSendPushForTrigger = (...args) => notificationTriggerRuntime.maybeSendPushForTrigger(...args);
const setAutoAcceptSession = (...args) => notificationTriggerRuntime.setAutoAcceptSession(...args);
clearPendingPushBadge = () => notificationTriggerRuntime.clearPendingPushBadge();
const globalMessageStreamHub = createGlobalMessageStreamHub({
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
upstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
});
const openCodeWatcherRuntime = createOpenCodeWatcherRuntime({
waitForOpenCodePort: (...args) => waitForOpenCodePort(...args),
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
parseSseDataPayload: (...args) => parseSseDataPayload(...args),
globalEventHub: globalMessageStreamHub,
onPayload: (payload) => {
maybeCacheSessionInfoFromEvent(payload);
void maybeSendPushForTrigger(payload);
sessionRuntime.processOpenCodeSsePayload(payload);
},
});
const processForwardedEventPayload = (payload, emitSyntheticEvent) => {
if (!payload || typeof payload !== 'object' || typeof emitSyntheticEvent !== 'function') {
return;
}
maybeCacheSessionInfoFromEvent(payload);
if (payload.type !== 'session.status') {
return;
}
const properties = payload.properties && typeof payload.properties === 'object' ? payload.properties : {};
const statusInfo = properties.status && typeof properties.status === 'object' ? properties.status : {};
const info = properties.info && typeof properties.info === 'object' ? properties.info : {};
const sessionId = typeof properties.sessionID === 'string' ? properties.sessionID.trim() : '';
const status = typeof statusInfo.type === 'string'
? statusInfo.type.trim()
: (typeof info.type === 'string' ? info.type.trim() : '');
if (!sessionId || !status) {
return;
}
emitSyntheticEvent({
type: 'openchamber:session-status',
properties: {
sessionID: sessionId,
status,
timestamp: Date.now(),
metadata: {
attempt: typeof statusInfo.attempt === 'number'
? statusInfo.attempt
: (typeof info.attempt === 'number' ? info.attempt : undefined),
message: typeof statusInfo.message === 'string'
? statusInfo.message
: (typeof info.message === 'string' ? info.message : undefined),
next: typeof statusInfo.next === 'number'
? statusInfo.next
: (typeof info.next === 'number' ? info.next : undefined),
},
needsAttention: false,
},
});
emitSyntheticEvent({
type: 'openchamber:session-activity',
properties: {
sessionId,
phase: status === 'busy' || status === 'retry' ? 'busy' : 'idle',
},
});
};
const serverUtilsRuntime = createServerUtilsRuntime({
fs,
os,
path,
process,
openCodeReadyGraceMs: OPEN_CODE_READY_GRACE_MS,
longRequestTimeoutMs: LONG_REQUEST_TIMEOUT_MS,
getRuntime: () => ({
openCodePort,
openCodeBaseUrl,
openCodeNotReadySince,
isOpenCodeReady,
isRestartingOpenCode,
}),
getOpenCodeAuthHeaders,
buildOpenCodeUrl,
ensureOpenCodeApiPrefix,
getUiNotificationClients: () => uiNotificationClients,
getOpenCodePort: () => openCodePort,
setOpenCodePortState: (value) => {
openCodePort = value;
},
syncToHmrState,
markOpenCodeNotReady: () => {
isOpenCodeReady = false;
},
setOpenCodeNotReadySince: (value) => {
openCodeNotReadySince = value;
},
clearLastOpenCodeError: () => {
lastOpenCodeError = null;
},
getLoginShellPath: () => {
const snapshot = getLoginShellEnvSnapshot();
if (!snapshot || typeof snapshot.PATH !== 'string' || snapshot.PATH.length === 0) {
return null;
}
return snapshot.PATH;
},
});
const setOpenCodePort = (...args) => serverUtilsRuntime.setOpenCodePort(...args);
const waitForOpenCodePort = (...args) => serverUtilsRuntime.waitForOpenCodePort(...args);
const buildAugmentedPath = (...args) => serverUtilsRuntime.buildAugmentedPath(...args);
const buildManagedOpenCodePath = (...args) => serverUtilsRuntime.buildManagedOpenCodePath(...args);
const parseSseDataPayload = (...args) => serverUtilsRuntime.parseSseDataPayload(...args);
const staticRoutesRuntime = createStaticRoutesRuntime({
fs,
path,
process,
__dirname,
express,
resolveProjectDirectory,
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
readSettingsFromDiskMigrated,
normalizePwaAppName,
normalizePwaOrientation,
});
const remoteClientAuthRuntime = createRemoteClientAuthRuntime({
fsPromises,
path,
crypto,
storePath: REMOTE_CLIENTS_FILE_PATH,
});
const featureRoutesRuntime = createFeatureRoutesRuntime({
clientReloadDelayMs: CLIENT_RELOAD_DELAY_MS,
});
const bootstrapRuntime = createBootstrapRuntime({
createUiAuth,
registerServerStatusRoutes,
registerCommonRequestMiddleware,
registerAuthAndAccessRoutes,
registerTtsRoutes,
registerNotificationRoutes,
registerOpenChamberRoutes,
express,
});
const tunnelWiringRuntime = createTunnelWiringRuntime({
crypto,
URL,
tunnelProviderRegistry,
tunnelAuthController,
readSettingsFromDiskMigrated,
readManagedRemoteTunnelConfigFromDisk,
normalizeTunnelProvider,
normalizeTunnelMode,
normalizeOptionalPath,
normalizeManagedRemoteTunnelHostname,
normalizeTunnelBootstrapTtlMs,
normalizeTunnelSessionTtlMs,
isSupportedTunnelMode,
upsertManagedRemoteTunnelToken,
resolveManagedRemoteTunnelToken,
TUNNEL_MODE_QUICK,
TUNNEL_MODE_MANAGED_LOCAL,
TUNNEL_MODE_MANAGED_REMOTE,
TUNNEL_PROVIDER_CLOUDFLARE,
TunnelServiceError,
getActiveTunnelController: () => activeTunnelController,
setActiveTunnelController: (value) => {
activeTunnelController = value;
},
getRuntimeManagedRemoteTunnelHostname: () => runtimeManagedRemoteTunnelHostname,
setRuntimeManagedRemoteTunnelHostname: (value) => {
runtimeManagedRemoteTunnelHostname = value;
},
getRuntimeManagedRemoteTunnelToken: () => runtimeManagedRemoteTunnelToken,
setRuntimeManagedRemoteTunnelToken: (value) => {
runtimeManagedRemoteTunnelToken = value;
},
});
const startupPipelineRuntime = createStartupPipelineRuntime({
createTerminalRuntime,
createMessageStreamWsRuntime,
createServerStartupRuntime,
});
const openCodeLifecycleState = {};
Object.defineProperties(openCodeLifecycleState, {
openCodeProcess: { get: () => openCodeProcess, set: (value) => { openCodeProcess = value; } },
openCodePort: { get: () => openCodePort, set: (value) => { openCodePort = value; } },
openCodeBaseUrl: { get: () => openCodeBaseUrl, set: (value) => { openCodeBaseUrl = value; } },
openCodeWorkingDirectory: { get: () => openCodeWorkingDirectory, set: (value) => { openCodeWorkingDirectory = value; } },
currentRestartPromise: { get: () => currentRestartPromise, set: (value) => { currentRestartPromise = value; } },
isRestartingOpenCode: { get: () => isRestartingOpenCode, set: (value) => { isRestartingOpenCode = value; } },
openCodeApiPrefix: { get: () => openCodeApiPrefix, set: (value) => { openCodeApiPrefix = value; } },
openCodeApiPrefixDetected: { get: () => openCodeApiPrefixDetected, set: (value) => { openCodeApiPrefixDetected = value; } },
openCodeApiDetectionTimer: { get: () => openCodeApiDetectionTimer, set: (value) => { openCodeApiDetectionTimer = value; } },
lastOpenCodeError: { get: () => lastOpenCodeError, set: (value) => { lastOpenCodeError = value; } },
lastOpenCodeLaunchDiagnostics: { get: () => lastOpenCodeLaunchDiagnostics, set: (value) => { lastOpenCodeLaunchDiagnostics = value; } },
isOpenCodeReady: { get: () => isOpenCodeReady, set: (value) => { isOpenCodeReady = value; } },
openCodeNotReadySince: { get: () => openCodeNotReadySince, set: (value) => { openCodeNotReadySince = value; } },
isExternalOpenCode: { get: () => isExternalOpenCode, set: (value) => { isExternalOpenCode = value; } },
isShuttingDown: { get: () => isShuttingDown, set: (value) => { isShuttingDown = value; } },
healthCheckInterval: { get: () => healthCheckInterval, set: (value) => { healthCheckInterval = value; } },
expressApp: { get: () => expressApp, set: (value) => { expressApp = value; } },
useWslForOpencode: { get: () => useWslForOpencode, set: (value) => { useWslForOpencode = value; } },
resolvedWslBinary: { get: () => resolvedWslBinary, set: (value) => { resolvedWslBinary = value; } },
resolvedWslOpencodePath: { get: () => resolvedWslOpencodePath, set: (value) => { resolvedWslOpencodePath = value; } },
resolvedWslDistro: { get: () => resolvedWslDistro, set: (value) => { resolvedWslDistro = value; } },
});
const openCodeLifecycleRuntime = createOpenCodeLifecycleRuntime({
state: openCodeLifecycleState,
env: {
ENV_CONFIGURED_OPENCODE_PORT,
ENV_CONFIGURED_OPENCODE_HOST,
ENV_EFFECTIVE_PORT,
ENV_CONFIGURED_OPENCODE_HOSTNAME,
ENV_SKIP_OPENCODE_START,
},
syncToHmrState,
syncFromHmrState,
getOpenCodeAuthHeaders,
buildOpenCodeUrl,
waitForReady,
normalizeApiPrefix,
applyOpencodeBinaryFromSettings,
ensureOpencodeCliEnv,
ensureLocalOpenCodeServerPassword,
resolveManagedOpenCodeLaunchSpec,
setOpenCodePort,
setDetectedOpenCodeApiPrefix,
setupProxy: (...args) => setupProxy(...args),
ensureOpenCodeApiPrefix,
clearResolvedOpenCodeBinary,
buildAugmentedPath,
buildManagedOpenCodePath,
getManagedOpenCodeShellEnvSnapshot: getLoginShellEnvSnapshot,
getActiveSessionCount,
});
const restartOpenCode = (...args) => openCodeLifecycleRuntime.restartOpenCode(...args);
const waitForOpenCodeReady = (...args) => openCodeLifecycleRuntime.waitForOpenCodeReady(...args);
const waitForAgentPresence = (...args) => openCodeLifecycleRuntime.waitForAgentPresence(...args);
const refreshOpenCodeAfterConfigChange = (...args) => openCodeLifecycleRuntime.refreshOpenCodeAfterConfigChange(...args);
const startHealthMonitoring = () => openCodeLifecycleRuntime.startHealthMonitoring(HEALTH_CHECK_INTERVAL);
const triggerHealthCheck = () => openCodeLifecycleRuntime.triggerHealthCheck();
const scheduledTasksRuntime = createScheduledTasksRuntime({
projectConfigRuntime,
listProjects: async () => {
const settings = await readSettingsFromDiskMigrated();
return sanitizeProjects(settings?.projects || []);
},
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
waitForOpenCodeReady,
emitTaskRunEvent: (event) => {
for (const client of uiOpenChamberEventClients) {
try {
writeSseEvent(client, {
type: 'openchamber:scheduled-task-ran',
properties: {
projectId: event.projectID,
taskId: event.taskID,
ranAt: event.ranAt,
status: event.status,
...(event.sessionID ? { sessionId: event.sessionID } : {}),
},
});
} catch {
uiOpenChamberEventClients.delete(client);
}
}
},
logger: console,
});
const ensureGlobalWatcherStarted = async () => {
if (globalWatcherStartPromise) {
return globalWatcherStartPromise;
}
globalWatcherStartPromise = openCodeWatcherRuntime.start().catch((error) => {
globalWatcherStartPromise = null;
throw error;
});
return globalWatcherStartPromise;
};
const bootstrapOpenCodeAtStartup = async (...args) => {
await openCodeLifecycleRuntime.bootstrapOpenCodeAtStartup(...args);
scheduleOpenCodeApiDetection();
if (openCodeLifecycleState.openCodeProcess && !openCodeLifecycleState.isExternalOpenCode) {
startHealthMonitoring();
}
if (ENV_DESKTOP_NOTIFY) {
void ensureGlobalWatcherStarted().catch((error) => {
console.warn(`Global event watcher startup failed: ${error?.message || error}`);
});
}
};
const killProcessOnPort = (...args) => openCodeLifecycleRuntime.killProcessOnPort(...args);
const waitForPortRelease = (...args) => openCodeLifecycleRuntime.waitForPortRelease(...args);
const fetchAgentsSnapshot = (...args) => serverUtilsRuntime.fetchAgentsSnapshot(...args);
const fetchProvidersSnapshot = (...args) => serverUtilsRuntime.fetchProvidersSnapshot(...args);
const fetchModelsSnapshot = (...args) => serverUtilsRuntime.fetchModelsSnapshot(...args);
const setupProxy = (...args) => serverUtilsRuntime.setupProxy(...args);
const gracefulShutdownRuntime = createGracefulShutdownRuntime({
process,
shutdownTimeoutMs: SHUTDOWN_TIMEOUT,
getExitOnShutdown: () => exitOnShutdown,
getIsShuttingDown: () => isShuttingDown,
setIsShuttingDown: (value) => {
isShuttingDown = value;
},
syncToHmrState,
openCodeWatcherRuntime,
sessionRuntime,
getHealthCheckInterval: () => healthCheckInterval,
clearHealthCheckInterval: (value) => clearInterval(value),
getTerminalRuntime: () => terminalRuntime,
setTerminalRuntime: (value) => {
terminalRuntime = value;
},
getMessageStreamRuntime: () => messageStreamRuntime,
setMessageStreamRuntime: (value) => {
messageStreamRuntime = value;
},
shouldSkipOpenCodeStop: () => ENV_SKIP_OPENCODE_START || isExternalOpenCode,
getOpenCodePort: () => openCodePort,
getOpenCodeProcess: () => openCodeProcess,
setOpenCodeProcess: (value) => {
openCodeProcess = value;
},
killProcessOnPort,
waitForPortRelease,
getServer: () => server,
getUiAuthController: () => uiAuthController,
setUiAuthController: (value) => {
uiAuthController = value;
},
getActiveTunnelController: () => activeTunnelController,
setActiveTunnelController: (value) => {
activeTunnelController = value;
},
tunnelAuthController,
scheduledTasksRuntime,
});
const gracefulShutdown = (...args) => gracefulShutdownRuntime.gracefulShutdown(...args);
async function main(options = {}) {
const port = Number.isFinite(options.port) && options.port >= 0 ? Math.trunc(options.port) : DEFAULT_PORT;
const host = typeof options.host === 'string' && options.host.length > 0 ? options.host : undefined;
const effectiveBindHost = host
|| (typeof process.env.OPENCHAMBER_HOST === 'string' && process.env.OPENCHAMBER_HOST.trim().length > 0
? process.env.OPENCHAMBER_HOST.trim()
: '127.0.0.1');
const uiPassword = typeof options.uiPassword === 'string'
? options.uiPassword
: (typeof process.env.OPENCHAMBER_UI_PASSWORD === 'string' ? process.env.OPENCHAMBER_UI_PASSWORD : null);
if (
isNetworkExposedBindHost(effectiveBindHost)
&& !(typeof uiPassword === 'string' && uiPassword.trim().length > 0)
&& !isUnsafeUnauthenticatedLanAllowed(process.env)
) {
throw new Error(getUnauthenticatedLanErrorMessage(effectiveBindHost));
}
const tryCfTunnel = options.tryCfTunnel === true;
const apiOnly = options.apiOnly === true || isEnvFlagEnabled(process.env.OPENCHAMBER_API_ONLY);
const shouldUseCanonicalTunnelConfig = typeof options.tunnelMode === 'string'
|| typeof options.tunnelProvider === 'string'
|| options.tunnelConfigPath === null
|| typeof options.tunnelConfigPath === 'string'
|| typeof options.tunnelToken === 'string'
|| typeof options.tunnelHostname === 'string';
const startupTunnelRequest = shouldUseCanonicalTunnelConfig
? normalizeTunnelStartRequest({
provider: normalizeTunnelProvider(options.tunnelProvider),
mode: options.tunnelMode,
configPath: normalizeOptionalPath(options.tunnelConfigPath),
token: typeof options.tunnelToken === 'string' ? options.tunnelToken.trim() : '',
hostname: normalizeManagedRemoteTunnelHostname(options.tunnelHostname),
})
: (tryCfTunnel
? {
provider: TUNNEL_PROVIDER_CLOUDFLARE,
mode: TUNNEL_MODE_QUICK,
configPath: undefined,
token: '',
hostname: undefined,
}
: null);
const attachSignals = options.attachSignals !== false;
const onTunnelReady = typeof options.onTunnelReady === 'function' ? options.onTunnelReady : null;
if (typeof options.exitOnShutdown === 'boolean') {
exitOnShutdown = options.exitOnShutdown;
}
if (typeof options.onDesktopNotification === 'function') {
notificationEmitterRuntime.setOnDesktopNotification(options.onDesktopNotification);
}
if (typeof options.getIsWindowFocused === 'function') {
notificationTriggerRuntime.setGetIsWindowFocused(options.getIsWindowFocused);
}
const getDesktopRuntimeConfig = typeof options.getDesktopRuntimeConfig === 'function'
? options.getDesktopRuntimeConfig
: null;
console.log(`Starting OpenChamber on port ${port === 0 ? 'auto' : port}`);
const sayTTSCapability = await detectSayTtsCapability(process);
const app = express();
const serverStartedAt = new Date().toISOString();
const packagedClientOrigins = new Set([
'openchamber-ui://app',
'capacitor://localhost',
'http://localhost',
'https://localhost',
]);
const isLocalDevClientOrigin = (origin) => /^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(origin);
app.set('trust proxy', true);
// Keep self-hosted instances out of search engines. The app shell is served
// publicly (it loads before prompting for the UI password), so without this
// even a password-protected instance gets crawled and indexed. Applies to
// every response; the robots.txt route makes the intent explicit for crawlers.
app.use((_req, res, next) => {
res.setHeader('X-Robots-Tag', 'noindex, nofollow');
next();
});
app.get('/robots.txt', (_req, res) => {
res.type('text/plain').send('User-agent: *\nDisallow: /\n');
});
app.use((req, res, next) => {
const origin = typeof req.headers.origin === 'string' ? req.headers.origin : '';
if (packagedClientOrigins.has(origin) || isLocalDevClientOrigin(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory');
res.setHeader('Access-Control-Expose-Headers', 'x-next-cursor');
res.setHeader('Vary', 'Origin');
if (req.method === 'OPTIONS') {
res.status(204).end();
return;
}
}
next();
});
app.use(compression({
filter: (req, res) => {
if (shouldSkipCompression(req, res)) return false;
return compression.filter(req, res);
},
threshold: 1024,
}));
expressApp = app;
server = http.createServer(app);
let realtimeProxyRuntime = { stop: () => {} };
const bootstrapResult = bootstrapRuntime.setupBaseRoutes(app, {
process,
openchamberVersion: OPENCHAMBER_VERSION,
runtimeName: process.env.OPENCHAMBER_RUNTIME || 'web',
serverStartedAt,
gracefulShutdown,
getHealthSnapshot: () => {
const launchSpec = resolvedOpencodeBinary && !useWslForOpencode
? resolveManagedOpenCodeLaunchSpec(resolvedOpencodeBinary)
: null;
return {
openCodePort,
openCodeRunning: Boolean(openCodePort && isOpenCodeReady && !isRestartingOpenCode),
openCodeSecureConnection: isOpenCodeConnectionSecure(),
openCodeAuthSource: openCodeAuthSource || null,
openCodeApiPrefix: '',
openCodeApiPrefixDetected: true,
isOpenCodeReady,
lastOpenCodeError,
lastOpenCodeLaunchDiagnostics,
opencodeBinaryResolved: resolvedOpencodeBinary || null,
opencodeBinarySource: resolvedOpencodeBinarySource || null,
opencodeLaunchBinary: launchSpec?.binary || null,
opencodeLaunchArgs: launchSpec?.args || [],
opencodeLaunchWrapperType: launchSpec?.wrapperType || null,
opencodeViaWsl: useWslForOpencode,
opencodeWslBinary: resolvedWslBinary || null,
opencodeWslPath: resolvedWslOpencodePath || null,
opencodeWslDistro: resolvedWslDistro || null,
nodeBinaryResolved: resolvedNodeBinary || null,
bunBinaryResolved: resolvedBunBinary || null,
desktopNotifyEnabled: ENV_DESKTOP_NOTIFY,
planModeExperimentalEnabled: PLAN_MODE_EXPERIMENT_ENABLED,
apiOnly,
};
},
verboseRequestLogs: OPENCHAMBER_VERBOSE_REQUEST_LOGS,
uiPassword,
tunnelAuthController,
remoteClientAuthRuntime,
readSettingsFromDiskMigrated,
normalizeTunnelSessionTtlMs,
sayTTSCapability,
ensurePushInitialized,
ensureGlobalWatcherStarted,
getOrCreateVapidKeys,
getUiSessionTokenFromRequest,
writeSettingsToDisk,
addOrUpdatePushSubscription,
removePushSubscription,
addOrUpdateApnsToken,
removeApnsToken,
updateUiVisibility,
clearPendingPushBadge: () => clearPendingPushBadge(),
isUiVisible,
getUiNotificationClients: () => uiNotificationClients,
writeSseEvent,
sessionRuntime,
setPushInitialized,
fs,
os,
path,
server,
__dirname,
openchamberDataDir: OPENCHAMBER_DATA_DIR,
modelsDevApiUrl: MODELS_DEV_API_URL,
modelsMetadataCacheTtl: MODELS_METADATA_CACHE_TTL,
fetchFreeZenModels,
getCachedZenModels,
setAutoAcceptSession,
});
uiAuthController = bootstrapResult.uiAuthController;
realtimeProxyRuntime = attachRealtimeProxy({
app,
server,
getDesktopRuntimeConfig,
getUiAuthController: () => uiAuthController,
isRequestOriginAllowed,
});
const tunnelRuntimeContext = tunnelWiringRuntime.initialize(app, port);
const { tunnelService, startTunnelWithNormalizedRequest } = tunnelRuntimeContext;
await featureRoutesRuntime.registerRoutes(app, {
crypto,
fs,
os,
path,
fsPromises,
spawn,
resolveGitBinaryForSpawn,
createFsSearchRuntime: createFsSearchRuntimeFactory,
openchamberDataDir: OPENCHAMBER_DATA_DIR,
openchamberUserConfigRoot: OPENCHAMBER_USER_CONFIG_ROOT,
normalizeDirectoryPath,
resolveProjectDirectory,
resolveOptionalProjectDirectory,
validateDirectoryPath,
readCustomThemesFromDisk,
refreshOpenCodeAfterConfigChange,
getOpenCodeResolutionSnapshot,
formatSettingsResponse,
readSettingsFromDisk,
readSettingsFromDiskMigrated,
persistSettings,
sanitizeProjects,
sanitizeSkillCatalogs,
isUnsafeSkillRelativePath,
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
getOpenCodePort: () => openCodePort,
buildAugmentedPath,
projectConfigRuntime,
scheduledTasksRuntime,
getOpenChamberEventClients: () => uiOpenChamberEventClients,
writeSseEvent,
});
const previewProxyRuntime = createPreviewProxyRuntime({
crypto,
URL,
createProxyMiddleware,
responseInterceptor,
});
previewProxyRuntime.attach(app, {
server,
express,
uiAuthController,
isRequestOriginAllowed,
rejectWebSocketUpgrade,
});
const startupPipelineResult = await startupPipelineRuntime.run({
app,
server,
express,
fs,
path,
uiAuthController,
buildAugmentedPath,
searchPathFor,
isExecutable,
isRequestOriginAllowed,
rejectWebSocketUpgrade,
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
globalEventHub: globalMessageStreamHub,
processForwardedEventPayload,
messageStreamWsClients: uiNotificationWsClients,
upstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
terminalHeartbeatIntervalMs: TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS,
terminalRebindWindowMs: TERMINAL_INPUT_WS_REBIND_WINDOW_MS,
terminalMaxRebindsPerWindow: TERMINAL_INPUT_WS_MAX_REBINDS_PER_WINDOW,
setupProxy,
scheduleOpenCodeApiDetection,
bootstrapOpenCodeAtStartup,
triggerHealthCheck,
staticRoutesRuntime,
process,
crypto,
normalizeTunnelBootstrapTtlMs,
readSettingsFromDiskMigrated,
tunnelAuthController,
startTunnelWithNormalizedRequest,
gracefulShutdown,
getSignalsAttached: () => signalsAttached,
setSignalsAttached: (value) => {
signalsAttached = value;
},
syncToHmrState,
TUNNEL_MODE_QUICK,
TUNNEL_MODE_MANAGED_LOCAL,
TUNNEL_MODE_MANAGED_REMOTE,
host,
port,
startupTunnelRequest,
onTunnelReady,
tunnelRuntimeContext,
attachSignals,
apiOnly,
});
terminalRuntime = startupPipelineResult.terminalRuntime;
messageStreamRuntime = startupPipelineResult.messageStreamRuntime;
try {
await scheduledTasksRuntime.start();
} catch (error) {
console.warn('[ScheduledTasks] Failed to start runtime:', error?.message || error);
}
return {
expressApp: app,
httpServer: server,
getPort: () => tunnelRuntimeContext.getActivePort(),
getOpenCodePort: () => openCodePort,
getTunnelUrl: () => tunnelService.getPublicUrl(),
getQuitRiskStatus: () => ({
tunnel: {
active: Boolean(tunnelService.getPublicUrl()),
},
scheduledTasks: scheduledTasksRuntime.getStatus(),
}),
isReady: () => isOpenCodeReady,
restartOpenCode: () => restartOpenCode(),
getOpenCodeProcessInfo: () => {
const managed = Boolean((openCodeProcess || openCodePort) && !ENV_SKIP_OPENCODE_START && !isExternalOpenCode);
// Only ever expose pid/port for a server WE manage. The Electron-side
// killer kills by port (lsof + kill -KILL), so returning a port we don't
// own — e.g. an external/desktop OpenCode on 4096 we attached to — would
// let a single miscomputed `managed` flag take down the user's separate
// server. Structurally withhold what isn't ours so the killer has no
// target, instead of relying on the flag check alone.
return {
managed,
pid: managed && typeof openCodeProcess?.pid === 'number' ? openCodeProcess.pid : null,
port: managed ? openCodePort : null,
};
},
stop: (shutdownOptions = {}) => {
realtimeProxyRuntime.stop();
return gracefulShutdown({ exitProcess: shutdownOptions.exitProcess ?? false });
}
};
}
runCliEntryIfMain({
process,
currentFilename: __filename,
parseServeCliOptions,
defaultPort: DEFAULT_PORT,
cloudflareProvider: TUNNEL_PROVIDER_CLOUDFLARE,
managedLocalMode: TUNNEL_MODE_MANAGED_LOCAL,
setExitOnShutdown: (value) => {
exitOnShutdown = value;
},
startServer: main,
});
export {
gracefulShutdown,
setupProxy,
restartOpenCode,
main as startWebUiServer,
parseServeCliOptions as parseArgs,
};