@wrongstack/webui 0.77.0 → 0.82.6

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server/index.ts","../../src/server/http-server.ts","../../src/server/file-picker.ts","../../../runtime/src/container.ts","../../src/server/boot.ts","../../src/server/autophase-ws-handler.ts","../../src/server/collaboration-ws-handler.ts","../../src/server/worktree-ws-handler.ts","../../src/server/ws-auth.ts","../../src/server/lifecycle.ts","../../src/server/instance-registry.ts","../../src/server/port-utils.ts","../../src/server/open-browser.ts","../../src/server/usage-cost.ts","../../src/server/provider-config-io.ts","../../src/server/provider-keys.ts","../../src/server/ws-utils.ts","../../src/server/provider-handlers.ts","../../src/server/setup-events.ts","../../src/server/token-estimator.ts","../../src/server/entry.ts"],"sourcesContent":["import * as fs from 'node:fs/promises';\r\nimport * as http from 'node:http';\r\nimport * as path from 'node:path';\r\nimport { createHttpServer } from './http-server.js';\r\nimport { SKIP_DIRS, isHiddenEntry, rankFiles } from './file-picker.js';\r\nimport {\r\n Agent,\r\n AutoCompactionMiddleware,\r\n Context,\r\n DefaultMemoryStore,\r\n DefaultModeStore,\r\n DefaultModelsRegistry,\r\n DefaultSessionReader,\r\n DefaultSessionStore,\r\n DefaultSkillLoader,\r\n DefaultSystemPromptBuilder,\r\n DefaultTokenCounter,\r\n AnnotationsStore,\r\n CollaborationBus,\r\n collabPauseMiddleware,\r\n collabInjectMiddleware,\r\n estimateRequestTokensCalibrated,\r\n EventBus,\r\n HybridCompactor,\r\n type ProviderConfig,\r\n type Provider,\r\n ProviderRegistry,\r\n TOKENS,\r\n ToolRegistry,\r\n atomicWrite,\r\n createDefaultPipelines,\r\n DEFAULT_CONTEXT_WINDOW_MODE_ID,\r\n DEFAULT_TOOLS_CONFIG,\r\n listContextWindowModes,\r\n repairToolUseAdjacency,\r\n resolveContextWindowPolicy,\r\n} from '@wrongstack/core';\r\nimport { ToolExecutor } from '@wrongstack/core/execution';\r\nimport { decryptConfigSecrets, encryptConfigSecrets } from '@wrongstack/core/security';\r\nimport { buildProviderFactoriesFromRegistry, makeProviderFromConfig } from '@wrongstack/providers';\r\nimport { builtinToolsPack, forgetTool, rememberTool } from '@wrongstack/tools';\r\nimport { type WebSocket, WebSocketServer } from 'ws';\r\nimport { createDefaultContainer } from '../../../runtime/src/container.js';\r\nimport { bootConfig, patchConfig, } from './boot.js';\r\nimport { AutoPhaseWebSocketHandler } from './autophase-ws-handler.js';\r\nimport { CollaborationWebSocketHandler } from './collaboration-ws-handler.js';\r\nimport { WorktreeWebSocketHandler } from './worktree-ws-handler.js';\r\nimport { verifyClient as verifyWsClient } from './ws-auth.js';\r\nimport { registerShutdownHandlers } from './lifecycle.js';\r\nimport { registerInstance, unregisterInstance } from './instance-registry.js';\r\nimport { findFreePort } from './port-utils.js';\r\nimport { openBrowser } from './open-browser.js';\r\nimport { computeUsageCost, getCostRates } from './usage-cost.js';\r\nimport { createProviderHandlers } from './provider-handlers.js';\r\nimport { setupEvents } from './setup-events.js';\r\nimport { maskedKey, normalizeKeys } from './provider-keys.js';\r\nimport { send, broadcast, sendResult, errMessage, generateAuthToken } from './ws-utils.js';\r\nimport { estimateContextBreakdown } from './token-estimator.js';\r\n\r\n// Re-export types — shared message shapes and options used by both the\r\n// standalone server and the CLI's `--webui` embedded mode.\r\nexport type { WebUIOptions, BackendServices } from './types.js';\r\nexport type { WSServerMessage, WSClientMessage, ConnectedClient } from './types.js';\r\n\r\n// Re-export the static-serve + multi-instance building blocks so other packages\r\n// (the CLI's `--webui` mode) can serve the same React frontend, inject the live\r\n// WS port, pick free ports, and register in the shared instance registry —\r\n// without duplicating any of that logic.\r\nexport { createHttpServer, buildCspHeader, injectWsPort } from './http-server.js';\r\nexport { findFreePort, isPortFree } from './port-utils.js';\r\nexport { openBrowser, browserOpenCommand } from './open-browser.js';\r\nexport {\r\n registerInstance,\r\n unregisterInstance,\r\n listInstances,\r\n formatInstances,\r\n registryPath,\r\n defaultBaseDir,\r\n type WebUIInstanceRecord,\r\n} from './instance-registry.js';\r\n\r\n// WebSocket utilities shared with CLI\r\nexport {\r\n send,\r\n broadcast,\r\n sendResult,\r\n errMessage,\r\n generateAuthToken,\r\n} from './ws-utils.js';\r\n\r\n// WS auth — pure functions for verifying WebSocket connections\r\nexport {\r\n verifyClient,\r\n isLoopbackHostname,\r\n isLoopbackBind,\r\n tokenMatches,\r\n extractToken,\r\n hostHeaderOk,\r\n type VerifyClientInput,\r\n} from './ws-auth.js';\r\n\r\n// Provider/API-key record transforms (pure functions, testable without I/O)\r\nexport {\r\n normalizeKeys,\r\n writeKeysBack,\r\n maskedKey,\r\n upsertKey,\r\n deleteKey,\r\n setActiveKey,\r\n addProvider,\r\n removeProvider,\r\n type KeyOpResult,\r\n type ProvidersRecord,\r\n} from './provider-keys.js';\r\n\r\n// Provider config load/save (decrypt from / encrypt to global config)\r\nexport {\r\n loadSavedProviders,\r\n saveProviders,\r\n createProviderConfigIO,\r\n} from './provider-config-io.js';\r\n\r\n// Message + client shapes now live in ./types.ts (shared with the CLI's\r\n// embedded server). Imported here for internal use; re-exported above for\r\n// external consumers. The previous local copies shadowed these and made the\r\n// `Map<WebSocket, ConnectedClient>` passed to the extracted ws-utils helpers\r\n// nominally distinct, which TS rejected.\r\nimport type { ConnectedClient, WSClientMessage, WSServerMessage } from './types.js';\r\n\r\nexport async function startWebUI(\r\n opts: { wsPort?: number; wsHost?: string; open?: boolean } = {},\r\n): Promise<void> {\r\n const requestedWsPort = opts.wsPort ?? 3457;\r\n // Bind to loopback IP by default (not the string \"localhost\", which on some\r\n // hosts resolves to IPv6 ::1 and surprises older WS clients). Set WS_HOST or\r\n // pass opts.wsHost to override (e.g. \"0.0.0.0\" for LAN access).\r\n const wsHost = opts.wsHost ?? '127.0.0.1';\r\n const requestedHttpPort = Number.parseInt(process.env['PORT'] ?? '3456', 10);\r\n\r\n // Port resolution. Unless WEBUI_STRICT_PORT is set, auto-advance past any port\r\n // already taken by another instance so running `webui` several times \"just\r\n // works\" — the real ports are then stamped into the served HTML and the\r\n // instance registry. Strict mode keeps the requested ports and lets bind fail\r\n // loudly (useful behind a reverse proxy that expects fixed ports).\r\n const strictPort =\r\n process.env['WEBUI_STRICT_PORT'] === '1' || process.env['WEBUI_STRICT_PORT'] === 'true';\r\n let wsPort = requestedWsPort;\r\n let httpPort = requestedHttpPort;\r\n if (!strictPort) {\r\n // Resolve HTTP first, then WS excluding it, so successive instances land on\r\n // tidy adjacent pairs (3456/3457, 3458/3459, …) instead of interleaving.\r\n httpPort = await findFreePort(wsHost, requestedHttpPort);\r\n wsPort = await findFreePort(wsHost, requestedWsPort, { exclude: new Set([httpPort]) });\r\n if (httpPort !== requestedHttpPort) {\r\n console.warn(`[WebUI] HTTP port ${requestedHttpPort} in use → using ${httpPort}`);\r\n }\r\n if (wsPort !== requestedWsPort) {\r\n console.warn(`[WebUI] WS port ${requestedWsPort} in use → using ${wsPort}`);\r\n }\r\n }\r\n\r\n console.log('[WebUI] Starting backend services...');\r\n\r\n // Boot configuration\r\n const boot = await bootConfig();\r\n const { config: baseConfig, vault, globalConfigPath, projectRoot, wpaths, logger } = boot;\r\n let config = baseConfig;\r\n\r\n // Serialize concurrent config writes to prevent races between model.switch\r\n // and key.add/key.update handlers that both read-modify-write globalConfigPath.\r\n let configWriteLock: Promise<void> = Promise.resolve();\r\n\r\n console.log('[WebUI] Config loaded:', config.provider ?? '(none)', '/', config.model ?? '(none)');\r\n\r\n // If no active provider is set but there are saved providers, pick the first one.\r\n // This handles configs written in older formats or by external tools.\r\n // Guard against config.providers being a string or other non-object value\r\n // (e.g., from a corrupted config or YAML parser misreading the value).\r\n if (\r\n !config.provider &&\r\n config.providers &&\r\n typeof config.providers === 'object' &&\r\n config.providers !== null &&\r\n !Array.isArray(config.providers) &&\r\n Object.keys(config.providers).length > 0\r\n ) {\r\n const firstKey = Object.keys(config.providers)[0]!;\r\n config = patchConfig(config, { provider: firstKey });\r\n console.log('[WebUI] No active provider — auto-selected:', firstKey);\r\n }\r\n\r\n // If still no provider, the frontend will show a no-provider welcome screen.\r\n // We still start the HTTP/WS servers so the user can configure via the UI.\r\n const needsProvider = !config.provider || !config.model;\r\n\r\n // ModelsRegistry\r\n const modelsRegistry = new DefaultModelsRegistry({\r\n cacheFile: wpaths.modelsCache,\r\n ttlSeconds: 24 * 3600,\r\n });\r\n\r\n // Container via shared factory\r\n const container = createDefaultContainer({ config, wpaths, logger, modelsRegistry });\r\n const configStore = container.resolve(TOKENS.ConfigStore);\r\n\r\n // Provider registry\r\n const providerRegistry = new ProviderRegistry();\r\n try {\r\n const factories = await buildProviderFactoriesFromRegistry({\r\n registry: modelsRegistry,\r\n log: logger,\r\n });\r\n for (const f of factories) providerRegistry.register(f);\r\n console.log('[WebUI] Provider registry loaded:', providerRegistry.list().length, 'providers');\r\n } catch (err) {\r\n console.warn('[WebUI] Failed to load provider registry:', err);\r\n }\r\n\r\n // Tool registry\r\n const toolRegistry = new ToolRegistry();\r\n toolRegistry.registerAllOrThrow([...(builtinToolsPack.tools ?? [])], builtinToolsPack.name);\r\n\r\n // Memory tools\r\n const memoryStore = new DefaultMemoryStore({ paths: wpaths });\r\n if (config.features.memory) {\r\n toolRegistry.register(rememberTool(memoryStore));\r\n toolRegistry.register(forgetTool(memoryStore));\r\n }\r\n console.log('[WebUI] Tool registry loaded:', toolRegistry.list().length, 'tools');\r\n\r\n // Event bus\r\n const events = new EventBus();\r\n events.setLogger(logger);\r\n\r\n // Session store\r\n const sessionStore = new DefaultSessionStore({ dir: wpaths.projectSessions });\r\n // Session reader — same on-disk store, read-only access. Used by the\r\n // collaboration handler to replay the last N events to late-joining\r\n // observers (Phase 1.5 of idea #13).\r\n const sessionReader = new DefaultSessionReader({ store: sessionStore });\r\n // Annotations store — sidecar files for collaboration notes (Phase 2\r\n // of idea #13). Living under `projectSessions` so all per-session\r\n // data is colocated and travels with the project.\r\n const annotationsStore = new AnnotationsStore({ dir: wpaths.projectSessions });\r\n let session = await sessionStore.create({\r\n id: '',\r\n title: '',\r\n model: config.model,\r\n provider: config.provider,\r\n });\r\n // Wall-clock when the *current* session started. Updated on /new and on\r\n // /resume so /stats can report accurate elapsed time per the active\r\n // session, not the daemon process uptime.\r\n let sessionStartedAt = Date.now();\r\n console.log('[WebUI] Session created:', session.id);\r\n\r\n // Token counter\r\n const tokenCounter = new DefaultTokenCounter({\r\n registry: modelsRegistry,\r\n providerId: config.provider,\r\n });\r\n\r\n // Mode store\r\n const modeStore = new DefaultModeStore({ directory: wpaths.configDir });\r\n const activeMode = await modeStore.getActiveMode();\r\n let modeId = activeMode?.id ?? 'default';\r\n const modePrompt = activeMode?.prompt ?? '';\r\n\r\n // System prompt builder\r\n const resolvedModel = await modelsRegistry.getModel(config.provider, config.model);\r\n const modelCapabilities = resolvedModel?.capabilities\r\n ? {\r\n maxContextTokens: resolvedModel.capabilities.maxContext,\r\n supportsTools: resolvedModel.capabilities.tools,\r\n supportsVision: resolvedModel.capabilities.vision,\r\n supportsReasoning: resolvedModel.capabilities.reasoning,\r\n }\r\n : undefined;\r\n\r\n const skillLoader = config.features.skills\r\n ? new DefaultSkillLoader({ paths: wpaths })\r\n : undefined;\r\n const systemPromptBuilder = new DefaultSystemPromptBuilder({\r\n memoryStore,\r\n skillLoader,\r\n modeStore,\r\n modeId,\r\n modePrompt,\r\n modelCapabilities,\r\n });\r\n\r\n const systemPrompt = await systemPromptBuilder.build({\r\n cwd: projectRoot,\r\n projectRoot,\r\n tools: toolRegistry.list(),\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n\r\n // Build provider (only if provider is configured)\r\n let provider: ReturnType<ProviderRegistry['create']>;\r\n if (!needsProvider) {\r\n const providerConfig = config.providers?.[config.provider] ?? {\r\n type: config.provider,\r\n apiKey: config.apiKey,\r\n baseUrl: config.baseUrl,\r\n };\r\n try {\r\n const cfgWithType = { ...providerConfig, type: config.provider };\r\n if (config.features.modelsRegistry && providerRegistry.has(config.provider)) {\r\n provider = providerRegistry.create(cfgWithType);\r\n } else {\r\n provider = makeProviderFromConfig(config.provider, cfgWithType);\r\n }\r\n } catch (err) {\r\n console.error('[WebUI] Failed to create provider:', err);\r\n throw err;\r\n }\r\n } else {\r\n // No provider is actively selected, but saved providers exist.\r\n // Re-read the config to find one with a usable encrypted API key\r\n // and create a real provider from it (the vault is already initialized).\r\n const savedProviders = config.providers ?? {};\r\n const firstKey = Object.keys(savedProviders)[0];\r\n if (firstKey) {\r\n const firstProvider = savedProviders[firstKey]!;\r\n try {\r\n provider = makeProviderFromConfig(firstKey, {\r\n ...firstProvider,\r\n type: firstKey,\r\n family: firstProvider.family,\r\n apiKey: firstProvider.apiKey,\r\n });\r\n console.log('[WebUI] Using saved provider:', firstKey);\r\n } catch (err) {\r\n console.error('[WebUI] Could not create provider stub:', err);\r\n throw err;\r\n }\r\n } else {\r\n throw new Error(\r\n 'No provider configured. Run `wrongstack init` first, or configure via the WebUI.',\r\n );\r\n }\r\n }\r\n\r\n // Context\r\n const context = new Context({\r\n systemPrompt,\r\n provider,\r\n session,\r\n signal: new AbortController().signal,\r\n tokenCounter,\r\n cwd: projectRoot,\r\n projectRoot,\r\n model: config.model,\r\n });\r\n const initialContextPolicy = resolveContextWindowPolicy(config.context);\r\n context.meta['contextWindowMode'] = initialContextPolicy.id;\r\n context.meta['contextWindowPolicy'] = initialContextPolicy;\r\n\r\n // Pipelines\r\n const pipelines = createDefaultPipelines();\r\n // Collaboration bus — process-singleton pause/resume signal. The\r\n // middleware below hooks it into the toolCall pipeline so a\r\n // `controller` participant can halt the agent before the next tool\r\n // call (Phase 3 of idea #13). The same bus instance is shared with\r\n // the CollaborationWebSocketHandler so client pause/resume requests\r\n // are routed to the kernel.\r\n const collabBus = new CollaborationBus();\r\n // prepend (not use) — the pause check must run first, before any\r\n // permission/retry middleware that would otherwise proceed.\r\n const collabPause = collabPauseMiddleware(collabBus, { logger });\r\n Object.defineProperty(collabPause, 'name', { value: 'collab-pause' });\r\n pipelines.toolCall.prepend(collabPause as never);\r\n // Phase 4 — collab-inject. Installed AFTER collab-pause so the\r\n // controller can pause + inject before the next tool runs. The\r\n // middleware checks the bus's injection queue and splices a\r\n // synthetic tool_result when a controller has queued one for\r\n // the current toolUse.id.\r\n const collabInject = collabInjectMiddleware(collabBus, { logger });\r\n Object.defineProperty(collabInject, 'name', { value: 'collab-inject' });\r\n pipelines.toolCall.prepend(collabInject as never);\r\n // Compactor\r\n const compactor = new HybridCompactor({\r\n preserveK: config.context?.preserveK ?? 20,\r\n eliseThreshold: config.context?.eliseThreshold ?? 0.7,\r\n });\r\n\r\n // Auto-compaction\r\n let autoCompactor: AutoCompactionMiddleware | undefined;\r\n if (config.context?.autoCompact !== false) {\r\n // Priority: explicit override → models.dev per-model window → family default.\r\n // The catalog lookup matters for openai-compatible providers (OpenRouter,\r\n // Groq, …) whose family default is 0; without it auto-compaction would be\r\n // disabled even though the model has a real published window. Mirrors\r\n // updateAutoCompactionMaxContext below.\r\n let effectiveMaxContext = config.context?.effectiveMaxContext ?? 0;\r\n if (!effectiveMaxContext) {\r\n try {\r\n const m = await modelsRegistry.getModel(provider.id, context.model);\r\n effectiveMaxContext = m?.capabilities?.maxContext ?? 0;\r\n } catch {\r\n // best-effort: fall through to provider capability\r\n }\r\n }\r\n if (!effectiveMaxContext) effectiveMaxContext = provider.capabilities.maxContext;\r\n autoCompactor = new AutoCompactionMiddleware(\r\n compactor,\r\n effectiveMaxContext,\r\n (ctx) => estimateRequestTokensCalibrated(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total,\r\n {\r\n warn: initialContextPolicy.thresholds.warn,\r\n soft: initialContextPolicy.thresholds.soft,\r\n hard: initialContextPolicy.thresholds.hard,\r\n },\r\n {\r\n events,\r\n aggressiveOn: initialContextPolicy.aggressiveOn,\r\n policyProvider: (ctx) => {\r\n const policy = ctx.meta['contextWindowPolicy'];\r\n return policy && typeof policy === 'object'\r\n ? (policy as ReturnType<typeof resolveContextWindowPolicy>)\r\n : initialContextPolicy;\r\n },\r\n },\r\n );\r\n pipelines.contextWindow.use({ name: 'AutoCompaction', handler: autoCompactor.handler() });\r\n }\r\n\r\n /** Refresh AutoCompactionMiddleware denominator when the active model changes. */\r\n async function updateAutoCompactionMaxContext(newProvider: Provider): Promise<void> {\r\n if (!autoCompactor) return;\r\n let newMaxContext = config.context?.effectiveMaxContext ?? newProvider.capabilities.maxContext;\r\n try {\r\n const m = await modelsRegistry.getModel(newProvider.id, context.model);\r\n newMaxContext = m?.capabilities?.maxContext ?? newMaxContext;\r\n } catch {\r\n // best-effort: use provider capability\r\n }\r\n autoCompactor.setMaxContext(newMaxContext);\r\n }\r\n\r\n // Agent\r\n const secretScrubber = container.resolve(TOKENS.SecretScrubber);\r\n const renderer = container.has(TOKENS.Renderer)\r\n ? container.resolve(TOKENS.Renderer)\r\n : undefined;\r\n const toolExecutor = new ToolExecutor(toolRegistry, {\r\n permissionPolicy: container.resolve(TOKENS.PermissionPolicy),\r\n secretScrubber,\r\n renderer,\r\n events,\r\n confirmAwaiter: undefined,\r\n iterationTimeoutMs: config.tools?.iterationTimeoutMs ?? DEFAULT_TOOLS_CONFIG.iterationTimeoutMs,\r\n perIterationOutputCapBytes: config.tools?.perIterationOutputCapBytes ?? DEFAULT_TOOLS_CONFIG.perIterationOutputCapBytes,\r\n tracer: undefined,\r\n });\r\n\r\n const agent = new Agent({\r\n container,\r\n tools: toolRegistry,\r\n providers: providerRegistry,\r\n events,\r\n pipelines,\r\n context,\r\n maxIterations: config.tools?.maxIterations ?? DEFAULT_TOOLS_CONFIG.maxIterations,\r\n iterationTimeoutMs: config.tools?.iterationTimeoutMs ?? DEFAULT_TOOLS_CONFIG.iterationTimeoutMs,\r\n executionStrategy: config.tools?.defaultExecutionStrategy ?? DEFAULT_TOOLS_CONFIG.defaultExecutionStrategy,\r\n perIterationOutputCapBytes: config.tools?.perIterationOutputCapBytes ?? DEFAULT_TOOLS_CONFIG.perIterationOutputCapBytes,\r\n confirmAwaiter: undefined,\r\n toolExecutor,\r\n });\r\n console.log('[WebUI] Agent initialized');\r\n\r\n // AutoPhase handler — manages AutoPhaseRunner lifecycle via WS messages.\r\n // Stored under the per-project autophase dir (not the shared SDD task-graphs).\r\n const autoPhaseHandler = new AutoPhaseWebSocketHandler(\r\n agent,\r\n context,\r\n logger,\r\n wpaths.projectAutophase,\r\n events,\r\n projectRoot,\r\n );\r\n\r\n // Worktree handler — subscribes to the shared EventBus `worktree.*` events\r\n // and streams live swim-lane / DAG state to connected clients.\r\n const worktreeHandler = new WorktreeWebSocketHandler(events, logger);\r\n\r\n // Collaboration handler — Phase 1 of idea #13. Lets a second client\r\n // (e.g. a senior dev) join an active agent run as a read-only\r\n // observer and watch a live mirror of kernel events. Annotated and\r\n // controller roles land in Phase 2/3. The session reader enables\r\n // replay-on-join for late observers.\r\n const collabHandler = new CollaborationWebSocketHandler(\r\n events,\r\n logger,\r\n sessionReader,\r\n annotationsStore,\r\n collabBus,\r\n );\r\n\r\n // Helper: build the rich session.start payload from current runtime state.\r\n // Centralised so initial connect, post-/new, and post-model.switch all\r\n // broadcast the same shape — frontend treats this as the single source of\r\n // truth for everything in the status bar (model, context window, project).\r\n async function sessionStartPayload(): Promise<{\r\n sessionId: string;\r\n model: string;\r\n provider: string;\r\n maxContext: number;\r\n /** USD per 1M input tokens (0 if unknown / free). */\r\n inputCost: number;\r\n /** USD per 1M output tokens. */\r\n outputCost: number;\r\n /** USD per 1M cache-read tokens. */\r\n cacheReadCost: number;\r\n projectName: string;\r\n cwd: string;\r\n mode: string;\r\n contextMode: string;\r\n wsToken: string;\r\n }> {\r\n let maxContext = 0;\r\n let inputCost = 0;\r\n let outputCost = 0;\r\n let cacheReadCost = 0;\r\n try {\r\n const m = await modelsRegistry.getModel(config.provider, config.model);\r\n maxContext = m?.capabilities?.maxContext ?? 0;\r\n // models.dev pricing is dollars per 1M tokens; some providers omit the\r\n // field for free/unmetered plans (e.g. minimax-coding-plan) — in that\r\n // case we report 0 and the cost chip just stays at $0.\r\n const rates = getCostRates(m);\r\n inputCost = rates.input;\r\n outputCost = rates.output;\r\n cacheReadCost = rates.cacheRead;\r\n } catch {\r\n // best-effort\r\n }\r\n return {\r\n sessionId: session.id,\r\n model: config.model,\r\n provider: config.provider,\r\n maxContext,\r\n inputCost,\r\n outputCost,\r\n cacheReadCost,\r\n projectName: path.basename(projectRoot) || projectRoot,\r\n cwd: projectRoot,\r\n mode: modeId,\r\n contextMode: String(context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID),\r\n wsToken,\r\n };\r\n }\r\n\r\n // WebSocket server(s).\r\n //\r\n // When the user keeps the default loopback bind (127.0.0.1), we ALSO open a\r\n // second listener on ::1 (IPv6 loopback). Reason: Chrome/Edge on Windows\r\n // resolve `localhost` to `[::1]` before `127.0.0.1`, so a single v4-only\r\n // bind causes \"ws disconnect hep\" — clients hammer the v6 socket, get\r\n // ECONNREFUSED, fall back to v4 inconsistently. Listening on both v4 and v6\r\n // loopback keeps the connection scope \"this machine only\" while removing\r\n // the resolution-order coin flip.\r\n //\r\n // When the user explicitly sets WS_HOST (e.g. 0.0.0.0 or a LAN IP), we\r\n // respect that choice exactly and don't add a second listener.\r\n // Generate a random WS auth token so only callers that know the token\r\n // can connect. Printed to console on startup; the frontend reads it from\r\n // the URL query param `?token=...`. Without a token, any client on the\r\n // network can connect and send `user_message`/`key.add`/`model.switch`.\r\n const wsToken = generateAuthToken();\r\n // Token is sent to clients via session.start payload — log only a masked\r\n // prefix so operators can correlate without leaking the full secret.\r\n console.log(`[WebUI] WS auth token: ${wsToken.slice(0, 4)}…${wsToken.slice(-4)} (masked)`);\r\n\r\n // CSWSH guard + token auth: when the user exposes the socket beyond loopback,\r\n // require the shared token; loopback connections bootstrap without one. The\r\n // policy (DNS-rebinding Host guard, constant-time token compare, loopback\r\n // bootstrap) lives in ./ws-auth.ts as pure functions — this closure just\r\n // pulls the relevant fields off the incoming request and delegates.\r\n const verifyClient = (info: {\r\n origin: string;\r\n secure: boolean;\r\n req: import('node:http').IncomingMessage;\r\n }) =>\r\n verifyWsClient({\r\n origin: info.origin,\r\n url: info.req.url ?? '',\r\n hostHeader: info.req.headers.host,\r\n remoteAddress: info.req.socket.remoteAddress,\r\n wsHost,\r\n expectedToken: wsToken,\r\n });\r\n // Cap inbound frame size (8 MiB) so a single oversized message can't exhaust\r\n // memory. Agent messages are small; large pastes/attachments stay well under.\r\n const WS_MAX_PAYLOAD = 8 * 1024 * 1024;\r\n const wssPrimary = new WebSocketServer({\r\n port: wsPort,\r\n host: wsHost,\r\n verifyClient,\r\n maxPayload: WS_MAX_PAYLOAD,\r\n } as ConstructorParameters<typeof WebSocketServer>[0]);\r\n const wssSecondary =\r\n wsHost === '127.0.0.1'\r\n ? new WebSocketServer({\r\n port: wsPort,\r\n host: '::1',\r\n verifyClient,\r\n maxPayload: WS_MAX_PAYLOAD,\r\n } as ConstructorParameters<typeof WebSocketServer>[0])\r\n : null;\r\n const clients = new Map<WebSocket, ConnectedClient>();\r\n\r\n // Per-connection message rate limiting: 60 messages per 60-second window.\r\n // Exceeding clients are temporarily blocked to prevent flooding.\r\n // Uses sessionId as the key once connected, falling back to ws for\r\n // pre-auth messages — prevents connection-reuse bypass.\r\n // Rate limit OFF by default (counted pings/list calls too and tripped during\r\n // normal use). Opt in via WEBUI_RATE_LIMIT=<messages-per-60s> for LAN exposure.\r\n const RATE_LIMIT_MESSAGES = Number.parseInt(process.env['WEBUI_RATE_LIMIT'] ?? '0', 10);\r\n const RATE_LIMIT_WINDOW_MS = 60_000;\r\n const rateLimits = new Map<string, { count: number; resetAt: number }>();\r\n\r\n function checkRateLimit(ws: WebSocket, client: ConnectedClient): boolean {\r\n if (RATE_LIMIT_MESSAGES <= 0) return true; // disabled\r\n const now = Date.now();\r\n // Prefer the per-client authenticated sessionId; fall back to the\r\n // WebSocket identity for pre-auth messages before session.start.\r\n const key = client.sessionId ?? String(ws);\r\n const limit = rateLimits.get(key);\r\n if (!limit || now > limit.resetAt) {\r\n rateLimits.set(key, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });\r\n return true;\r\n }\r\n if (limit.count >= RATE_LIMIT_MESSAGES) return false;\r\n limit.count++;\r\n return true;\r\n }\r\n\r\n /** Holds the AbortController for the currently in-flight agent.run().\r\n * Non-null while the agent is running; guarded at the user_message\r\n * handler to prevent concurrent runs that would corrupt shared state\r\n * (context, agent, tokenCounter). A second user_message while running\r\n * is answered with an inline error instead of being queued — the\r\n * caller should wait for run.result. */\r\n let runLock: AbortController | null = null;\r\n\r\n console.log(\r\n `[WebUI] WebSocket server running on ws://${wsHost}:${wsPort}` +\r\n (wssSecondary ? ` (and ws://[::1]:${wsPort})` : ''),\r\n );\r\n\r\n // Pending permission confirmations. When the agent emits\r\n // tool.confirm_needed, we store the resolve function here keyed by\r\n // toolUseId. When the client sends tool.confirm_result back, we look\r\n // it up and resolve — unblocking the agent loop.\r\n const pendingConfirms = new Map<string, (d: 'yes' | 'no' | 'always' | 'deny') => void>();\r\n\r\n const handleConnection = (ws: WebSocket): void => {\r\n const client: ConnectedClient = { ws, sessionId: session.id, connectedAt: Date.now() };\r\n clients.set(ws, client);\r\n console.log('[WebUI] Client connected, total:', clients.size);\r\n\r\n void sessionStartPayload().then((payload) => {\r\n send(ws, { type: 'session.start', payload });\r\n });\r\n\r\n // Register this client with the AutoPhase handler so it receives phase events\r\n autoPhaseHandler.addClient(ws);\r\n // …and the worktree handler for live isolation lanes.\r\n worktreeHandler.addClient(ws);\r\n // …and the collaboration handler for read-only session observation.\r\n collabHandler.addClient(ws);\r\n\r\n ws.on('message', async (data) => {\r\n if (!checkRateLimit(ws, client)) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'rate_limit',\r\n message: 'Too many messages. Please wait before sending more.',\r\n },\r\n });\r\n return;\r\n }\r\n try {\r\n // Prototype pollution guard: reject messages whose root-level payload\r\n // contains __proto__, constructor, or prototype keys. These could\r\n // cause prototype pollution via Object.assign({}, payload) or\r\n // spread {...payload}. The top-level check below catches the\r\n // dangerous keys; nested payload sub-objects are low-risk since\r\n // handlers don't do deep property merges.\r\n const rawObj = JSON.parse(data.toString());\r\n if (typeof rawObj === 'object' && rawObj !== null) {\r\n const obj = rawObj as Record<string, unknown>;\r\n if ('__proto__' in obj || 'constructor' in obj || 'prototype' in obj) {\r\n send(ws, { type: 'error', payload: { phase: 'parse', message: 'Invalid message object' } });\r\n } else {\r\n await handleMessage(ws, client, rawObj as WSClientMessage);\r\n }\r\n } else {\r\n // Non-object JSON (array, string, number…) — pass through\r\n await handleMessage(ws, client, rawObj as unknown as WSClientMessage);\r\n }\r\n } catch (err) {\r\n console.error('[WebUI] Failed to parse message', err);\r\n }\r\n });\r\n\r\n ws.on('close', () => {\r\n clients.delete(ws);\r\n rateLimits.delete(String(ws));\r\n console.log('[WebUI] Client disconnected, total:', clients.size);\r\n // If the client disconnects while a permission prompt is pending,\r\n // resolve all pending confirms with 'no' so the agent loop doesn't\r\n // hang forever waiting for a response that will never come.\r\n if (pendingConfirms.size > 0) {\r\n for (const [id, resolve] of pendingConfirms) {\r\n resolve('no');\r\n pendingConfirms.delete(id);\r\n }\r\n }\r\n });\r\n\r\n ws.on('error', (err) => {\r\n // Without this handler an errored socket would crash the process.\r\n console.warn('[WebUI] Client socket error:', err.message);\r\n });\r\n };\r\n\r\n let eventsArmed = false;\r\n const armOnce = (label: string): void => {\r\n if (eventsArmed) return;\r\n eventsArmed = true;\r\n console.log(`[WebUI] Backend ready (${label})`);\r\n setupEvents({ events, broadcast, clients, config, context, pendingConfirms });\r\n };\r\n\r\n wssPrimary.on('listening', () => armOnce(`${wsHost}:${wsPort}`));\r\n wssPrimary.on('connection', handleConnection);\r\n wssPrimary.on('error', (err) => {\r\n console.error(`[WebUI] Primary WS server error (${wsHost}):`, err);\r\n });\r\n\r\n if (wssSecondary) {\r\n wssSecondary.on('listening', () => armOnce(`::1:${wsPort}`));\r\n wssSecondary.on('connection', handleConnection);\r\n wssSecondary.on('error', (err: NodeJS.ErrnoException) => {\r\n // Best-effort secondary: if IPv6 loopback isn't available on this host\r\n // (e.g. disabled in OS), just log and continue. Primary v4 is enough.\r\n if (err.code === 'EAFNOSUPPORT' || err.code === 'EADDRNOTAVAIL') {\r\n console.warn('[WebUI] IPv6 loopback not available, v4-only:', err.code);\r\n } else {\r\n console.error('[WebUI] Secondary WS server error (::1):', err);\r\n }\r\n });\r\n }\r\n\r\n async function handleMessage(\r\n ws: WebSocket,\r\n _client: ConnectedClient,\r\n msg: WSClientMessage,\r\n ): Promise<void> {\r\n switch (msg.type) {\r\n // Collaboration messages short-circuit the user/agent flow.\r\n // They don't touch runLock, the agent loop, or the message queue —\r\n // they're pure transport for the live observer mirror.\r\n case 'collab.join':\r\n case 'collab.leave':\r\n case 'collab.annotate':\r\n case 'collab.resolve': {\r\n collabHandler.handleMessage(ws, msg as { type: string; payload?: unknown });\r\n return;\r\n }\r\n case 'user_message': {\r\n const content = (msg as { payload: { content: string } }).payload.content;\r\n\r\n // Guard against concurrent agent runs — a second user_message while\r\n // the agent is already processing would kick off two agent.run()\r\n // calls on the same shared context/agent, leading to corrupted\r\n // state (duplicate tool bubbles, mixed text_delta streams, token\r\n // counter undercount). Reject with an inline error; the frontend\r\n // should wait for run.result before sending the next message.\r\n if (runLock) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'user_message',\r\n message: 'Agent is already processing a request. Wait for the current run to finish.',\r\n },\r\n });\r\n break;\r\n }\r\n\r\n runLock = new AbortController();\r\n // Capture so the finally block only clears its own lock — a\r\n // second race could set a new runLock between await and finally.\r\n const thisRun = runLock;\r\n\r\n try {\r\n const result = await agent.run(content, { signal: thisRun.signal });\r\n send(ws, {\r\n type: 'run.result',\r\n payload: {\r\n status: result.status,\r\n iterations: result.iterations,\r\n finalText: result.finalText,\r\n error: result.error\r\n ? {\r\n code: result.error.code,\r\n message: result.error.message,\r\n recoverable: result.error.recoverable,\r\n }\r\n : undefined,\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'agent.run',\r\n message: errMessage(err),\r\n },\r\n });\r\n } finally {\r\n // Only clear runLock if it's still ours — otherwise we'd wipe a\r\n // newer run's controller set after we returned.\r\n if (runLock === thisRun) {\r\n runLock = null;\r\n }\r\n }\r\n break;\r\n }\r\n\r\n case 'tool.confirm_result': {\r\n const { id, decision } = (msg as { payload: { id: string; decision: 'yes' | 'no' | 'always' | 'deny' } }).payload;\r\n const resolve = pendingConfirms.get(id);\r\n if (resolve) {\r\n pendingConfirms.delete(id);\r\n resolve(decision);\r\n }\r\n break;\r\n }\r\n\r\n case 'abort':\r\n runLock?.abort();\r\n broadcast(clients, { type: 'error', payload: { phase: 'abort', message: 'User aborted' } });\r\n break;\r\n\r\n case 'ping':\r\n send(ws, { type: 'pong', payload: {} });\r\n break;\r\n\r\n case 'session.new': {\r\n // Truly fresh chat: new on-disk session AND reset every piece of\r\n // in-memory state that survived (messages history, todos, read-file\r\n // tracking, token totals). Otherwise the model still sees the prior\r\n // turns even though the UI looks empty — that's the \"ghost context\"\r\n // bug. After this, the next user message goes out as turn 1 with no\r\n // prior history.\r\n session = await sessionStore.create({\r\n id: '',\r\n title: '',\r\n model: config.model,\r\n provider: config.provider,\r\n });\r\n context.session = session;\r\n context.state.replaceMessages([]);\r\n context.state.replaceTodos([]);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n sessionStartedAt = Date.now();\r\n broadcast(clients, { type: 'session.start', payload: await sessionStartPayload() });\r\n break;\r\n }\r\n\r\n case 'context.clear': {\r\n // Same in-memory wipe as session.new, but reuses the current session\r\n // file (so the JSONL still has the history for audit / replay). The\r\n // user wants a clean slate on the model side; the disk record stays.\r\n context.state.replaceMessages([]);\r\n context.state.replaceTodos([]);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n sendResult(ws, true, 'Context cleared');\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: { ...(await sessionStartPayload()), reset: true },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.debug': {\r\n // Per-section token estimate so users can see what's actually eating\r\n // the context window. The breakdown maths lives in ./token-estimator.ts\r\n // (4-chars-per-token heuristic); we layer the active mode/policy on top.\r\n const breakdown = estimateContextBreakdown({\r\n systemPrompt: context.systemPrompt,\r\n tools: toolRegistry.list(),\r\n messages: context.messages,\r\n });\r\n send(ws, {\r\n type: 'context.debug',\r\n payload: {\r\n ...breakdown,\r\n mode: context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID,\r\n policy: context.meta['contextWindowPolicy'],\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.compact': {\r\n const aggressive = !!(msg as { payload?: { aggressive?: boolean } }).payload?.aggressive;\r\n try {\r\n const report = await compactor.compact(context, { aggressive });\r\n send(ws, {\r\n type: 'context.compacted',\r\n payload: {\r\n before: report.before,\r\n after: report.after,\r\n saved: Math.max(0, report.before - report.after),\r\n reductions: report.reductions,\r\n repaired: report.repaired,\r\n },\r\n });\r\n sendResult(\r\n ws,\r\n true,\r\n `Compacted: ${report.before} → ${report.after} tokens (saved ~${Math.max(0, report.before - report.after)})`,\r\n );\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'context.repair': {\r\n const beforeMessages = context.messages.length;\r\n const repaired = repairToolUseAdjacency(context.messages);\r\n if (repaired.report.changed) {\r\n context.state.replaceMessages(repaired.messages);\r\n }\r\n const payload = {\r\n removedToolUses: repaired.report.removedToolUses,\r\n removedToolResults: repaired.report.removedToolResults,\r\n removedMessages: repaired.report.removedMessages,\r\n beforeMessages,\r\n afterMessages: context.messages.length,\r\n };\r\n broadcast(clients, { type: 'context.repaired', payload });\r\n const removed =\r\n payload.removedToolUses.length +\r\n payload.removedToolResults.length +\r\n payload.removedMessages;\r\n sendResult(\r\n ws,\r\n true,\r\n removed > 0\r\n ? `Context repaired: removed ${removed} orphan protocol item(s)`\r\n : 'Context repair found no orphan protocol blocks',\r\n );\r\n break;\r\n }\r\n\r\n case 'context.modes.list': {\r\n const active = String(context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID);\r\n send(ws, {\r\n type: 'context.modes.list',\r\n payload: {\r\n activeId: active,\r\n modes: listContextWindowModes().map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n description: m.description,\r\n isActive: m.id === active,\r\n thresholds: m.thresholds,\r\n preserveK: m.preserveK,\r\n eliseThreshold: m.eliseThreshold,\r\n })),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.mode.switch': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n const policy = resolveContextWindowPolicy({}, id);\r\n if (policy.id !== id) {\r\n sendResult(ws, false, `Unknown context mode \"${id}\"`);\r\n break;\r\n }\r\n context.meta['contextWindowMode'] = policy.id;\r\n context.meta['contextWindowPolicy'] = policy;\r\n sendResult(ws, true, `Context mode switched to ${policy.id}`);\r\n broadcast(clients, {\r\n type: 'context.mode.changed',\r\n payload: { id: policy.id, name: policy.name, policy },\r\n });\r\n break;\r\n }\r\n\r\n case 'providers.list': {\r\n const providers = await modelsRegistry.listProviders();\r\n // \"Configured\" should mean *any* working credential, not just env vars.\r\n // Users register keys with `wstack auth`, which writes apiKey/apiKeys\r\n // into config.providers[<id>] — those are decrypted in memory here.\r\n const savedIds = new Set(Object.keys(config.providers ?? {}));\r\n send(ws, {\r\n type: 'provider.catalog',\r\n payload: {\r\n providers: providers.map((p) => ({\r\n id: p.id,\r\n name: p.name,\r\n family: p.family,\r\n apiBase: p.apiBase,\r\n envVars: p.envVars,\r\n modelCount: p.models.length,\r\n hasApiKey: savedIds.has(p.id) || p.envVars.some((v) => !!process.env[v]),\r\n })),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'providers.saved': {\r\n const saved = await providerHandlers.loadConfigProviders();\r\n send(ws, {\r\n type: 'providers.saved',\r\n payload: {\r\n providers: Object.entries(saved).map(([id, cfg]) => {\r\n const keys = normalizeKeys(cfg);\r\n return {\r\n id,\r\n family: cfg.family ?? id,\r\n baseUrl: cfg.baseUrl,\r\n apiKeys: keys.map((k) => ({\r\n label: k.label,\r\n maskedKey: maskedKey(k.apiKey),\r\n isActive: k.label === cfg.activeKey,\r\n createdAt: k.createdAt,\r\n })),\r\n };\r\n }),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'provider.models': {\r\n const providerId = (msg as { payload: { providerId: string } }).payload.providerId;\r\n const provider = await modelsRegistry.getProvider(providerId);\r\n if (provider) {\r\n send(ws, {\r\n type: 'provider.models',\r\n payload: {\r\n provider: providerId,\r\n models: provider.models.map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n releaseDate: (m as { release_date?: string }).release_date,\r\n contextWindow: (m as { limit?: { context?: number } }).limit?.context,\r\n inputCost: (m as { cost?: { input?: number } }).cost?.input,\r\n outputCost: (m as { cost?: { output?: number } }).cost?.output,\r\n capabilities: [\r\n ...((m as { tool_call?: boolean }).tool_call ? ['tools'] : []),\r\n ...((m as { reasoning?: boolean }).reasoning ? ['reasoning'] : []),\r\n ],\r\n })),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'model.switch': {\r\n const { provider: newProvider, model: newModel } = (\r\n msg as { payload: { provider: string; model: string } }\r\n ).payload;\r\n try {\r\n // Update config\r\n config = patchConfig(config, { provider: newProvider, model: newModel });\r\n configStore.update({ provider: newProvider, model: newModel });\r\n context.model = newModel;\r\n\r\n // Create new provider instance — fail loudly if the user picks a\r\n // provider with no creds rather than silently keeping the old one.\r\n const providerCfg = config.providers?.[newProvider] ?? { type: newProvider };\r\n const newProv = providerRegistry.has(newProvider)\r\n ? providerRegistry.create({ ...providerCfg, type: newProvider })\r\n : makeProviderFromConfig(newProvider, providerCfg);\r\n context.provider = newProv;\r\n\r\n // Update AutoCompactionMiddleware with the new model's maxContext so\r\n // backend threshold triggers (warn/soft/hard) use the correct denominator.\r\n // sessionStartPayload is called below (after this block) and uses\r\n // the new provider for its modelsRegistry lookup.\r\n updateAutoCompactionMaxContext?.(newProv);\r\n\r\n // Persist to global config file\r\n try {\r\n configWriteLock = configWriteLock.then(async () => {\r\n const raw = await fs.readFile(globalConfigPath, 'utf8');\r\n const parsed = JSON.parse(raw);\r\n parsed.provider = newProvider;\r\n parsed.model = newModel;\r\n await atomicWrite(globalConfigPath, JSON.stringify(parsed, null, 2));\r\n });\r\n await configWriteLock;\r\n } catch (err) {\r\n console.warn('[WebUI] Failed to save config:', err);\r\n }\r\n\r\n // Toast for the SettingsPanel\r\n send(ws, {\r\n type: 'key.operation_result',\r\n payload: { success: true, message: `Switched to ${newProvider} / ${newModel}` },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'key.operation_result',\r\n payload: {\r\n success: false,\r\n message: `Switch failed: ${errMessage(err)}`,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n broadcast(clients, { type: 'session.start', payload: await sessionStartPayload() });\r\n break;\r\n }\r\n\r\n case 'key.add':\r\n case 'key.update': {\r\n const { providerId, label, apiKey } = (\r\n msg as { payload: { providerId: string; label: string; apiKey: string } }\r\n ).payload;\r\n await providerHandlers.handleKeyUpsert(ws, providerId, label, apiKey);\r\n break;\r\n }\r\n\r\n case 'key.delete': {\r\n const { providerId, label } = (msg as { payload: { providerId: string; label: string } })\r\n .payload;\r\n await providerHandlers.handleKeyDelete(ws, providerId, label);\r\n break;\r\n }\r\n\r\n case 'key.set_active': {\r\n const { providerId, label } = (msg as { payload: { providerId: string; label: string } })\r\n .payload;\r\n await providerHandlers.handleKeySetActive(ws, providerId, label);\r\n break;\r\n }\r\n\r\n case 'provider.add': {\r\n const p = (\r\n msg as { payload: { id: string; family: string; baseUrl?: string; apiKey?: string } }\r\n ).payload;\r\n await providerHandlers.handleProviderAdd(ws, p);\r\n break;\r\n }\r\n\r\n case 'provider.remove': {\r\n const { providerId } = (msg as { payload: { providerId: string } }).payload;\r\n await providerHandlers.handleProviderRemove(ws, providerId);\r\n break;\r\n }\r\n\r\n case 'sessions.list': {\r\n // Per-project history. Sessions live under .wrongstack/sessions/ for\r\n // this project; we never enumerate cross-project state.\r\n const limit = (msg as { payload?: { limit?: number } }).payload?.limit ?? 50;\r\n try {\r\n const list = await sessionStore.list(limit);\r\n send(ws, {\r\n type: 'sessions.list',\r\n payload: {\r\n sessions: list.map((s) => ({\r\n id: s.id,\r\n title: s.title,\r\n startedAt: s.startedAt,\r\n model: s.model,\r\n provider: s.provider,\r\n tokenTotal: s.tokenTotal,\r\n isCurrent: s.id === session.id,\r\n })),\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'sessions.list',\r\n payload: { sessions: [], error: errMessage(err) },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'session.delete': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n if (id === session.id) {\r\n sendResult(ws, false, 'Cannot delete the active session');\r\n break;\r\n }\r\n await sessionStore.delete(id);\r\n sendResult(ws, true, `Session ${id} deleted`);\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'session.resume': {\r\n // Load a past session's messages + usage, swap the active session\r\n // writer, hydrate the live Context, then broadcast a session.start\r\n // payload tagged with the replayed transcript so the UI can render\r\n // the chat history.\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n if (id === session.id) {\r\n sendResult(ws, false, 'Session is already active');\r\n break;\r\n }\r\n const resumed = await sessionStore.resume(id);\r\n // Close prior writer best-effort; swallow errors so we don't block\r\n // the resume on a crashed file handle.\r\n try {\r\n await session.close();\r\n } catch {\r\n /* noop */\r\n }\r\n session = resumed.writer;\r\n context.session = session;\r\n context.state.replaceMessages(resumed.data.messages);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n // Replay usage so the topbar shows accurate totals after resume.\r\n tokenCounter.account(resumed.data.usage, config.model);\r\n sessionStartedAt = Date.now();\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: {\r\n ...(await sessionStartPayload()),\r\n reset: true,\r\n replayMessages: resumed.data.messages,\r\n replayUsage: resumed.data.usage,\r\n },\r\n });\r\n sendResult(ws, true, `Resumed session ${id}`);\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'session.save': {\r\n // SessionWriter already flushes after every event; this is mostly a\r\n // no-op marker so the user gets confirmation. Useful for habit\r\n // parity with the CLI /save command.\r\n sendResult(ws, true, `Session ${session.id} is auto-saved`);\r\n break;\r\n }\r\n\r\n case 'tools.list': {\r\n // Full tool registry dump for the /tools inspect view. We surface\r\n // name, description, and schema-derived param names so the user\r\n // can tell at a glance which tools the model can call right now.\r\n const list = toolRegistry.list().map((t) => {\r\n const schema =\r\n (t as { inputSchema?: { properties?: Record<string, unknown> } }).inputSchema ?? {};\r\n const params = schema.properties ? Object.keys(schema.properties) : [];\r\n return {\r\n name: t.name,\r\n description: (t as { description?: string }).description ?? '',\r\n params,\r\n };\r\n });\r\n send(ws, { type: 'tools.list', payload: { tools: list } });\r\n break;\r\n }\r\n\r\n case 'memory.list': {\r\n // All three scopes (project-agents, project-memory, user-memory)\r\n // rolled up as readAll already does. Returned as raw markdown so\r\n // the UI can render with the same style as everything else.\r\n try {\r\n const text = await memoryStore.readAll();\r\n send(ws, { type: 'memory.list', payload: { text } });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'memory.list',\r\n payload: { text: '', error: errMessage(err) },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'memory.remember': {\r\n const { text, scope } = (\r\n msg as {\r\n payload: { text: string; scope?: 'project-agents' | 'project-memory' | 'user-memory' };\r\n }\r\n ).payload;\r\n try {\r\n await memoryStore.remember(text, scope ?? 'project-memory');\r\n sendResult(ws, true, 'Saved to memory');\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'memory.forget': {\r\n const { text, scope } = (\r\n msg as {\r\n payload: { text: string; scope?: 'project-agents' | 'project-memory' | 'user-memory' };\r\n }\r\n ).payload;\r\n try {\r\n const removed = await memoryStore.forget(text, scope ?? 'project-memory');\r\n sendResult(\r\n ws,\r\n removed > 0,\r\n removed > 0\r\n ? `Removed ${removed} entr${removed === 1 ? 'y' : 'ies'}`\r\n : 'No matching entries',\r\n );\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'skills.list': {\r\n if (!skillLoader) {\r\n send(ws, { type: 'skills.list', payload: { skills: [], enabled: false } });\r\n break;\r\n }\r\n try {\r\n const manifests = await skillLoader.list();\r\n const entries = await skillLoader.listEntries();\r\n const byName = new Map(entries.map((e) => [e.name, e]));\r\n send(ws, {\r\n type: 'skills.list',\r\n payload: {\r\n enabled: true,\r\n skills: manifests.map((m) => ({\r\n name: m.name,\r\n description: m.description,\r\n version: m.version ?? '',\r\n source: m.source,\r\n path: m.path,\r\n trigger: byName.get(m.name)?.trigger ?? '',\r\n scope: byName.get(m.name)?.scope ?? [],\r\n })),\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'skills.list',\r\n payload: {\r\n skills: [],\r\n enabled: true,\r\n error: errMessage(err),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'diag.get': {\r\n // Snapshot of the moving parts so the user can debug \"why is X\r\n // not working?\" without diving into the server logs.\r\n const usage = tokenCounter.total();\r\n send(ws, {\r\n type: 'diag.get',\r\n payload: {\r\n provider: config.provider,\r\n model: config.model,\r\n cwd: projectRoot,\r\n sessionId: session.id,\r\n tools: {\r\n count: toolRegistry.list().length,\r\n names: toolRegistry.list().map((t) => t.name),\r\n },\r\n features: {\r\n memory: !!config.features?.memory,\r\n skills: !!config.features?.skills,\r\n modelsRegistry: !!config.features?.modelsRegistry,\r\n },\r\n mode: modeId ?? 'default',\r\n usage,\r\n messages: context.messages.length,\r\n todos: context.todos.length,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'todos.get': {\r\n // On-demand snapshot — used when a UI surface first mounts and\r\n // needs to render the live todo list without waiting for the next\r\n // tool.executed to broadcast.\r\n send(ws, {\r\n type: 'todos.updated',\r\n payload: { todos: [...context.todos] },\r\n });\r\n break;\r\n }\r\n\r\n case 'todos.clear': {\r\n // Manual override — the agent normally curates this list via\r\n // TodoWrite, but the user might want a clean slate without losing\r\n // the rest of the context. Use state.replaceTodos so observers\r\n // (checkpoint writer) stay in sync.\r\n context.state.replaceTodos([]);\r\n sendResult(ws, true, 'Todos cleared');\r\n broadcast(clients, { type: 'todos.updated', payload: { todos: [] } });\r\n break;\r\n }\r\n\r\n case 'todos.remove': {\r\n // Remove a single todo item by id or 1-based index.\r\n const payload = msg.payload as { id?: string; index?: number } | undefined;\r\n if (!payload) { sendResult(ws, false, 'Missing id or index'); break; }\r\n const { id, index } = payload;\r\n let targetIdx = -1;\r\n if (typeof id === 'string') {\r\n targetIdx = context.todos.findIndex((t) => t.id === id);\r\n } else if (typeof index === 'number' && index > 0) {\r\n targetIdx = index - 1;\r\n }\r\n if (targetIdx < 0 || !context.todos[targetIdx]) {\r\n sendResult(ws, false, 'Todo not found');\r\n break;\r\n }\r\n const removed = context.todos[targetIdx]!;\r\n const next = [\r\n ...context.todos.slice(0, targetIdx),\r\n ...context.todos.slice(targetIdx + 1),\r\n ];\r\n context.state.replaceTodos(next);\r\n sendResult(ws, true, `Removed: ${removed.content}`);\r\n broadcast(clients, { type: 'todos.updated', payload: { todos: next } });\r\n break;\r\n }\r\n\r\n case 'plan.get': {\r\n // On-demand plan snapshot — used when a UI surface first mounts\r\n // and needs to render the live plan without waiting for the next\r\n // tool.executed to broadcast.\r\n const planPath = (context.meta as Record<string, unknown>)['plan.path'];\r\n if (typeof planPath === 'string' && planPath) {\r\n try {\r\n const { loadPlan } = await import('@wrongstack/core');\r\n const plan = await loadPlan(planPath);\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: plan ?? { version: 1, sessionId: session.id, updatedAt: new Date().toISOString(), items: [] } },\r\n });\r\n } catch {\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: { version: 1, sessionId: session.id, updatedAt: new Date().toISOString(), items: [] } },\r\n });\r\n }\r\n } else {\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: null, error: 'Plan storage is not configured for this session.' },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'plan.template_use': {\r\n const { template } = (msg as { payload: { template: string } }).payload;\r\n const planPath = (context.meta as Record<string, unknown>)['plan.path'];\r\n if (typeof planPath !== 'string' || !planPath) {\r\n sendResult(ws, false, 'Plan storage is not configured for this session.');\r\n break;\r\n }\r\n try {\r\n const { getPlanTemplate, loadPlan, savePlan, emptyPlan, addPlanItem } = await import('@wrongstack/core');\r\n const tpl = getPlanTemplate(template);\r\n if (!tpl) {\r\n sendResult(ws, false, `Unknown template \"${template}\".`);\r\n break;\r\n }\r\n let plan = (await loadPlan(planPath)) ?? emptyPlan(session.id);\r\n for (const item of tpl.items) {\r\n ({ plan } = addPlanItem(plan, item.title, item.details));\r\n }\r\n await savePlan(planPath, plan);\r\n sendResult(ws, true, `Applied template \"${tpl.name}\" — ${tpl.items.length} items added.`);\r\n broadcast(clients, {\r\n type: 'plan.updated',\r\n payload: { plan },\r\n });\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'files.list': {\r\n // Lightweight project file picker for the chat `@` mention popup.\r\n // Walks projectRoot, skipping the heavyweight build/vcs/node_modules\r\n // dirs that would blow up the response on a real project. Applies\r\n // a fuzzy substring match against the (lowercased) query and caps\r\n // the result so the popup never has to paginate.\r\n const payload = (msg as { payload?: { query?: string; limit?: number } }).payload ?? {};\r\n const limit = payload.limit ?? 50;\r\n // Filtering (isHiddenEntry/SKIP_DIRS) and ranking (rankFiles) live in\r\n // ./file-picker.ts; the walk itself stays here since it's disk I/O.\r\n const results: string[] = [];\r\n async function walk(dir: string, rel: string, depth: number): Promise<void> {\r\n if (depth > 8 || results.length >= 600) return;\r\n let entries: import('node:fs').Dirent[] = [];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n for (const e of entries) {\r\n if (results.length >= 600) return;\r\n if (isHiddenEntry(e.name)) continue;\r\n const childRel = rel ? `${rel}/${e.name}` : e.name;\r\n if (e.isDirectory()) {\r\n if (SKIP_DIRS.has(e.name)) continue;\r\n await walk(path.join(dir, e.name), childRel, depth + 1);\r\n } else if (e.isFile()) {\r\n results.push(childRel);\r\n }\r\n }\r\n }\r\n await walk(projectRoot, '', 0);\r\n send(ws, {\r\n type: 'files.list',\r\n payload: { files: rankFiles(results, payload.query ?? '', limit) },\r\n });\r\n break;\r\n }\r\n\r\n case 'modes.list': {\r\n try {\r\n const modes = await modeStore.listModes();\r\n const active = await modeStore.getActiveMode();\r\n send(ws, {\r\n type: 'modes.list',\r\n payload: {\r\n modes: modes.map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n description: m.description,\r\n isActive: m.id === (active?.id ?? 'default'),\r\n })),\r\n activeId: active?.id ?? 'default',\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'modes.list',\r\n payload: {\r\n modes: [],\r\n activeId: 'default',\r\n error: errMessage(err),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'mode.switch': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n // 'default' is the implicit no-mode state — persisting null\r\n // clears the override. Anything else has to exist in the store.\r\n if (id === 'default') {\r\n await modeStore.setActiveMode(null);\r\n } else {\r\n const found = await modeStore.getMode(id);\r\n if (!found) throw new Error(`Unknown mode \"${id}\"`);\r\n await modeStore.setActiveMode(id);\r\n }\r\n modeId = id;\r\n // Rebuild the system prompt so the next turn picks up the new\r\n // mode's instructions. The builder caches the environment block\r\n // per projectRoot (including the modeId), so we clear the cache\r\n // and rebuild. The `buildMode()` method reads this.opts.modePrompt\r\n // which is set on the builder constructor — we construct a fresh\r\n // builder with the updated mode. This is cheap (no fs/net IO in\r\n // the constructor; the real work happens in build()).\r\n const modePrompt = id === 'default' ? '' : ((await modeStore.getMode(id))?.prompt ?? '');\r\n const freshBuilder = new DefaultSystemPromptBuilder({\r\n memoryStore,\r\n skillLoader,\r\n modeStore,\r\n modeId: id,\r\n modePrompt,\r\n modelCapabilities,\r\n });\r\n context.systemPrompt = await freshBuilder.build({\r\n cwd: projectRoot,\r\n projectRoot,\r\n tools: toolRegistry.list(),\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n sendResult(ws, true, `Switched to mode \"${id}\"`);\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: { ...(await sessionStartPayload()) },\r\n });\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'stats.get': {\r\n // Mirror of the CLI's /stats: detailed session report.\r\n const usage = tokenCounter.total();\r\n const cacheStats = tokenCounter.cacheStats();\r\n const m = await modelsRegistry.getModel(config.provider, config.model).catch(() => null);\r\n const cost = computeUsageCost(usage, getCostRates(m));\r\n send(ws, {\r\n type: 'stats.get',\r\n payload: {\r\n sessionId: session.id,\r\n provider: config.provider,\r\n model: config.model,\r\n usage,\r\n cache: cacheStats,\r\n cost,\r\n messages: context.messages.length,\r\n readFiles: context.readFiles.size,\r\n tools: toolRegistry.list().length,\r\n elapsedMs: Date.now() - sessionStartedAt,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n default:\r\n if (msg.type.startsWith('autophase.')) {\r\n // Delegate all AutoPhase lifecycle messages to the handler\r\n await autoPhaseHandler.handleMessage(msg as { type: string; payload?: Record<string, unknown> });\r\n } else {\r\n send(ws, { type: 'error', payload: { phase: 'handleMessage', message: `Unknown message type: ${msg.type}` } });\r\n }\r\n }\r\n }\r\n\r\n // ---- Provider/Key management helpers (extracted to provider-handlers.ts) ----\r\n const providerHandlers = createProviderHandlers({\r\n globalConfigPath,\r\n vault,\r\n getConfigWriteLock: () => configWriteLock,\r\n setConfigWriteLock: (p) => { configWriteLock = p; },\r\n });\r\n\r\n // HTTP server for the React frontend (port 3456) — see `http-server.ts`\r\n // for the static-serve, MIME matching, path-traversal guard, and CSP\r\n // header logic. Constructed here, listen()d below alongside the WS server.\r\n const httpServer = createHttpServer({\r\n host: wsHost,\r\n distDir: path.resolve(import.meta.dirname, '../../dist'),\r\n wsPort,\r\n });\r\n // httpPort/wsPort were resolved (and possibly auto-advanced) at the top.\r\n // Base dir for the running-instance registry — keep it next to the rest of\r\n // the wstack home state (config.json lives here too).\r\n const registryBaseDir = path.dirname(globalConfigPath);\r\n httpServer.listen(httpPort, wsHost, () => {\r\n const openUrl = `http://${wsHost}:${httpPort}`;\r\n console.log(`[WebUI] HTTP server running on ${openUrl}`);\r\n // Optionally pop the browser open (best-effort; the URL is always printed).\r\n if (opts.open) openBrowser(openUrl);\r\n // Record this instance so `webui --list` (and `~/.wrongstack/\r\n // webui-instances.json`) show which ports are open for which project.\r\n // Best-effort: a registry write failure must not affect serving.\r\n void registerInstance(\r\n {\r\n pid: process.pid,\r\n httpPort,\r\n wsPort,\r\n host: wsHost,\r\n projectRoot,\r\n projectName: path.basename(projectRoot) || projectRoot,\r\n startedAt: new Date().toISOString(),\r\n url: `http://${wsHost}:${httpPort}`,\r\n },\r\n registryBaseDir,\r\n ).catch((err) => console.warn('[WebUI] Could not record instance:', errMessage(err)));\r\n });\r\n\r\n // Graceful shutdown on SIGINT/SIGTERM — see `lifecycle.ts`. The session\r\n // flush (session_end + close) is passed as a thunk so lifecycle stays\r\n // decoupled from the session/tokenCounter types.\r\n registerShutdownHandlers({\r\n flushSession: async () => {\r\n await session.append({\r\n type: 'session_end',\r\n ts: new Date().toISOString(),\r\n usage: tokenCounter.total(),\r\n });\r\n await session.close();\r\n },\r\n clients: () => clients.keys(),\r\n servers: [httpServer, wssPrimary, wssSecondary],\r\n // Drop this instance from the registry on a clean exit so the file reflects\r\n // reality. Crash exits are healed by the next register()/list() prune pass.\r\n onShutdown: () => unregisterInstance(process.pid, registryBaseDir),\r\n });\r\n}\r\n","/**\n * Static-file HTTP server for the WebUI React frontend.\n *\n * - Serves files from `distDir` (typically `<webui>/dist`).\n * - Returns `index.html` for any unknown path so client-side routing works\n * (SPA fallback) — and applies the same Content-Security-Policy to that\n * fallback as to a direct `.html` response, so deep-linked routes are\n * not unprotected.\n * - **Path-traversal guard**: `path.join` alone does NOT prevent\n * `%2e%2e%2f` escapes (the `URL` constructor decodes percent-encoding\n * before we see the path). We re-`resolve` the candidate and verify it\n * stays under `distDir`.\n * - **CSP**: `connect-src` uses explicit loopback addresses for the WS\n * server (not bare `ws:` / `wss:`) so a malicious page script cannot\n * dial an attacker-controlled WebSocket. Combined with token-in-URL\n * (C-2), this prevents cross-origin WS abuse.\n *\n * Extracted from `index.ts` so the static-serve concern can be tested\n * with a tiny fake `distDir` and asserted on path-traversal, MIME\n * matching, and CSP header presence.\n */\nimport * as fs from 'node:fs/promises';\nimport * as http from 'node:http';\nimport * as path from 'node:path';\n\nexport interface CreateHttpServerOptions {\n /** Port to listen on. Defaults to 3456 (or the `PORT` env var). */\n port?: number;\n /** Host/interface to bind. Typically the loopback for the WebUI. */\n host: string;\n /** Resolved path to the directory containing the built React assets. */\n distDir: string;\n /**\n * WS port — appears in the CSP `connect-src` directive so the browser\n * is allowed to open a WebSocket back to the local server.\n */\n wsPort: number;\n}\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Inject the live WS port into the served HTML so the frontend connects to\n * THIS instance's backend instead of a hardcoded default. Enables running\n * several WebUI instances simultaneously on different PORT/WS_PORT pairs\n * (e.g. one per project) — each instance serves HTML stamped with its own\n * WS port.\n *\n * A `<meta>` tag is used deliberately rather than an inline `<script>`: the\n * CSP sets `script-src 'self'`, which would block an inline script, but meta\n * tags are not subject to script-src. The frontend reads\n * `meta[name=\"wrongstack-ws-port\"]` (see ws-client.ts `defaultWsUrl`).\n */\nexport function injectWsPort(html: string, wsPort: number): string {\n const tag = `<meta name=\"wrongstack-ws-port\" content=\"${wsPort}\" />`;\n // Idempotent: never inject twice if the source HTML already carries one.\n if (html.includes('name=\"wrongstack-ws-port\"')) return html;\n if (html.includes('</head>')) {\n return html.replace('</head>', ` ${tag}\\n </head>`);\n }\n // No <head> (unexpected) — prepend so the tag is still in the document.\n return `${tag}\\n${html}`;\n}\n\n/** Build the Content-Security-Policy value for the given WS port. */\nexport function buildCspHeader(wsPort: number): string {\n return (\n `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; ` +\n `connect-src 'self' ws://127.0.0.1:${wsPort} wss://127.0.0.1:${wsPort} ` +\n `ws://[::1]:${wsPort} wss://[::1]:${wsPort}; ` +\n `img-src 'self' data:; font-src 'self' data:; object-src 'none'; ` +\n `base-uri 'self'; frame-ancestors 'none'; form-action 'self'`\n );\n}\n\n/**\n * Returns true when `candidate` (a fully-resolved absolute path) lies\n * strictly inside `distDir` (or equals it). Used to reject path-traversal\n * attempts after `path.resolve` has normalised any `..` segments.\n *\n * Exported so tests can assert the guard's contract without having to\n * also defeat the WHATWG URL normaliser (which strips `..` from the\n * path string *before* the request even reaches the server, making a\n * black-box test via fetch impossible).\n */\nexport function isInsideDist(candidate: string, distDir: string): boolean {\n const root = path.resolve(distDir);\n const resolved = path.resolve(candidate);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/**\n * Create the static-file HTTP server. Returns the `http.Server` (not\n * listening yet) so the caller can attach to a `shutdown()` hook and\n * coordinate the listen() with the WebSocket bootstrap.\n */\nexport function createHttpServer(opts: CreateHttpServerOptions): http.Server {\n const port = opts.port ?? Number.parseInt(process.env['PORT'] ?? '3456', 10);\n const distDir = path.resolve(opts.distDir);\n const wsPort = opts.wsPort;\n\n return http.createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);\n let filePath: string;\n\n if (url.pathname === '/' || url.pathname === '') {\n filePath = path.join(distDir, 'index.html');\n } else if (url.pathname.startsWith('/assets/')) {\n filePath = path.join(distDir, url.pathname);\n } else if (url.pathname.startsWith('/')) {\n filePath = path.join(distDir, url.pathname);\n } else {\n filePath = path.join(distDir, 'index.html');\n }\n\n // Path traversal guard: the resolved path must stay inside distDir.\n // WHATWG URL leaves percent-encoding alone in `url.pathname` (it\n // does not decode `%2e%2e` to `..`), so percent-encoded escapes\n // are *not* a concern here — but unencoded `..` segments are\n // normalised by `path.resolve` and would walk the candidate up\n // out of distDir. `isInsideDist` catches that.\n const resolvedPath = path.resolve(filePath);\n if (!isInsideDist(resolvedPath, distDir)) {\n res.writeHead(403, { 'Content-Type': 'text/plain' });\n res.end('Forbidden');\n return;\n }\n\n const ext = path.extname(resolvedPath);\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';\n res.setHeader('Content-Type', contentType);\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'DENY');\n res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');\n\n if (ext === '.html') {\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Content-Security-Policy', buildCspHeader(wsPort));\n // Stamp the live WS port into the HTML so the frontend dials this\n // instance's backend (not the hardcoded default) — required for\n // running multiple WebUI instances on different ports.\n const html = await fs.readFile(resolvedPath, 'utf8');\n res.writeHead(200);\n res.end(injectWsPort(html, wsPort));\n return;\n }\n\n const fileContent = await fs.readFile(resolvedPath);\n res.writeHead(200);\n res.end(fileContent);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n // SPA fallback: serve index.html so client-side routing still works.\n try {\n const html = await fs.readFile(path.join(distDir, 'index.html'), 'utf8');\n res.writeHead(200, {\n 'Content-Type': 'text/html',\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\n 'Content-Security-Policy': buildCspHeader(wsPort),\n });\n res.end(injectWsPort(html, wsPort));\n } catch {\n res.writeHead(404);\n res.end('Not found');\n }\n } else {\n res.writeHead(500);\n res.end('Server error');\n }\n }\n });\n}\n","/**\n * Pure filtering + ranking for the `files.list` project file picker (the chat\n * `@`-mention popup). The directory *walk* stays in index.ts (it's I/O), but\n * the two decisions that shape the result — which entries to hide and how to\n * rank matches — are pure and live here so the scoring weights, depth penalty,\n * and tie-break order can be unit tested. A silently-flipped weight would make\n * the picker feel subtly wrong with nothing to catch it.\n */\n/** Heavyweight build/vcs/dependency dirs the picker never descends into. */\nexport const SKIP_DIRS: ReadonlySet<string> = new Set([\n '.git',\n 'node_modules',\n 'dist',\n 'build',\n '.next',\n '.turbo',\n '.cache',\n 'target',\n 'coverage',\n '.nyc_output',\n 'out',\n '.pnpm-store',\n '.parcel-cache',\n]);\n\n/** Dotfiles/dirs kept despite the hide-dotfiles-by-default rule. */\nconst KEEP_DOTFILES: ReadonlySet<string> = new Set([\n '.wrongstack',\n '.env.example',\n '.gitignore',\n '.eslintrc',\n '.prettierrc',\n]);\n\n/**\n * Whether a directory entry should be hidden from the picker by its name.\n * Dotfiles are hidden by default, except a few commonly-wanted ones.\n */\nexport function isHiddenEntry(name: string): boolean {\n return name.startsWith('.') && !KEEP_DOTFILES.has(name);\n}\n\n/**\n * Rank `paths` against `query` and return up to `limit` paths, best first.\n *\n * Scoring (cheap heuristic, good enough for a picker): exact basename match\n * (100) > basename prefix (60) > path substring (20); non-matches are dropped.\n * Each match is penalized by its path depth so root files sort first. Ties\n * break by lexicographic path. An empty query keeps every path (score 0), so\n * the result is the paths sorted lexicographically, capped to `limit`.\n */\nexport function rankFiles(paths: readonly string[], query: string, limit: number): string[] {\n const q = query.toLowerCase();\n const scored: Array<{ path: string; score: number }> = [];\n for (const p of paths) {\n if (!q) {\n scored.push({ path: p, score: 0 });\n continue;\n }\n const lower = p.toLowerCase();\n const base = lower.split('/').pop() ?? lower;\n let score = 0;\n if (base === q) score = 100;\n else if (base.startsWith(q)) score = 60;\n else if (lower.includes(q)) score = 20;\n else continue;\n // Penalise depth so root files come first.\n score -= p.split('/').length;\n scored.push({ path: p, score });\n }\n scored.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n return scored.slice(0, limit).map((s) => s.path);\n}\n","import {\n type Config,\n Container,\n DefaultConfigStore,\n DefaultErrorHandler,\n DefaultMemoryStore,\n DefaultModeStore,\n DefaultPermissionPolicy,\n DefaultRetryPolicy,\n DefaultSecretScrubber,\n DefaultSessionStore,\n DefaultSkillLoader,\n DefaultSystemPromptBuilder,\n DefaultTokenCounter,\n HybridCompactor,\n type Logger,\n type ModelsRegistry,\n TOKENS,\n type Tool,\n type WstackPaths,\n} from '@wrongstack/core';\nimport type { DefaultSystemPromptBuilderOptions } from '@wrongstack/core';\n\nexport interface CreateContainerOptions {\n config: Config;\n wpaths: WstackPaths;\n logger: Logger;\n modelsRegistry: ModelsRegistry;\n permission?: {\n yolo?: boolean;\n yoloDestructive?: boolean;\n /** @deprecated Use `yoloDestructive`. */\n forceAllYolo?: boolean;\n /** When true, destructive ops prompt even in YOLO mode. */\n confirmDestructive?: boolean;\n promptDelegate?: (\n tool: Tool,\n input: unknown,\n suggestedPattern: string,\n ) => Promise<'yes' | 'no' | 'always' | 'deny'>;\n };\n compactor?: { preserveK?: number; eliseThreshold?: number };\n systemPrompt?: Partial<DefaultSystemPromptBuilderOptions>;\n /** Bundled skills directory path (resolved at boot time). */\n bundledSkillsDir?: string;\n}\n\n/**\n * Create a Container pre-bound with all default service implementations.\n * Both CLI and WebUI use this factory so container wiring stays in one place.\n */\nexport function createDefaultContainer(opts: CreateContainerOptions): Container {\n const { config, wpaths, logger, modelsRegistry } = opts;\n const container = new Container();\n\n const configStore = new DefaultConfigStore(config);\n container.bind(TOKENS.ConfigStore, () => configStore);\n container.bind(TOKENS.Logger, () => logger);\n container.bind(TOKENS.SecretScrubber, () => new DefaultSecretScrubber());\n container.bind(TOKENS.RetryPolicy, () => new DefaultRetryPolicy());\n container.bind(TOKENS.ErrorHandler, () => new DefaultErrorHandler());\n container.bind(TOKENS.ModelsRegistry, () => modelsRegistry);\n container.bind(\n TOKENS.TokenCounter,\n () => new DefaultTokenCounter({ registry: modelsRegistry, providerId: config.provider }),\n );\n\n const modeStore = new DefaultModeStore({ directory: wpaths.configDir });\n container.bind(TOKENS.ModeStore, () => modeStore);\n container.bind(\n TOKENS.SessionStore,\n () =>\n new DefaultSessionStore({\n dir: wpaths.projectSessions,\n // Scrub secrets out of persisted user/model turns (F-06). Tool output\n // is already scrubbed by the executor.\n secretScrubber: container.resolve(TOKENS.SecretScrubber),\n }),\n );\n\n const memoryStore = new DefaultMemoryStore({ paths: wpaths });\n container.bind(TOKENS.MemoryStore, () => memoryStore);\n\n const skillLoader = new DefaultSkillLoader({ paths: wpaths, bundledDir: opts.bundledSkillsDir });\n container.bind(TOKENS.SkillLoader, () => skillLoader);\n\n if (opts.systemPrompt) {\n container.bind(\n TOKENS.SystemPromptBuilder,\n () => new DefaultSystemPromptBuilder(opts.systemPrompt as DefaultSystemPromptBuilderOptions),\n );\n }\n\n container.bind(\n TOKENS.PermissionPolicy,\n () =>\n new DefaultPermissionPolicy({\n trustFile: wpaths.projectTrust,\n yolo: opts.permission?.yolo ?? false,\n yoloDestructive: opts.permission?.yoloDestructive ?? opts.permission?.forceAllYolo ?? false,\n confirmDestructive: opts.permission?.confirmDestructive ?? false,\n promptDelegate: opts.permission?.promptDelegate,\n }),\n );\n\n container.bind(\n TOKENS.Compactor,\n () =>\n new HybridCompactor({\n preserveK: opts.compactor?.preserveK ?? 20,\n eliseThreshold: opts.compactor?.eliseThreshold ?? 0.7,\n }),\n );\n\n return container;\n}\n","import {\n type Config,\n type DefaultLogger,\n type DefaultSecretVault,\n type WstackPaths,\n bootConfig as coreBootConfig,\n} from '@wrongstack/core';\n\nexport interface BootResult {\n config: Config;\n vault: DefaultSecretVault;\n globalConfigPath: string;\n projectRoot: string;\n wpaths: WstackPaths;\n logger: InstanceType<typeof DefaultLogger>;\n}\n\n/**\n * Thin WebUI wrapper over the canonical `bootConfig` in `@wrongstack/core`\n * (mirrors packages/cli/src/boot-config.ts). All real boot behavior — wstack\n * path resolution, the AES-GCM `DefaultSecretVault`, plaintext-secret\n * migration, and config load/merge — lives in core so the WebUI server and the\n * CLI can't drift. Only the secret-migration notice label (`WebUI`) differs.\n */\nexport async function bootConfig(): Promise<BootResult> {\n const { config, vault, globalConfigPath, projectRoot, wpaths, logger } = await coreBootConfig({\n appLabel: 'WebUI',\n });\n return { config, vault, globalConfigPath, projectRoot, wpaths, logger };\n}\n\nexport function patchConfig(config: Config, updates: Partial<Config>): Config {\n return Object.freeze({ ...config, ...updates });\n}\n","import { spawnSync } from 'node:child_process';\nimport type { WebSocket } from 'ws';\nimport {\n AutoPhasePlanner,\n PhaseGraphBuilder,\n PhaseOrchestrator,\n PhaseStore,\n WorktreeManager,\n type PhaseGraph,\n type PhaseTemplate,\n} from '@wrongstack/core';\nimport type { Agent, Context, EventBus, Logger } from '@wrongstack/core';\n\nfunction isGitRepo(cwd: string): boolean {\n try {\n const r = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd, encoding: 'utf8' });\n return r.status === 0 && r.stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\ninterface WSClient {\n ws: WebSocket;\n id: string;\n}\n\ninterface AutoPhaseWSMessage {\n type: string;\n payload?: Record<string, unknown>;\n}\n\n/**\n * AutoPhaseWebSocketHandler — WebSocket üzerinden AutoPhase kontrolü.\n *\n * Mesaj tipleri:\n * autophase.start → { title, phases?, autonomous? }\n * autophase.pause → {}\n * autophase.resume → {}\n * autophase.stop → {}\n * autophase.status → {}\n * autophase.selectPhase → { phaseId }\n * autophase.taskStatus → { taskId, status }\n */\nexport class AutoPhaseWebSocketHandler {\n private orchestrator: PhaseOrchestrator | null = null;\n private graph: PhaseGraph | null = null;\n private store: PhaseStore;\n private clients = new Set<WSClient>();\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n /** Aborts in-flight task agents when the run is stopped. */\n private abort: AbortController | null = null;\n /** Optional per-phase git-worktree isolation (lazily created at start). */\n private worktrees: WorktreeManager | null = null;\n\n constructor(\n private agent: Agent,\n private context: Context,\n private logger: Logger,\n storeDir: string,\n private events?: EventBus,\n private projectRoot?: string,\n ) {\n this.store = new PhaseStore({ baseDir: storeDir });\n }\n\n addClient(ws: WebSocket): void {\n const client: WSClient = { ws, id: crypto.randomUUID() };\n this.clients.add(client);\n\n ws.on('close', () => this.clients.delete(client));\n ws.on('error', () => this.clients.delete(client));\n\n // Anlık durum gönder\n this.sendState(client);\n }\n\n async handleMessage(msg: AutoPhaseWSMessage): Promise<void> {\n switch (msg.type) {\n case 'autophase.start':\n await this.handleStart(msg.payload);\n break;\n case 'autophase.pause':\n this.orchestrator?.pause();\n this.broadcast({ type: 'autophase.paused', payload: {} });\n break;\n case 'autophase.resume':\n this.orchestrator?.resume();\n this.broadcast({ type: 'autophase.resumed', payload: {} });\n break;\n case 'autophase.stop':\n this.abort?.abort();\n this.orchestrator?.stop();\n this.stopBroadcast();\n if (this.graph) void this.store.save(this.graph);\n this.broadcast({ type: 'autophase.stopped', payload: {} });\n break;\n case 'autophase.status':\n this.broadcastState();\n break;\n case 'autophase.selectPhase': {\n const phaseId = msg.payload?.phaseId as string;\n if (phaseId && this.graph) {\n this.broadcastState(phaseId);\n }\n break;\n }\n case 'autophase.taskStatus': {\n const { taskId, status } = msg.payload as { taskId: string; status: string };\n await this.handleTaskStatusChange(taskId, status);\n break;\n }\n case 'autophase.toggleAutonomous': {\n const autonomous = (msg.payload?.autonomous as boolean) ?? !this.graph?.autonomous;\n if (this.graph) {\n this.graph.autonomous = autonomous;\n await this.store.save(this.graph);\n this.broadcast({ type: 'autophase.state', payload: this.buildState() });\n }\n break;\n }\n case 'autophase.save': {\n if (this.graph) {\n await this.store.save(this.graph);\n this.broadcast({ type: 'autophase.saved', payload: { graphId: this.graph.id } });\n }\n break;\n }\n case 'autophase.list': {\n const graphs = await this.store.list();\n this.broadcast({ type: 'autophase.list', payload: { graphs } });\n break;\n }\n case 'autophase.load': {\n const graphId = msg.payload?.graphId as string | undefined;\n if (graphId) {\n const graph = await this.store.load(graphId);\n if (graph) {\n this.graph = graph;\n this.broadcast({ type: 'autophase.state', payload: this.buildState() });\n } else {\n this.broadcast({ type: 'autophase.error', payload: { message: `Graph not found: ${graphId}` } });\n }\n }\n break;\n }\n }\n }\n\n private async handleStart(payload?: Record<string, unknown>): Promise<void> {\n const title = (payload?.goal as string) || (payload?.title as string) || 'Untitled Project';\n const autonomous = (payload?.autonomous as boolean) ?? true;\n\n // Phase plan resolution:\n // 1. explicit phases in the payload win (caller override);\n // 2. otherwise the LLM plans phases+todos for the goal;\n // 3. failing that, fall back to the generic default phases.\n const phases = Array.isArray(payload?.phases)\n ? (payload.phases as PhaseTemplate[])\n : await this.planPhases(title);\n\n this.logger.info(`[AutoPhase] Starting: ${title}`);\n\n // Build the graph up-front so we have a reference for live broadcasts and\n // persistence *before* the (long-running) build begins.\n const graph = await new PhaseGraphBuilder({ title, phases, autonomous }).build();\n this.graph = graph;\n this.abort = new AbortController();\n await this.store.save(graph);\n\n // Per-phase git-worktree isolation, when enabled and inside a git repo.\n // The shared agent/context means we can't run phases in parallel here\n // (we swap a single context.cwd per task), so phases stay sequential —\n // but each phase still commits + squash-merges back through its own\n // worktree, and the lifecycle events drive the live swim-lane/DAG view.\n if (\n !this.worktrees &&\n this.events &&\n this.projectRoot &&\n process.env['WRONGSTACK_AUTOPHASE_WORKTREES'] !== '0' &&\n isGitRepo(this.projectRoot)\n ) {\n this.worktrees = new WorktreeManager({ projectRoot: this.projectRoot, events: this.events });\n }\n\n this.orchestrator = new PhaseOrchestrator({\n graph,\n ctx: {\n executeTask: async (task, phaseId, env) => {\n this.logger.info(`[AutoPhase] [${phaseId}] Executing: ${task.title}`);\n const result = await this.executeTaskWithAgent(task, phaseId, env);\n this.logger.info(`[AutoPhase] [${phaseId}] Completed: ${task.title}`);\n return result;\n },\n onPhaseComplete: (phase) => {\n this.logger.info(`[AutoPhase] Phase completed: ${phase.name}`);\n void this.store.save(graph);\n this.broadcastState();\n },\n onPhaseFail: (phase, error) => {\n this.logger.error(`[AutoPhase] Phase failed: ${phase.name} — ${error.message}`);\n void this.store.save(graph);\n this.broadcastState();\n },\n },\n worktrees: this.worktrees ?? undefined,\n autonomous,\n // Must stay 1: phase tasks run on the single shared context whose cwd we\n // swap per phase, so parallel phases would race on context.cwd.\n maxConcurrentPhases: 1,\n // Sequential within a phase: each todo is a full-tool agent editing the\n // phase worktree, so running two at once risks concurrent writes.\n maxConcurrentTasks: 1,\n });\n\n // Start the live broadcast immediately, then run the orchestrator in the\n // background. Awaiting start() would block until the *entire* build\n // finishes — the periodic broadcast (below) reads the mutating graph, so\n // clients see live progress while it runs.\n this.startBroadcast();\n this.broadcastState();\n\n void this.orchestrator\n .start()\n .then(() => {\n this.orchestrator?.stop(); // clear the autonomous tick interval\n void this.store.save(graph);\n this.stopBroadcast();\n const failed = graph.failedPhaseIds.length > 0;\n this.broadcast(\n failed\n ? { type: 'autophase.failed', payload: { title } }\n : { type: 'autophase.completed', payload: { title } },\n );\n this.broadcastState();\n })\n .catch((err: unknown) => {\n this.logger.error(`[AutoPhase] Aborted: ${err instanceof Error ? err.message : String(err)}`);\n this.stopBroadcast();\n this.broadcast({ type: 'autophase.failed', payload: { title, error: String(err) } });\n });\n }\n\n /** Generic fallback phases when the LLM planner produces nothing usable. */\n private defaultPhases(): PhaseTemplate[] {\n return [\n { name: 'Discovery', description: 'Requirements gathering', priority: 'high', estimateHours: 2, parallelizable: false },\n { name: 'Design', description: 'Architecture and design', priority: 'critical', estimateHours: 4, parallelizable: false },\n { name: 'Implementation', description: 'Core development', priority: 'critical', estimateHours: 12, parallelizable: false },\n { name: 'Testing', description: 'Unit and integration tests', priority: 'high', estimateHours: 6, parallelizable: true },\n { name: 'Deployment', description: 'Deploy to production', priority: 'medium', estimateHours: 2, parallelizable: false },\n ];\n }\n\n /** Plan phases+todos for the goal via the LLM; fall back to defaults on failure. */\n private async planPhases(goal: string): Promise<PhaseTemplate[]> {\n try {\n const planner = new AutoPhasePlanner({\n goal,\n runOnce: async (prompt) => {\n const result = (await this.agent.run(prompt, { signal: new AbortController().signal })) as {\n status: string;\n finalText?: string;\n };\n return result.status === 'done' ? (result.finalText ?? '') : '';\n },\n });\n const { phases, parseFailed } = await planner.plan();\n if (!parseFailed && phases.length > 0) {\n const todos = phases.reduce((n, p) => n + (p.taskTemplates?.length ?? 0), 0);\n this.logger.info(`[AutoPhase] Planned ${phases.length} phases / ${todos} todos for: ${goal}`);\n return phases;\n }\n this.logger.info(`[AutoPhase] Planner produced no phases; using defaults for: ${goal}`);\n } catch (err) {\n this.logger.error(`[AutoPhase] Planning failed, using defaults: ${err instanceof Error ? err.message : String(err)}`);\n }\n return this.defaultPhases();\n }\n\n private async executeTaskWithAgent(\n task: import('@wrongstack/core').TaskNode,\n phaseId: string,\n env?: { cwd?: string; branch?: string },\n ): Promise<unknown> {\n // Task'ı agent'a çalıştır\n const prompt = `Execute task: ${task.title}\\n\\nDescription: ${task.description}\\nPhase: ${phaseId}\\nPriority: ${task.priority}\\nType: ${task.type}`;\n const signal = this.abort?.signal ?? new AbortController().signal;\n // Redirect the shared context's cwd at the phase worktree for the duration\n // of this task. Safe because phases/tasks run strictly sequentially here;\n // tools read `ctx.cwd` live, so the agent operates inside the worktree.\n const prevCwd = this.context.cwd;\n if (env?.cwd) this.context.cwd = env.cwd;\n try {\n return await this.agent.run(prompt, { signal });\n } finally {\n this.context.cwd = prevCwd;\n }\n }\n\n private async handleTaskStatusChange(taskId: string, status: string): Promise<void> {\n if (!this.graph) return;\n\n for (const phase of this.graph.phases.values()) {\n const task = phase.taskGraph.nodes.get(taskId);\n if (task) {\n task.status = status as import('@wrongstack/core').TaskStatus;\n task.updatedAt = Date.now();\n this.broadcastState();\n return;\n }\n }\n }\n\n private startBroadcast(): void {\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => {\n const progress = this.orchestrator?.getProgress();\n if (progress) this.broadcast({ type: 'autophase.progress', payload: progress });\n this.broadcastState();\n }, 2000);\n }\n\n private stopBroadcast(): void {\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcastState(activePhaseId?: string): void {\n if (!this.graph) return;\n\n const state = this.buildState(activePhaseId);\n this.broadcast({ type: 'autophase.state', payload: state });\n }\n\n private buildState(activePhaseId?: string): Record<string, unknown> {\n if (!this.graph) {\n return { phases: [], tasks: [], overallPercent: 0, autonomous: true, title: '' };\n }\n\n const phases = Array.from(this.graph.phases.values());\n const currentActiveId = activePhaseId || phases.find((p) => p.status === 'running')?.id || phases[0]?.id || '';\n const activePhase = this.graph.phases.get(currentActiveId);\n\n const totalTasks = phases.reduce((sum, p) => sum + p.taskGraph.nodes.size, 0);\n const completedTasks = phases.reduce(\n (sum, p) => sum + Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length,\n 0,\n );\n\n const phaseItems = phases.map((p) => ({\n id: p.id,\n name: p.name,\n description: p.description,\n status: p.status,\n priority: p.priority,\n estimateHours: p.estimateHours,\n actualDurationMs: p.actualDurationMs,\n startedAt: p.startedAt,\n completedAt: p.completedAt,\n progressPercent: p.taskGraph.nodes.size > 0\n ? Math.round((Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length / p.taskGraph.nodes.size) * 100)\n : 0,\n taskCount: p.taskGraph.nodes.size,\n completedTasks: Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length,\n assignedAgents: p.assignedAgents,\n isActive: p.id === currentActiveId,\n }));\n\n const taskItems = activePhase\n ? Array.from(activePhase.taskGraph.nodes.values()).map((t) => ({\n id: t.id,\n title: t.title,\n description: t.description,\n status: t.status,\n priority: t.priority,\n type: t.type,\n estimateHours: t.estimateHours,\n actualHours: t.actualHours,\n assignee: t.assignee,\n tags: t.tags || [],\n startedAt: t.startedAt,\n completedAt: t.completedAt,\n }))\n : [];\n\n const completedPhases = phases.filter((p) => p.status === 'completed').length;\n\n return {\n title: this.graph.title,\n phases: phaseItems,\n tasks: taskItems,\n activePhaseId: currentActiveId,\n overallPercent: phases.length > 0 ? Math.round((completedPhases / phases.length) * 100) : 0,\n autonomous: this.graph.autonomous,\n totalTasks,\n completedTasks,\n };\n }\n\n private sendState(client: WSClient): void {\n if (!this.graph) return;\n const state = this.buildState();\n this.send(client, { type: 'autophase.state', payload: state });\n }\n\n private broadcast(msg: { type: string; payload: unknown }): void {\n const data = JSON.stringify(msg);\n for (const client of this.clients) {\n if (client.ws.readyState === 1) { // OPEN\n client.ws.send(data);\n }\n }\n }\n\n private send(client: WSClient, msg: { type: string; payload: unknown }): void {\n if (client.ws.readyState === 1) {\n client.ws.send(JSON.stringify(msg));\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { WebSocket } from 'ws';\nimport type { CollaborationBus, EventBus, Logger } from '@wrongstack/core';\nimport type { AnnotationsStore, SessionReader } from '@wrongstack/core/storage';\nimport type {\n CollabRole,\n WSCollabParticipantJoined,\n WSCollabParticipantLeft,\n WSCollabState,\n WSServerMessage,\n} from '../types.js';\n\n/** How many historical events to replay to a late-joining observer. */\nconst REPLAY_LIMIT = 50;\n\n/** How long the middleware waits before auto-resuming (mirrors the middleware default). */\nconst PAUSE_TIMEOUT_MS = 60_000;\n\n/**\n * CollaborationWebSocketHandler — passive read-only session observer (Phase 1\n * of idea #13 from IDEAS.md). Mirrors `WorktreeWebSocketHandler` and\n * `AutoPhaseWebSocketHandler`.\n *\n * Capabilities in this phase:\n * - A second human (or any client) joins an active agent run as an\n * `observer` and receives a live mirror of the kernel's iteration /\n * tool / subagent events.\n * - The observer declares a `sessionId` on join (used for state scoping\n * and future replay-on-join). Live event routing is session-agnostic\n * for now — see the limitation note below.\n * - The observer can leave at any time; cleanup runs on WS close/error.\n * - The observer CANNOT modify the agent's state, pause it, or inject\n * tool calls. Those capabilities land in Phase 2/3.\n *\n * Limitation (documented, acceptable for Phase 1):\n * The webui server multiplexes every active session onto a single\n * EventBus, and most event payloads (`tool.started`, `iteration.*`,\n * `subagent.*`) do NOT carry a `sessionId` field. The webui's primary\n * WS path works because it is the only consumer and assumes one\n * active session at a time. We mirror that assumption here. When a\n * future multi-session \"session router\" lands, this handler will be\n * upgraded to filter by sessionId.\n *\n * Protocol additions (see `packages/webui/src/types.ts`):\n * client → server: collab.join { sessionId, role: 'observer' }\n * collab.leave { sessionId }\n * server → client: collab.state (initial + 2s periodic)\n * collab.participant.joined\n * collab.participant.left\n * collab.event (live kernel event mirror)\n */\nexport class CollaborationWebSocketHandler {\n private readonly clients = new Set<WebSocket>();\n /** sessionId → participants currently watching it. */\n private readonly bySession = new Map<string, Set<Participant>>();\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n private readonly offs: Array<() => void> = [];\n\n constructor(\n private readonly events: EventBus,\n private readonly logger: Logger,\n /**\n * Optional reader over the on-disk session log. When provided, late\n * joiners receive the last `REPLAY_LIMIT` events of the joined\n * session before live mirroring begins. Without a reader, joining\n * is still allowed — the observer simply starts from \"now\" with no\n * historical context.\n */\n private readonly reader?: SessionReader,\n /**\n * Optional sidecar store for collaboration annotations. Required\n * for the `annotator` role — without it, `collab.annotate` messages\n * are rejected with an error.\n */\n private readonly annotations?: AnnotationsStore,\n /**\n * Optional kernel-level pause/resume bus. Required for the\n * `controller` role — without it, `collab.request_pause` is rejected\n * with an error. Wired to the agent's `toolCall` pipeline via\n * `collabPauseMiddleware` in the webui server boot.\n */\n private readonly bus?: CollaborationBus,\n ) {\n this.subscribe();\n }\n\n // ── Public API (called by server/index.ts per WS connection) ───────────\n\n addClient(ws: WebSocket): void {\n this.clients.add(ws);\n this.ensureBroadcast();\n ws.on('close', () => this.handleDisconnect(ws));\n ws.on('error', () => this.handleDisconnect(ws));\n }\n\n dispose(): void {\n for (const off of this.offs) off();\n this.offs.length = 0;\n this.stopBroadcast();\n }\n\n // ── Inbound client messages ────────────────────────────────────────────\n\n /**\n * Dispatch a parsed client message. Returns true when the message was\n * recognized and handled; false when the caller should ignore / log.\n * Phase 1 only knows `collab.join` and `collab.leave`; unknown types\n * return false so the upstream router can decide.\n */\n handleMessage(\n ws: WebSocket,\n msg: { type: string; payload?: unknown },\n ): boolean {\n if (msg.type === 'collab.join') {\n const payload = msg.payload as { sessionId?: string; role?: CollabRole } | undefined;\n if (!payload?.sessionId) {\n this.send(ws, this.errorMessage('collab.join requires sessionId'));\n return true;\n }\n // The `role` field is accepted on the wire for forward-compat;\n // 'controller' (Phase 3) is not yet wired and is rejected here.\n this.join(ws, payload.sessionId, payload.role ?? 'observer');\n return true;\n }\n if (msg.type === 'collab.leave') {\n this.leave(ws);\n return true;\n }\n if (msg.type === 'collab.annotate') {\n void this.handleAnnotate(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.resolve') {\n void this.handleResolve(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.request_pause') {\n void this.handleRequestPause(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.resume') {\n void this.handleResume(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.grant_control') {\n void this.handleGrantControl(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.inject_tool') {\n void this.handleInjectTool(ws, msg.payload);\n return true;\n }\n return false;\n }\n\n // ── Join / leave flow ──────────────────────────────────────────────────\n\n private join(ws: WebSocket, sessionId: string, role: CollabRole): void {\n if (role === 'controller' && !this.bus) {\n this.send(\n ws,\n this.errorMessage(\n `role 'controller' is not available: server has no CollaborationBus`,\n ),\n );\n return;\n }\n if (role === 'annotator' && !this.annotations) {\n this.send(\n ws,\n this.errorMessage(\n `role 'annotator' is not available: server has no annotations store`,\n ),\n );\n return;\n }\n const participant: Participant = {\n participantId: randomUUID(),\n ws,\n sessionId,\n role,\n joinedAt: new Date().toISOString(),\n };\n let bucket = this.bySession.get(sessionId);\n if (!bucket) {\n bucket = new Set();\n this.bySession.set(sessionId, bucket);\n }\n bucket.add(participant);\n\n // Per-participant hello: send the current state snapshot immediately\n // so the new observer knows who else is watching. Then broadcast the\n // join event AND a fresh state to every participant (including the\n // newcomer) so existing observers see the updated count without\n // waiting for the 2s timer.\n this.send(ws, this.stateMessage(sessionId));\n this.broadcast(sessionId, {\n type: 'collab.participant.joined',\n payload: {\n participantId: participant.participantId,\n sessionId,\n role,\n joinedAt: participant.joinedAt,\n },\n });\n this.broadcast(sessionId, this.stateMessage(sessionId));\n\n // Replay last N events to give the late joiner historical context.\n // Best-effort: failures are logged and silently ignored — the live\n // mirror continues regardless.\n if (this.reader) {\n this.replayHistory(ws, sessionId).catch((err) => {\n this.logger.debug?.(\n `collab: replay failed for ${sessionId}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n }\n this.logger.debug?.(\n `collab: participant ${participant.participantId} joined ${sessionId}`,\n );\n }\n\n private leave(ws: WebSocket): void {\n this.handleDisconnect(ws);\n }\n\n private handleDisconnect(ws: WebSocket): void {\n this.clients.delete(ws);\n // Remove from every session bucket the WS may have joined (a single\n // WS is in at most one bucket in Phase 1, but the loop is cheap and\n // future-proofs multi-session observers).\n //\n // Order matters:\n // 1. Send `participant.left` to the leaving ws so they get a\n // confirmation that their leave registered.\n // 2. Delete from bucket.\n // 3. Broadcast the fresh state to remaining observers so they\n // see the updated count without waiting for the 2s timer.\n for (const [sessionId, bucket] of this.bySession) {\n for (const p of bucket) {\n if (p.ws === ws) {\n const leftEvent = {\n type: 'collab.participant.left' as const,\n payload: { participantId: p.participantId, sessionId },\n };\n // Send directly to the leaving ws first so they get an\n // immediate confirmation, then broadcast to the rest of the\n // bucket (which is still inclusive of the leaving ws here —\n // the per-iteration below strips it out).\n this.send(ws, leftEvent);\n bucket.delete(p);\n if (bucket.size === 0) {\n this.bySession.delete(sessionId);\n } else {\n this.broadcast(sessionId, leftEvent);\n this.broadcast(sessionId, this.stateMessage(sessionId));\n }\n break;\n }\n }\n }\n if (this.bySession.size === 0) this.stopBroadcast();\n }\n\n // ── Annotation flow (Phase 2) ───────────────────────────────────────────\n\n /**\n * Look up the participant record for a given WS across all sessions.\n * Returns null when the WS hasn't joined (e.g. the client sent a\n * `collab.annotate` before `collab.join`).\n */\n private findParticipant(ws: WebSocket): Participant | null {\n for (const bucket of this.bySession.values()) {\n for (const p of bucket) {\n if (p.ws === ws) return p;\n }\n }\n return null;\n }\n\n private async handleAnnotate(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.annotations) {\n this.send(ws, this.errorMessage('annotations store is not configured'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('annotate requires an active join'));\n return;\n }\n if (participant.role !== 'annotator') {\n this.send(\n ws,\n this.errorMessage(\n `annotate requires the 'annotator' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | { sessionId?: string; atEventIndex?: number; text?: string }\n | undefined;\n if (\n !payload?.sessionId ||\n typeof payload.atEventIndex !== 'number' ||\n typeof payload.text !== 'string'\n ) {\n this.send(\n ws,\n this.errorMessage('annotate requires { sessionId, atEventIndex, text }'),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `annotate sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n try {\n const annotation = await this.annotations.add({\n sessionId: payload.sessionId,\n atEventIndex: payload.atEventIndex,\n authorId: participant.participantId,\n text: payload.text,\n });\n this.broadcast(payload.sessionId, {\n type: 'collab.annotation.added',\n payload: {\n sessionId: payload.sessionId,\n annotation: {\n id: annotation.id,\n atEventIndex: annotation.atEventIndex,\n authorId: annotation.authorId,\n authorRole: annotation.authorRole,\n text: annotation.text,\n createdAt: annotation.createdAt,\n resolved: annotation.resolved,\n },\n },\n });\n } catch (err) {\n this.send(\n ws,\n this.errorMessage(\n `annotation rejected: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n );\n }\n }\n\n private async handleResolve(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.annotations) {\n this.send(ws, this.errorMessage('annotations store is not configured'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('resolve requires an active join'));\n return;\n }\n if (participant.role !== 'annotator') {\n this.send(\n ws,\n this.errorMessage(\n `resolve requires the 'annotator' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | { sessionId?: string; annotationId?: string }\n | undefined;\n if (!payload?.sessionId || !payload.annotationId) {\n this.send(\n ws,\n this.errorMessage('resolve requires { sessionId, annotationId }'),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `resolve sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n try {\n const updated = await this.annotations.resolve({\n sessionId: payload.sessionId,\n annotationId: payload.annotationId,\n resolvedBy: participant.participantId,\n });\n if (!updated) {\n this.send(\n ws,\n this.errorMessage(`annotation not found: ${payload.annotationId}`),\n );\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.annotation.resolved',\n payload: {\n sessionId: payload.sessionId,\n annotationId: updated.id,\n resolvedBy: updated.resolvedBy ?? participant.participantId,\n resolvedAt: updated.resolvedAt ?? new Date().toISOString(),\n },\n });\n } catch (err) {\n this.send(\n ws,\n this.errorMessage(\n `resolve failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n );\n }\n }\n\n // ── Event subscription (live mirror) ───────────────────────────────────\n\n private subscribe(): void {\n // Same trick as WorktreeWebSocketHandler: bind a single typed-on helper\n // to a string-keyed signature so we can register many handlers.\n const on = this.events.on.bind(this.events) as unknown as (\n ev: string,\n fn: (p: unknown) => void,\n ) => () => void;\n\n // Mirror every event an observer would care about. Each is forwarded\n // to all joined participants as a generic `collab.event` envelope so\n // the client can render a flowing activity strip. Filtering /\n // denormalization happens on the client.\n const forwarded: Array<[string, string]> = [\n ['iteration.started', 'iteration.started'],\n ['iteration.completed', 'iteration.completed'],\n ['tool.started', 'tool.started'],\n ['tool.progress', 'tool.progress'],\n ['tool.executed', 'tool.executed'],\n ['tool.confirm_needed', 'tool.confirm_needed'],\n ['subagent.spawned', 'subagent.spawned'],\n ['subagent.task_started', 'subagent.task_started'],\n ['subagent.iteration_summary', 'subagent.iteration_summary'],\n ['subagent.task_completed', 'subagent.task_completed'],\n ['subagent.done', 'subagent.done'],\n ];\n for (const [kernelEvent, kind] of forwarded) {\n this.offs.push(\n on(kernelEvent, (raw) => {\n // Best-effort payload shape: we don't deeply validate, but we\n // make sure it's serializable. Observers must never receive\n // non-serializable objects (Functions, circular refs).\n let payload: unknown = raw;\n try {\n payload = JSON.parse(JSON.stringify(raw));\n } catch {\n // Skip unserializable payloads — better to drop than to crash\n // the broadcast loop.\n return;\n }\n this.broadcastEvent(kind, payload);\n }),\n );\n }\n }\n\n private broadcastEvent(kind: string, payload: unknown): void {\n if (this.bySession.size === 0) return; // nobody watching — no-op\n const msg: WSServerMessage = {\n type: 'collab.event',\n payload: { kind, payload, at: new Date().toISOString() },\n };\n const data = JSON.stringify(msg);\n for (const bucket of this.bySession.values()) {\n for (const p of bucket) {\n try {\n if (p.ws.readyState === 1) p.ws.send(data);\n } catch (err) {\n this.logger.debug?.(\n `collab broadcast failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n }\n\n /**\n * Replay the last `REPLAY_LIMIT` events from the on-disk session log\n * to a single observer (the late joiner). Each event is forwarded as\n * a `collab.event` with `replay: true` so the client can distinguish\n * history from the live stream.\n *\n * The session log stores typed `SessionEvent`s (`user_input`,\n * `llm_response`, `tool_result`, etc.) — different from the kernel's\n * bus events. We translate the most useful subset (`tool.*` and\n * `iteration.*`-shaped ones) into the same `kind` namespace the live\n * mirror uses, so the client can render a single activity strip.\n */\n private async replayHistory(ws: WebSocket, sessionId: string): Promise<void> {\n if (!this.reader) return;\n const all: unknown[] = [];\n try {\n for await (const ev of this.reader.replay(sessionId)) {\n all.push(ev);\n }\n } catch (err) {\n this.logger.debug?.(\n `collab: session reader rejected ${sessionId}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n return;\n }\n const tail = all.slice(-REPLAY_LIMIT);\n if (tail.length === 0) return; // nothing to replay\n for (const raw of tail) {\n const ev = raw as { type?: string; ts?: string; [k: string]: unknown };\n const kind = this.historyEventToKind(ev);\n if (!kind) continue; // skip events we don't know how to mirror\n this.send(ws, {\n type: 'collab.event',\n payload: {\n kind,\n payload: ev,\n at: ev.ts ?? new Date().toISOString(),\n replay: true,\n },\n });\n }\n }\n\n /**\n * Map a stored `SessionEvent` to a `collab.event.kind` so the live\n * strip and the history strip can share a single rendering path.\n * Returns null for events that don't have a meaningful live analog\n * (e.g. `session_start`, file-snapshot bookkeeping, rewind markers).\n */\n private historyEventToKind(ev: { type?: string }): string | null {\n switch (ev.type) {\n case 'user_input':\n return 'user_input';\n case 'llm_response':\n return 'llm_response';\n case 'tool_result':\n return 'tool.executed';\n case 'compaction':\n return 'compaction';\n case 'error':\n return 'error';\n default:\n return null;\n }\n }\n\n // ── State snapshot + periodic broadcast ────────────────────────────────\n\n private stateMessage(sessionId: string): WSCollabState {\n const bucket = this.bySession.get(sessionId);\n return {\n type: 'collab.state',\n payload: {\n sessionId,\n participants: bucket\n ? [...bucket].map((p) => ({\n participantId: p.participantId,\n role: p.role,\n joinedAt: p.joinedAt,\n }))\n : [],\n },\n };\n }\n\n private ensureBroadcast(): void {\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => {\n for (const sessionId of this.bySession.keys()) {\n this.broadcast(sessionId, this.stateMessage(sessionId));\n }\n }, 2000);\n }\n\n private stopBroadcast(): void {\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcast(sessionId: string, msg: WSServerMessage): void {\n const data = JSON.stringify(msg);\n const bucket = this.bySession.get(sessionId);\n if (!bucket) return;\n for (const p of bucket) {\n try {\n if (p.ws.readyState === 1) p.ws.send(data);\n } catch (err) {\n this.logger.debug?.(\n `collab broadcast failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n\n private send(ws: WebSocket, msg: WSServerMessage): void {\n try {\n if (ws.readyState === 1) ws.send(JSON.stringify(msg));\n } catch {\n /* client gone */\n }\n }\n\n private errorMessage(detail: string): WSServerMessage {\n return { type: 'error', payload: { phase: 'collab', message: detail } };\n }\n\n // ── Controller flow (Phase 3) ───────────────────────────────────────────\n\n private async handleRequestPause(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('pause requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('pause requires an active join'));\n return;\n }\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `pause requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as { sessionId?: string } | undefined;\n if (!payload?.sessionId || payload.sessionId !== participant.sessionId) {\n this.send(ws, this.errorMessage('pause sessionId mismatch'));\n return;\n }\n const transitioned = this.bus.requestPause(participant.participantId);\n if (!transitioned) {\n // Already paused — surface the current state to the requester.\n const s = this.bus.getState();\n this.send(ws, {\n type: 'error',\n payload: {\n phase: 'collab',\n message: `bus already paused by ${s.pausedBy ?? '?'} at ${s.pausedAt ?? '?'}`,\n },\n });\n return;\n }\n const s = this.bus.getState();\n this.broadcast(payload.sessionId, {\n type: 'collab.pause.granted',\n payload: {\n sessionId: payload.sessionId,\n pausedBy: s.pausedBy ?? participant.participantId,\n pausedAt: s.pausedAt ?? new Date().toISOString(),\n autoResumeInMs: PAUSE_TIMEOUT_MS,\n },\n });\n }\n\n private async handleResume(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('resume requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('resume requires an active join'));\n return;\n }\n // Permission: controller OR the original pauser. We do a simple\n // \"any controller can release\" check — fine for Phase 3, can be\n // tightened to \"only the pauser\" later.\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `resume requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as { sessionId?: string } | undefined;\n if (!payload?.sessionId || payload.sessionId !== participant.sessionId) {\n this.send(ws, this.errorMessage('resume sessionId mismatch'));\n return;\n }\n const transitioned = this.bus.resume();\n if (!transitioned) {\n this.send(ws, this.errorMessage('bus is not currently paused'));\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.pause.released',\n payload: {\n sessionId: payload.sessionId,\n reason: 'controller',\n at: new Date().toISOString(),\n },\n });\n }\n\n private async handleGrantControl(ws: WebSocket, raw: unknown): Promise<void> {\n // Phase 3 metadata-only: record the grant in the log; the\n // existing controller's effective permissions do not change.\n // A future iteration can wire this to a per-participant RBAC\n // table that the `handleRequestPause`/`handleResume` checks read.\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('grant_control requires an active join'));\n return;\n }\n const payload = raw as\n | { sessionId?: string; toParticipant?: string }\n | undefined;\n if (\n !payload?.sessionId ||\n !payload.toParticipant ||\n payload.sessionId !== participant.sessionId\n ) {\n this.send(ws, this.errorMessage('grant_control requires { sessionId, toParticipant }'));\n return;\n }\n this.logger.debug?.(\n `collab: control granted from ${participant.participantId} to ${payload.toParticipant} in ${payload.sessionId}`,\n );\n }\n\n /**\n * Phase 4 — handle a controller's manual tool-call injection.\n * Validates the payload, queues it on the bus, and broadcasts\n * the grant so observers see what just happened. The actual\n * splice into the agent's pipeline is performed by the\n * `collabInjectMiddleware` on the next tool call.\n */\n private async handleInjectTool(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('inject_tool requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('inject_tool requires an active join'));\n return;\n }\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `inject_tool requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | {\n sessionId?: string;\n toolUseId?: string;\n content?: unknown;\n isError?: boolean;\n reason?: string;\n }\n | undefined;\n if (\n !payload?.sessionId ||\n !payload.toolUseId ||\n typeof payload.isError !== 'boolean' ||\n typeof payload.reason !== 'string' ||\n payload.content === undefined\n ) {\n this.send(\n ws,\n this.errorMessage(\n 'inject_tool requires { sessionId, toolUseId, content, isError, reason }',\n ),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `inject_tool sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n const queued = this.bus.injectToolResult({\n toolUseId: payload.toolUseId,\n content: payload.content,\n isError: payload.isError,\n reason: payload.reason,\n authorId: participant.participantId,\n });\n if (!queued) {\n this.send(\n ws,\n this.errorMessage(\n `an injection for toolUseId ${payload.toolUseId} is already queued`,\n ),\n );\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.injection.granted',\n payload: {\n sessionId: payload.sessionId,\n toolUseId: payload.toolUseId,\n // The tool name is unknown here (the injection is queued\n // before the model produces the tool call). We surface a\n // placeholder; the middleware will emit a `consumed` event\n // with the real name on match.\n toolName: '(pending match)',\n authorId: participant.participantId,\n reason: payload.reason,\n isError: payload.isError,\n phase: 'queued',\n at: new Date().toISOString(),\n },\n });\n }\n}\n\ninterface Participant {\n participantId: string;\n ws: WebSocket;\n sessionId: string;\n role: CollabRole;\n joinedAt: string;\n}\n","import type { WebSocket } from 'ws';\nimport type { EventBus, Logger } from '@wrongstack/core';\nimport type { WorktreeHandleView, WSServerMessage } from '../types.js';\n\nconst MAX_ACTIVITY = 6;\n\n/**\n * WorktreeWebSocketHandler — mirrors AutoPhaseWebSocketHandler. Subscribes to\n * the shared EventBus `worktree.*` lifecycle events, keeps a live snapshot of\n * every worktree, and broadcasts:\n * - `worktree.event` incrementally (drives the flowing activity strip)\n * - `worktree.state` on connect + on a 2s timer (drives swim-lanes/DAG)\n */\nexport class WorktreeWebSocketHandler {\n private readonly clients = new Set<WebSocket>();\n private readonly handles = new Map<string, WorktreeHandleView>();\n private baseBranch = '';\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n private readonly offs: Array<() => void> = [];\n\n constructor(\n private readonly events: EventBus,\n private readonly logger: Logger,\n ) {\n this.subscribe();\n }\n\n addClient(ws: WebSocket): void {\n this.clients.add(ws);\n ws.on('close', () => this.clients.delete(ws));\n ws.on('error', () => this.clients.delete(ws));\n this.send(ws, this.stateMessage());\n }\n\n dispose(): void {\n for (const off of this.offs) off();\n this.offs.length = 0;\n this.stopBroadcast();\n }\n\n // ── internals ───────────────────────────────────────────────────────────\n\n private subscribe(): void {\n const on = this.events.on.bind(this.events) as unknown as (\n ev: string,\n fn: (p: unknown) => void,\n ) => () => void;\n\n this.offs.push(\n on('worktree.allocated', (p) => {\n const e = p as { handleId: string; ownerId: string; ownerLabel: string; branch: string; baseBranch: string };\n this.baseBranch = e.baseBranch || this.baseBranch;\n this.upsert(e.handleId, {\n handleId: e.handleId,\n ownerId: e.ownerId,\n ownerLabel: e.ownerLabel,\n branch: e.branch,\n baseBranch: e.baseBranch,\n status: 'active',\n insertions: 0,\n deletions: 0,\n files: 0,\n allocatedAt: Date.now(),\n lastEventAt: Date.now(),\n recentActivity: [],\n });\n this.activity(e.handleId, 'allocated', `branch ${e.branch}`);\n this.ensureBroadcast();\n }),\n on('worktree.committed', (p) => {\n const e = p as { handleId: string; insertions: number; deletions: number; files: number; committed: boolean };\n this.patch(e.handleId, { status: 'committing', insertions: e.insertions, deletions: e.deletions, files: e.files });\n if (e.committed) this.activity(e.handleId, 'committed', `+${e.insertions}/-${e.deletions} (${e.files}f)`);\n this.broadcastState();\n }),\n on('worktree.merged', (p) => {\n const e = p as { handleId: string; baseBranch: string };\n this.patch(e.handleId, { status: 'merged' });\n this.activity(e.handleId, 'merged', `→ ${e.baseBranch}`);\n this.broadcastState();\n }),\n on('worktree.conflict', (p) => {\n const e = p as { handleId: string; conflictFiles: string[] };\n this.patch(e.handleId, { status: 'needs-review', conflictFiles: e.conflictFiles });\n this.activity(e.handleId, 'conflict', e.conflictFiles.join(', '));\n this.broadcastState();\n }),\n on('worktree.failed', (p) => {\n const e = p as { handleId: string; error: string };\n this.patch(e.handleId, { status: 'failed' });\n this.activity(e.handleId, 'failed', e.error);\n this.broadcastState();\n }),\n on('worktree.released', (p) => {\n const e = p as { handleId: string; kept: boolean };\n if (!e.kept) this.handles.delete(e.handleId);\n this.activity(e.handleId, 'released', e.kept ? 'kept for review' : 'removed');\n if (this.handles.size === 0) this.stopBroadcast();\n else this.broadcastState();\n }),\n );\n }\n\n private upsert(id: string, view: WorktreeHandleView): void {\n this.handles.set(id, view);\n }\n\n private patch(id: string, patch: Partial<WorktreeHandleView>): void {\n const cur = this.handles.get(id);\n if (!cur) return;\n this.handles.set(id, { ...cur, ...patch, lastEventAt: Date.now() });\n }\n\n private activity(id: string, kind: string, text: string): void {\n const cur = this.handles.get(id);\n if (cur) {\n const recentActivity = [...cur.recentActivity, { kind, text, at: Date.now() }].slice(-MAX_ACTIVITY);\n this.handles.set(id, { ...cur, recentActivity });\n }\n this.broadcast({ type: 'worktree.event', payload: { kind, handleId: id, text, at: Date.now() } });\n }\n\n private stateMessage(): WSServerMessage {\n return {\n type: 'worktree.state',\n payload: { worktrees: [...this.handles.values()], baseBranch: this.baseBranch },\n };\n }\n\n private broadcastState(): void {\n this.broadcast(this.stateMessage());\n }\n\n private ensureBroadcast(): void {\n this.broadcast(this.stateMessage());\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => this.broadcast(this.stateMessage()), 2000);\n }\n\n private stopBroadcast(): void {\n this.broadcast(this.stateMessage());\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcast(msg: WSServerMessage): void {\n const data = JSON.stringify(msg);\n for (const ws of this.clients) {\n try {\n if (ws.readyState === 1) ws.send(data);\n } catch (err) {\n this.logger.debug?.(`worktree broadcast failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n }\n\n private send(ws: WebSocket, msg: WSServerMessage): void {\n try {\n if (ws.readyState === 1) ws.send(JSON.stringify(msg));\n } catch {\n /* client gone */\n }\n }\n}\n","/**\n * WebSocket connection authentication for the WebUI server.\n *\n * Three layered defenses, all enforced in {@link verifyClient}:\n * 1. **DNS-rebinding guard** ({@link hostHeaderOk}) — on a loopback bind the\n * `Host` header must itself be a loopback name, so a rebound attacker page\n * (`Host: evil.com`) is rejected even though its TCP peer is 127.0.0.1.\n * 2. **Shared-token auth** ({@link tokenMatches}, constant-time) — required for\n * any non-loopback origin and for non-browser clients reaching a publicly\n * bound socket.\n * 3. **Loopback bootstrap** — same-machine browser origins are allowed without\n * a token (the token is delivered in `session.start` and replayed on\n * reconnect); the Host-header guard above already blocks cross-site pages.\n *\n * Extracted from `index.ts` as pure functions so the auth contract can be unit\n * tested without standing up a real `http.Server`/`WebSocketServer`. `index.ts`\n * builds a thin closure that pulls the fields below off the incoming request.\n */\nimport { Buffer } from 'node:buffer';\nimport { timingSafeEqual } from 'node:crypto';\n\n/** A hostname that refers to the local machine. */\nexport function isLoopbackHostname(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '[::1]'\n );\n}\n\n/** True when the server is bound to a loopback interface (vs. LAN/0.0.0.0). */\nexport function isLoopbackBind(wsHost: string): boolean {\n return wsHost === '127.0.0.1' || wsHost === '::1' || wsHost === 'localhost';\n}\n\n/**\n * Constant-time comparison of a provided token against the expected one.\n * A length mismatch short-circuits (lengths aren't secret); equal-length\n * inputs are compared with `timingSafeEqual` so the token can't be recovered\n * byte-by-byte via response timing.\n */\nexport function tokenMatches(provided: string | undefined, expected: string): boolean {\n if (!provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(expected);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\n/** Pull the `token` query param out of a request URL (`/?token=…`). */\nexport function extractToken(url: string): string | undefined {\n const match = url.match(/[?&]token=([^&]+)/);\n return match ? match[1] : undefined;\n}\n\n/**\n * DNS-rebinding defense. On a loopback bind, the `Host` header must resolve to\n * a loopback name. When the operator deliberately exposes the socket (wsHost is\n * a LAN/0.0.0.0 address) the Host is legitimately non-loopback, so the guard is\n * skipped and connection auth falls to the token check.\n */\nexport function hostHeaderOk(input: { hostHeader: string | undefined; wsHost: string }): boolean {\n if (!isLoopbackBind(input.wsHost)) return true; // operator opted into wider exposure\n const hostHeader = (input.hostHeader ?? '').trim();\n if (!hostHeader) return false;\n // Strip the port (handle bare host, host:port, and [::1]:port).\n let hostname: string;\n try {\n hostname = new URL(`http://${hostHeader}`).hostname;\n } catch {\n return false;\n }\n return isLoopbackHostname(hostname);\n}\n\nexport interface VerifyClientInput {\n /** Browser `Origin` header, or undefined for non-browser clients. */\n origin?: string;\n /** Request URL (`req.url`) — carries the `?token=…` query param. */\n url: string;\n /** `Host` header (`req.headers.host`). */\n hostHeader?: string;\n /** Peer address (`req.socket.remoteAddress`). */\n remoteAddress?: string;\n /** Host/interface the WS server is bound to. */\n wsHost: string;\n /** The server's generated auth token. */\n expectedToken: string;\n}\n\n/**\n * Decide whether to accept an incoming WebSocket handshake. Pure mirror of the\n * closure previously inlined in `index.ts`; see the module doc for the layered\n * policy. Returns `true` to accept, `false` to reject.\n */\nexport function verifyClient(input: VerifyClientInput): boolean {\n const { origin, url, hostHeader, remoteAddress, wsHost, expectedToken } = input;\n const tokenOk = tokenMatches(extractToken(url ?? ''), expectedToken);\n\n // DNS-rebinding guard runs first on a loopback bind — independent of token\n // and Origin. Blocks a rebound attacker page (Host = attacker domain) even\n // though the TCP peer is 127.0.0.1.\n if (!hostHeaderOk({ hostHeader, wsHost })) return false;\n\n if (!origin) {\n // Non-browser clients (curl, scripts): require token unless on loopback.\n // When wsHost=0.0.0.0 the server accepts connections from any network\n // interface — a non-loopback peer is denied outright.\n const remoteIp = remoteAddress ?? '';\n const isRemoteLoopback = remoteIp === '127.0.0.1' || remoteIp === '::1';\n if (!isRemoteLoopback && wsHost === '0.0.0.0') return false; // LAN exposure = deny\n return tokenOk || isLoopbackBind(wsHost);\n }\n try {\n const { hostname } = new URL(origin);\n // Loopback browser origins: allow without token (bootstrap). The Host-header\n // guard above already rejects cross-site/rebinding pages here.\n if (isLoopbackHostname(hostname)) return true;\n // Non-loopback origins: token is mandatory.\n return tokenOk;\n } catch {\n return false;\n }\n}\n","/**\n * Process lifecycle for the WebUI server: graceful shutdown and the\n * SIGINT/SIGTERM wiring that triggers it.\n *\n * On a termination signal we (best-effort) flush + close the active session,\n * close every connected WebSocket, stop the HTTP and WS servers, then exit.\n * A re-entrancy guard makes a second signal during shutdown a no-op (rapid\n * double Ctrl+C no longer runs the teardown twice).\n *\n * Extracted from `index.ts` as a parameterized factory so the teardown\n * sequence can be unit tested without a real process signal, server, or\n * `process.exit` — `log` and `exit` are injectable seams.\n */\n\nexport interface LifecycleResources {\n /** Persist + close the active session (best-effort; errors are logged). */\n flushSession: () => Promise<void>;\n /**\n * Returns the currently-connected client sockets to close. A thunk (not a\n * snapshot) so shutdown closes whoever is connected *at signal time*, not\n * whoever was connected when the handler was registered.\n */\n clients: () => Iterable<{ close: () => void }>;\n /** Servers to stop (HTTP + WS). `null`/`undefined` entries are skipped. */\n servers: Array<{ close: () => void } | null | undefined>;\n /**\n * Optional best-effort cleanup run after the session flush and before exit\n * (e.g. removing this process from the running-instance registry). Errors are\n * logged, never thrown — cleanup must not block a clean shutdown.\n */\n onShutdown?: () => Promise<void> | void;\n /** Output sink. Defaults to `console.log`. */\n log?: (msg: string) => void;\n /** Process exit. Defaults to `process.exit`. Injectable for tests. */\n exit?: (code: number) => void;\n}\n\n/**\n * Build the graceful-shutdown handler. Returns an idempotent async function:\n * the first call runs the teardown, subsequent calls (e.g. a second SIGINT)\n * return immediately.\n */\nexport function createShutdown(res: LifecycleResources): () => Promise<void> {\n const log = res.log ?? ((m: string) => console.log(m));\n const exit = res.exit ?? ((code: number) => process.exit(code));\n let shuttingDown = false;\n\n return async () => {\n if (shuttingDown) return; // a second signal during teardown is a no-op\n shuttingDown = true;\n\n log('[WebUI] Shutting down...');\n try {\n await res.flushSession();\n } catch (e) {\n log(`[WebUI] Error closing session: ${e instanceof Error ? e.message : String(e)}`);\n }\n for (const ws of res.clients()) ws.close();\n for (const server of res.servers) server?.close();\n if (res.onShutdown) {\n try {\n await res.onShutdown();\n } catch (e) {\n log(`[WebUI] Error during shutdown cleanup: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n exit(0);\n };\n}\n\n/**\n * Register the shutdown handler on SIGINT and SIGTERM. Returns an unregister\n * function that detaches both listeners (useful for tests and clean restarts).\n */\nexport function registerShutdownHandlers(res: LifecycleResources): () => void {\n const shutdown = createShutdown(res);\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n return () => {\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n };\n}\n","/**\n * Running-instance registry for the standalone WebUI server.\n *\n * Every live `webui` process records itself in a single JSON file under the\n * wstack home dir (`~/.wrongstack/webui-instances.json`) so a user running\n * several instances (one per project, or several per project on different\n * ports) can see at a glance which ports are open for which path.\n *\n * Design notes:\n * - **Self-healing**: every register/unregister/list prunes entries whose PID\n * is no longer alive (`process.kill(pid, 0)`), so a crashed instance that\n * never got to unregister doesn't leave a ghost behind.\n * - **Atomic writes**: the file is rewritten via `atomicWrite` (tmp + rename),\n * so a concurrent reader never sees a half-written file. Two instances\n * starting at the *exact* same millisecond could still race the\n * read-modify-write — acceptable for a best-effort tracking file, and the\n * next register() heals any dropped entry.\n * - **Best-effort**: a failure to read/write the registry must NEVER take the\n * server down. Callers wrap these in `.catch()`.\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as fs from 'node:fs/promises';\nimport { atomicWrite } from '@wrongstack/core';\n\n/** One running WebUI process. */\nexport interface WebUIInstanceRecord {\n /** OS process id — also the liveness key. */\n pid: number;\n /** HTTP port serving the React frontend. */\n httpPort: number;\n /** WebSocket port for the agent backend. */\n wsPort: number;\n /** Bind host (e.g. 127.0.0.1 or 0.0.0.0). */\n host: string;\n /** Absolute project root the instance booted against. */\n projectRoot: string;\n /** Display name (basename of projectRoot). */\n projectName: string;\n /** ISO timestamp when the instance registered. */\n startedAt: string;\n /** Convenience open-in-browser URL. */\n url: string;\n}\n\ninterface RegistryFile {\n version: 1;\n instances: WebUIInstanceRecord[];\n}\n\n/** Default wstack home dir (`~/.wrongstack`). Callers may override the base. */\nexport function defaultBaseDir(): string {\n return path.join(os.homedir(), '.wrongstack');\n}\n\n/** Resolve the registry file path for a given base dir. */\nexport function registryPath(baseDir: string = defaultBaseDir()): string {\n return path.join(baseDir, 'webui-instances.json');\n}\n\n/**\n * Liveness probe. `process.kill(pid, 0)` sends no signal — it only checks the\n * process exists. ESRCH ⇒ dead; EPERM ⇒ alive but owned by another user (still\n * counts as alive). Any other error is treated conservatively as \"alive\" so we\n * never prune an instance we simply failed to probe.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\nasync function load(file: string): Promise<RegistryFile> {\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as RegistryFile;\n if (parsed?.version === 1 && Array.isArray(parsed.instances)) {\n return parsed;\n }\n } catch {\n // Missing or corrupt → start fresh.\n }\n return { version: 1, instances: [] };\n}\n\nasync function save(file: string, instances: WebUIInstanceRecord[]): Promise<void> {\n await atomicWrite(file, `${JSON.stringify({ version: 1, instances }, null, 2)}\\n`, {\n mode: 0o600,\n });\n}\n\n/** Drop dead processes and (optionally) one specific pid. */\nfunction prune(instances: WebUIInstanceRecord[], excludePid?: number): WebUIInstanceRecord[] {\n return instances.filter((i) => i.pid !== excludePid && isPidAlive(i.pid));\n}\n\n/**\n * Register (or refresh) this instance. Prunes dead entries and any stale entry\n * for our own PID before adding the current record. Best-effort — rejects only\n * on a hard fs error, which callers swallow.\n */\nexport async function registerInstance(\n record: WebUIInstanceRecord,\n baseDir: string = defaultBaseDir(),\n): Promise<void> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const instances = prune(data.instances, record.pid);\n instances.push(record);\n await save(file, instances);\n}\n\n/** Remove this instance (called on graceful shutdown). Also prunes dead pids. */\nexport async function unregisterInstance(\n pid: number,\n baseDir: string = defaultBaseDir(),\n): Promise<void> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const instances = prune(data.instances, pid);\n await save(file, instances);\n}\n\n/** List live instances, pruning any dead entries encountered. */\nexport async function listInstances(\n baseDir: string = defaultBaseDir(),\n): Promise<WebUIInstanceRecord[]> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const live = prune(data.instances);\n // Persist the pruned view so `cat`-ing the file also shows reality, but never\n // fail the list on a write error.\n if (live.length !== data.instances.length) {\n await save(file, live).catch(() => {});\n }\n return live;\n}\n\n/** Human-readable table of running instances for `webui --list`. */\nexport function formatInstances(instances: WebUIInstanceRecord[]): string {\n if (instances.length === 0) {\n return 'No WebUI instances are currently running.';\n }\n const lines = [`Running WebUI instances (${instances.length}):`, ''];\n for (const i of instances) {\n lines.push(\n ` • ${i.url} · ws:${i.wsPort} · pid ${i.pid}`,\n ` project: ${i.projectName} (${i.projectRoot})`,\n ` since: ${i.startedAt}`,\n );\n }\n return lines.join('\\n');\n}\n","/**\n * Free-port discovery for the standalone WebUI server.\n *\n * When a user runs several instances, the default ports (HTTP 3456 / WS 3457)\n * are taken by the first one. Rather than make the user hand-pick `PORT` /\n * `WS_PORT` for every extra instance, the server probes upward from the\n * requested port and binds the first free one — then stamps that real port into\n * the served HTML and the instance registry so everything stays consistent.\n *\n * The probe binds a throwaway `net.Server`, then closes it, so there is a tiny\n * TOCTOU window between \"found free\" and \"the real server binds it\". For local\n * single-user multi-instance use that race is negligible; if it ever loses, the\n * real bind fails loudly with EADDRINUSE exactly as before.\n */\n\nimport * as net from 'node:net';\n\n/** Resolve true when `port` can be bound on `host`, false on EADDRINUSE/EACCES. */\nexport function isPortFree(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const srv = net.createServer();\n srv.once('error', () => resolve(false));\n srv.once('listening', () => {\n srv.close(() => resolve(true));\n });\n try {\n srv.listen(port, host);\n } catch {\n resolve(false);\n }\n });\n}\n\nexport interface FindFreePortOptions {\n /** Ports to skip even if free (e.g. one already chosen for the sibling server). */\n exclude?: Set<number>;\n /** How many consecutive ports to try before giving up. Default 200. */\n maxTries?: number;\n}\n\n/**\n * Find the first free port at or above `startPort` on `host`, skipping any in\n * `exclude`. Throws if nothing is free within `maxTries` steps.\n */\nexport async function findFreePort(\n host: string,\n startPort: number,\n opts: FindFreePortOptions = {},\n): Promise<number> {\n const exclude = opts.exclude ?? new Set<number>();\n const maxTries = opts.maxTries ?? 200;\n let port = startPort;\n for (let i = 0; i < maxTries; i++) {\n // Stay inside the valid TCP range; wrap into the high ephemeral band if a\n // pathological startPort pushes us past the ceiling.\n if (port > 65535) port = 1024 + (port % 50000);\n if (!exclude.has(port) && (await isPortFree(host, port))) {\n return port;\n }\n port++;\n }\n throw new Error(\n `No free port found near ${startPort} on ${host} after ${maxTries} attempts.`,\n );\n}\n","/**\n * Best-effort \"open this URL in the default browser\" for `--webui --open`.\n *\n * Cross-platform via the OS opener (`start` / `open` / `xdg-open`). Fully\n * fire-and-forget: a missing opener, a headless box, or a spawn failure must\n * NEVER take the server down — the URL is always also printed to the console.\n */\n\nimport { spawn } from 'node:child_process';\n\n/** Resolve the platform's URL-opener command + args. */\nexport function browserOpenCommand(\n url: string,\n platform: NodeJS.Platform = process.platform,\n): { command: string; args: string[] } {\n if (platform === 'win32') {\n // `start` is a cmd builtin; the empty \"\" is the window title slot so URLs\n // containing `&` / spaces are passed through intact.\n return { command: 'cmd', args: ['/c', 'start', '', url] };\n }\n if (platform === 'darwin') {\n return { command: 'open', args: [url] };\n }\n return { command: 'xdg-open', args: [url] };\n}\n\n/** Spawn the OS browser-opener for `url`. Never throws. */\nexport function openBrowser(url: string, platform: NodeJS.Platform = process.platform): void {\n try {\n const { command, args } = browserOpenCommand(url, platform);\n const child = spawn(command, args, { stdio: 'ignore', detached: true });\n // A missing opener (e.g. xdg-open absent on a headless box) surfaces as an\n // async 'error' event — swallow it so it doesn't crash the process.\n child.on('error', () => {});\n child.unref();\n } catch {\n // Synchronous spawn failure — best-effort, ignore.\n }\n}\n","/**\n * Token-usage cost math for the WebUI server.\n *\n * models.dev pricing is expressed in **dollars per 1,000,000 tokens**, and\n * providers omit the field entirely for free/unmetered plans. Both the\n * `session.start` payload (which ships the per-token rates to the client) and\n * `stats.get` (which reports an actual dollar figure) repeated the same\n * \"read `model.cost.*` with a `?? 0` fallback, then divide by 1e6\" logic\n * inline. Pulling it here keeps the rate normalization and the cost formula in\n * one tested place — a wrong field name or a missing `/ 1e6` silently produces\n * a plausible-but-wrong number, which is exactly what a unit test should pin.\n */\n\n/** Per-1,000,000-token pricing, normalized to numbers (0 when unpriced). */\nexport interface CostRates {\n /** $ per 1M input tokens. */\n input: number;\n /** $ per 1M output tokens. */\n output: number;\n /** $ per 1M cache-read tokens. */\n cacheRead: number;\n}\n\n/** Token counts for a turn/session. `cacheRead` is optional (older counters). */\nexport interface TokenUsage {\n input: number;\n output: number;\n cacheRead?: number;\n}\n\n/**\n * Normalize a models.dev model object's pricing into {@link CostRates}.\n * Missing model, missing `cost`, or missing individual fields all yield 0 —\n * free/unmetered plans report `$0` rather than crashing.\n */\nexport function getCostRates(model: unknown): CostRates {\n const cost = (\n model as { cost?: { input?: number; output?: number; cache_read?: number } } | null | undefined\n )?.cost;\n return {\n input: cost?.input ?? 0,\n output: cost?.output ?? 0,\n cacheRead: cost?.cache_read ?? 0,\n };\n}\n\n/**\n * Dollar cost of `usage` at the given per-1M-token `rates`. Returns 0 when all\n * rates are 0 (unpriced plan).\n */\nexport function computeUsageCost(usage: TokenUsage, rates: CostRates): number {\n return (\n (usage.input * rates.input +\n usage.output * rates.output +\n (usage.cacheRead ?? 0) * rates.cacheRead) /\n 1_000_000\n );\n}\n","/**\n * Shared config I/O helpers for the `providers` map inside the global config.\n *\n * Extracted from both `packages/webui/src/server/index.ts` and\n * `packages/cli/src/webui-server.ts` so the CLI's `--webui` mode doesn't\n * duplicate the read-merge-decrypt / encrypt-write cycle. Callers supply\n * their own vault (already booted) and config path — this module is pure I/O\n * with no side-channel state.\n */\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { type ProviderConfig, type SecretVault, atomicWrite } from '@wrongstack/core';\nimport { decryptConfigSecrets, encryptConfigSecrets } from '@wrongstack/core/security';\n\n/**\n * Read the `providers` section from the global config, decrypting\n * secret-bearing fields. Returns an empty record when the config file\n * doesn't exist or has no `providers` key.\n */\nexport async function loadSavedProviders(\n configPath: string,\n vault: SecretVault,\n): Promise<Record<string, ProviderConfig>> {\n let raw: string;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch {\n return {};\n }\n let parsed: { providers?: Record<string, ProviderConfig> } = {};\n try {\n parsed = JSON.parse(raw) as { providers?: Record<string, ProviderConfig> };\n } catch {\n return {};\n }\n if (!parsed.providers) return {};\n return decryptConfigSecrets(parsed.providers, vault);\n}\n\n/**\n * Write `providers` back into the global config, encrypting secrets first.\n * Refuses to overwrite a corrupt-but-existing config file (the operator\n * should fix it manually). When the config file is missing (ENOENT), starts\n * from an empty object.\n */\nexport async function saveProviders(\n configPath: string,\n vault: SecretVault,\n providers: Record<string, ProviderConfig>,\n): Promise<void> {\n let raw: string;\n let fileExists = true;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new Error(\n `Refusing to mutate ${configPath}: ${(err as Error).message}`,\n { cause: err },\n );\n }\n fileExists = false;\n raw = '{}';\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n if (fileExists) {\n throw new Error(\n `Refusing to overwrite corrupt config at ${configPath} ` +\n `(${(err as Error).message}). Fix or move the file aside before retrying.`,\n { cause: err },\n );\n }\n parsed = {};\n }\n parsed.providers = providers;\n const encrypted = encryptConfigSecrets(parsed, vault);\n await atomicWrite(configPath, JSON.stringify(encrypted, null, 2), { mode: 0o600 });\n}\n\n// ---------------------------------------------------------------------------\n// Standalone WebUI server helpers (boot phase — not WS-connected)\n// ---------------------------------------------------------------------------\n\nimport { DefaultSecretVault } from '@wrongstack/core';\n\n/**\n * Small helper for the standalone WebUI entry point: create a\n * `{ load, save }` pair from a config path alone (uses the\n * config-directory-relative `.key` file for the vault). The `--webui`\n * CLI mode and the standalone server both need to read/write the\n * `providers` map identically.\n */\nexport function createProviderConfigIO(configPath: string) {\n const keyFile = path.join(path.dirname(configPath), '.key');\n const vault = new DefaultSecretVault({ keyFile });\n\n return {\n load: () => loadSavedProviders(configPath, vault),\n save: (providers: Record<string, ProviderConfig>) =>\n saveProviders(configPath, vault, providers),\n };\n}\n","/**\n * Pure provider/API-key record transforms for the WebUI server's `key.*` and\n * `provider.*` WebSocket handlers.\n *\n * These operate on an in-memory `providers` record (the decrypted\n * `config.providers` map) and return a `{ ok, message }` result mirroring the\n * status string the handler sends back to the client. All persistence\n * (load/decrypt, encrypt/atomic-write) and WS messaging stays in `index.ts` —\n * keeping this layer pure means the security-sensitive key bookkeeping (which\n * key is active, when a provider is dropped, how legacy single-key configs are\n * normalized) is unit-testable without a vault or a socket.\n *\n * Extracted from `index.ts`; transforms mutate the passed record in place, the\n * same way the original handlers did before calling `saveProviders`.\n */\nimport type { ProviderApiKey, ProviderConfig } from '@wrongstack/core';\n\nexport type ProvidersRecord = Record<string, ProviderConfig>;\n\nexport interface KeyOpResult {\n ok: boolean;\n message: string;\n}\n\n/**\n * Normalize a provider's keys to the array form, upgrading a legacy single\n * `apiKey` string to a one-element `[{ label: 'default', ... }]` list. Returns\n * fresh copies so callers can mutate without aliasing the stored config.\n */\nexport function normalizeKeys(cfg: ProviderConfig): ProviderApiKey[] {\n if (Array.isArray(cfg.apiKeys) && cfg.apiKeys.length > 0) {\n return cfg.apiKeys.map((k) => ({ ...k }));\n }\n if (typeof cfg.apiKey === 'string' && cfg.apiKey.length > 0) {\n return [{ label: 'default', apiKey: cfg.apiKey, createdAt: '' }];\n }\n return [];\n}\n\n/**\n * Write a normalized key list back onto a provider config: drop all key fields\n * when empty, otherwise sync `apiKeys`, the legacy `apiKey` mirror (the active\n * key), and re-point `activeKey` if it no longer names a present key.\n */\nexport function writeKeysBack(cfg: ProviderConfig, keys: ProviderApiKey[]): void {\n if (keys.length === 0) {\n delete cfg.apiKeys;\n delete cfg.apiKey;\n delete cfg.activeKey;\n return;\n }\n cfg.apiKeys = keys;\n const active = keys.find((k) => k.label === cfg.activeKey) ?? keys[0]!;\n cfg.apiKey = active.apiKey;\n if (!cfg.activeKey || !keys.some((k) => k.label === cfg.activeKey)) {\n cfg.activeKey = active.label;\n }\n}\n\n/** Mask a secret for display: `••••` for short keys, `abcd…wxyz` otherwise. */\nexport function maskedKey(key: string | undefined): string {\n if (!key) return '—';\n if (key.length <= 8) return '•'.repeat(key.length);\n return `${key.slice(0, 4)}…${key.slice(-4)}`;\n}\n\n/** Add or replace a labeled key for a provider, creating the provider if new. */\nexport function upsertKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n apiKey: string,\n nowIso: string,\n): KeyOpResult {\n const existing: ProviderConfig = providers[providerId] ?? { type: providerId };\n const keys = normalizeKeys(existing);\n const idx = keys.findIndex((k) => k.label === label);\n if (idx >= 0) {\n keys[idx] = { ...keys[idx]!, apiKey, createdAt: nowIso };\n } else {\n keys.push({ label, apiKey, createdAt: nowIso });\n }\n writeKeysBack(existing, keys);\n if (!existing.activeKey) existing.activeKey = label;\n providers[providerId] = existing;\n return { ok: true, message: `Key \"${label}\" saved for ${providerId}` };\n}\n\n/** Remove a labeled key; drops the provider entirely when its last key goes. */\nexport function deleteKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n): KeyOpResult {\n const existing = providers[providerId];\n if (!existing) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n const keys = normalizeKeys(existing).filter((k) => k.label !== label);\n if (keys.length === 0) {\n delete providers[providerId];\n } else {\n writeKeysBack(existing, keys);\n if (existing.activeKey === label) existing.activeKey = keys[0]!.label;\n providers[providerId] = existing;\n }\n return { ok: true, message: `Key \"${label}\" deleted from ${providerId}` };\n}\n\n/** Point a provider's active key at the given label. */\nexport function setActiveKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n): KeyOpResult {\n const existing = providers[providerId];\n if (!existing) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n existing.activeKey = label;\n writeKeysBack(existing, normalizeKeys(existing));\n providers[providerId] = existing;\n return { ok: true, message: `Active key for ${providerId} set to \"${label}\"` };\n}\n\n/** Register a brand-new provider (optionally with an initial `default` key). */\nexport function addProvider(\n providers: ProvidersRecord,\n payload: { id: string; family: string; baseUrl?: string; apiKey?: string },\n nowIso: string,\n): KeyOpResult {\n if (providers[payload.id]) {\n return {\n ok: false,\n message: `Provider \"${payload.id}\" already exists. Use key.add to add a key.`,\n };\n }\n const newProv: ProviderConfig = {\n type: payload.id,\n family: payload.family as ProviderConfig['family'],\n baseUrl: payload.baseUrl,\n };\n if (payload.apiKey) {\n newProv.apiKeys = [{ label: 'default', apiKey: payload.apiKey, createdAt: nowIso }];\n newProv.activeKey = 'default';\n }\n providers[payload.id] = newProv;\n return { ok: true, message: `Provider \"${payload.id}\" added` };\n}\n\n/** Remove an entire provider and all its keys. */\nexport function removeProvider(providers: ProvidersRecord, providerId: string): KeyOpResult {\n if (!providers[providerId]) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n delete providers[providerId];\n return { ok: true, message: `Provider \"${providerId}\" removed` };\n}\n","/**\n * Shared WebSocket utilities for both the standalone WebUI server and the\n * CLI's `--webui` embedded server. Extracted from the duplicated `send` /\n * `broadcast` / `sendResult` / `generateAuthToken` patterns that were\n * copy-pasted between `packages/webui/src/server/index.ts` and\n * `packages/cli/src/webui-server.ts`.\n */\nimport { randomBytes } from 'node:crypto';\n// Value import (not `import type`): we reference `WebSocket.OPEN` below, which\n// is a runtime value, not just a type.\nimport { WebSocket } from 'ws';\nimport type { ConnectedClient, WSServerMessage } from './types.js';\n\n/**\n * Send a JSON message to a single WebSocket client.\n * No-op when the socket is not in OPEN state (disconnected / closing).\n */\nexport function send(ws: WebSocket, msg: WSServerMessage): void {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(msg));\n }\n}\n\n/**\n * Broadcast a JSON message to every connected client.\n * Swallows per-socket send errors — a client that disconnected between the\n * readyState check and `ws.send()` is cleaned up by its own `close` handler.\n */\nexport function broadcast(\n clients: Map<WebSocket, ConnectedClient>,\n msg: WSServerMessage,\n): void {\n const data = JSON.stringify(msg);\n for (const [ws] of clients) {\n if (ws.readyState === WebSocket.OPEN) {\n try {\n ws.send(data);\n } catch {\n // Client disconnected between the readyState check and the send —\n // let the 'close' handler remove it from the map naturally.\n }\n }\n }\n}\n\n/**\n * Send a success/failure result message (used by key.* and provider.* handlers).\n * The frontend expects `key.operation_result` with `{ success, message }`.\n */\nexport function sendResult(ws: WebSocket, success: boolean, message: string): void {\n send(ws, { type: 'key.operation_result', payload: { success, message } });\n}\n\n/**\n * Extract a human-readable message from an unknown thrown value.\n */\nexport function errMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Generate a cryptographically random WebSocket auth token (hex string).\n * Shared between standalone and CLI-embedded WebUI servers.\n */\nexport function generateAuthToken(): string {\n return randomBytes(16).toString('hex');\n}\n","import type { WebSocket } from 'ws';\nimport type { ProviderConfig } from '@wrongstack/core';\nimport { loadSavedProviders, saveProviders } from './provider-config-io.js';\nimport {\n upsertKey as upsertKeyRecord,\n deleteKey as deleteKeyRecord,\n setActiveKey as setActiveKeyRecord,\n addProvider as addProviderRecord,\n removeProvider as removeProviderRecord,\n} from './provider-keys.js';\nimport type { WSServerMessage } from './types.js';\nimport { sendResult, errMessage } from './ws-utils.js';\n\nexport interface ProviderHandlerDeps {\n globalConfigPath: string;\n vault: import('@wrongstack/core').SecretVault;\n /** Shared config write lock — serialized via chained promises */\n setConfigWriteLock: (lock: Promise<void>) => void;\n getConfigWriteLock: () => Promise<void>;\n}\n\nexport function createProviderHandlers(deps: ProviderHandlerDeps) {\n const { globalConfigPath, vault } = deps;\n let configWriteLock = deps.getConfigWriteLock();\n\n async function loadConfigProviders(): Promise<Record<string, ProviderConfig>> {\n return loadSavedProviders(globalConfigPath, vault);\n }\n\n async function saveConfigProviders(providers: Record<string, ProviderConfig>): Promise<void> {\n const next = configWriteLock.then(() => saveProviders(globalConfigPath, vault, providers));\n configWriteLock = next;\n deps.setConfigWriteLock(next);\n await next;\n }\n\n async function handleKeyUpsert(ws: WebSocket, providerId: string, label: string, apiKey: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = upsertKeyRecord(providers, providerId, label, apiKey, new Date().toISOString());\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleKeyDelete(ws: WebSocket, providerId: string, label: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = deleteKeyRecord(providers, providerId, label);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleKeySetActive(ws: WebSocket, providerId: string, label: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = setActiveKeyRecord(providers, providerId, label);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleProviderAdd(ws: WebSocket, payload: { id: string; family: string; baseUrl?: string; apiKey?: string }): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = addProviderRecord(providers, payload, new Date().toISOString());\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleProviderRemove(ws: WebSocket, providerId: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = removeProviderRecord(providers, providerId);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n return { handleKeyUpsert, handleKeyDelete, handleKeySetActive, handleProviderAdd, handleProviderRemove, loadConfigProviders };\n}\n","import type { EventBus, Context } from '@wrongstack/core';\nimport type { WebSocket } from 'ws';\nimport type { ConnectedClient, WSServerMessage } from './types.js';\n\nexport interface SetupEventsDeps {\n events: EventBus;\n broadcast: (clients: Map<WebSocket, ConnectedClient>, msg: WSServerMessage) => void;\n clients: Map<WebSocket, ConnectedClient>;\n config: { tools?: { maxIterations?: number } };\n context: Context;\n pendingConfirms: Map<string, (d: 'yes' | 'no' | 'always' | 'deny') => void>;\n}\n\nexport function setupEvents(deps: SetupEventsDeps): void {\n const { events, broadcast, clients, config, context, pendingConfirms } = deps;\n\n events.on('iteration.started', (e) => {\n broadcast(clients, {\n type: 'iteration.started',\n payload: { index: e.index, maxIterations: config.tools?.maxIterations ?? 100 },\n });\n });\n\n events.on('provider.text_delta', (e) => {\n broadcast(clients, { type: 'provider.text_delta', payload: { text: e.text, messageId: 'current' } });\n });\n\n events.on('provider.thinking_delta', (e) => {\n broadcast(clients, { type: 'provider.thinking_delta', payload: { text: e.text } });\n });\n\n events.on('tool.started', (e) => {\n broadcast(clients, {\n type: 'tool.started',\n payload: { id: e.id, name: e.name, input: e.input, messageId: `tool_${e.id}` },\n });\n });\n\n events.on('tool.progress', (e) => {\n broadcast(clients, {\n type: 'tool.progress',\n payload: { id: e.id, name: e.name, eventType: e.event.type, text: e.event.text },\n });\n });\n\n events.on('tool.executed', (e) => {\n broadcast(clients, {\n type: 'tool.executed',\n payload: { id: e.id, name: e.name, durationMs: e.durationMs, ok: e.ok, input: e.input, output: e.output },\n });\n broadcast(clients, { type: 'todos.updated', payload: { todos: [...context.todos] } });\n });\n\n events.on('provider.response', (e) => {\n broadcast(clients, { type: 'provider.response', payload: { usage: e.usage, stopReason: e.stopReason, messageId: 'current' } });\n });\n\n events.on('context.repaired', (e) => {\n broadcast(clients, { type: 'context.repaired', payload: { removedToolUses: e.removedToolUses, removedToolResults: e.removedToolResults, removedMessages: e.removedMessages } });\n });\n\n events.on('tool.confirm_needed', (e) => {\n const id = e.toolUseId ?? `confirm_${Date.now()}`;\n pendingConfirms.set(id, e.resolve);\n broadcast(clients, { type: 'tool.confirm_needed', payload: { id, toolName: e.tool?.name ?? 'unknown', input: e.input, suggestedPattern: e.suggestedPattern } });\n });\n\n events.on('error', (e) => {\n broadcast(clients, { type: 'error', payload: { phase: e.phase, message: e.err instanceof Error ? e.err.message : String(e.err) } });\n });\n\n // Subagent fleet lifecycle\n const forwardSubagent = (kind: string, payload: Record<string, unknown>) =>\n broadcast(clients, { type: 'subagent.event', payload: { kind, ...payload } });\n\n events.on('subagent.spawned', (e) => forwardSubagent('spawned', { subagentId: e.subagentId, taskId: e.taskId, name: e.name, provider: e.provider, model: e.model, description: e.description }));\n events.on('subagent.task_started', (e) => forwardSubagent('task_started', { subagentId: e.subagentId, taskId: e.taskId, description: e.description }));\n events.on('subagent.tool_executed', (e) => forwardSubagent('tool_executed', { subagentId: e.subagentId, toolName: e.name, durationMs: e.durationMs, ok: e.ok }));\n events.on('subagent.iteration_summary', (e) => forwardSubagent('iteration_summary', { subagentId: e.subagentId, iteration: e.iteration, toolCalls: e.toolCalls, costUsd: e.costUsd, currentTool: e.currentTool }));\n events.on('subagent.budget_extended', (e) => forwardSubagent('budget_extended', { subagentId: e.subagentId, totalExtensions: e.totalExtensions }));\n events.on('subagent.ctx_pct', (e) => forwardSubagent('ctx_pct', { subagentId: e.subagentId, load: e.load, tokens: e.tokens, maxContext: e.maxContext }));\n events.on('subagent.task_completed', (e) => forwardSubagent('task_completed', { subagentId: e.subagentId, status: e.status, iterations: e.iterations, toolCalls: e.toolCalls, error: e.error ? { kind: e.error.kind, message: e.error.message } : undefined }));\n}\n","/**\n * Per-section context-window token estimate for the `context.debug` command.\n *\n * Uses the simple 4-chars-per-token heuristic — not exact, but close enough to\n * spot which section (system prompt, tool schemas, or message history) is\n * eating the context window. Tool schemas in particular are easy to overlook:\n * each tool ships its full JSON schema to the model every turn, so 20+ builtins\n * can cost 10-20k tokens on their own.\n *\n * Extracted from `index.ts` as a pure function so the breakdown maths can be\n * unit tested without standing up a Context/ToolRegistry.\n */\n\n/** 4-chars-per-token heuristic estimate for a string. */\nexport function estimateTokens(s: string): number {\n return Math.ceil(s.length / 4);\n}\n\n/** Stringify arbitrary content for length estimation (JSON, with fallbacks). */\nexport function stringifyContent(c: unknown): string {\n if (typeof c === 'string') return c;\n try {\n return JSON.stringify(c);\n } catch {\n return String(c);\n }\n}\n\ninterface PromptBlock {\n text?: string;\n}\ninterface ToolLike {\n name: string;\n inputSchema?: unknown;\n description?: string;\n}\ninterface ContentBlock {\n type?: string;\n text?: string;\n input?: unknown;\n content?: unknown;\n name?: string;\n}\ninterface MessageLike {\n role: string;\n content: unknown;\n}\n\nexport interface ToolTokenEntry {\n name: string;\n tokens: number;\n}\nexport interface MessageTokenEntry {\n index: number;\n role: string;\n tokens: number;\n preview: string;\n}\n\nexport interface ContextBreakdown {\n total: number;\n systemPrompt: number;\n tools: { total: number; count: number; breakdown: ToolTokenEntry[] };\n messages: { total: number; count: number; breakdown: MessageTokenEntry[] };\n}\n\nfunction messageTokens(content: unknown): number {\n if (typeof content === 'string') return estimateTokens(content);\n if (!Array.isArray(content)) return 0;\n let tk = 0;\n for (const b of content as ContentBlock[]) {\n if (b.type === 'text') tk += estimateTokens(b.text ?? '');\n else if (b.type === 'tool_use') tk += estimateTokens(stringifyContent(b.input));\n else if (b.type === 'tool_result') tk += estimateTokens(stringifyContent(b.content));\n else tk += estimateTokens(stringifyContent(b));\n }\n return tk;\n}\n\nfunction messagePreview(content: unknown): string {\n if (typeof content === 'string') return content.slice(0, 60);\n if (!Array.isArray(content)) return '';\n return (content as ContentBlock[])\n .map((b) =>\n b.type === 'text'\n ? (b.text ?? '').slice(0, 40)\n : b.type === 'tool_use'\n ? `[tool_use: ${b.name}]`\n : b.type === 'tool_result'\n ? '[tool_result]'\n : `[${b.type}]`,\n )\n .join(' ')\n .slice(0, 60);\n}\n\n/**\n * Compute the per-section token breakdown for the active context. Mirrors the\n * shape the `context.debug` WS reply expects (minus the `mode`/`policy` fields,\n * which the caller layers on from `context.meta`).\n */\nexport function estimateContextBreakdown(input: {\n systemPrompt: ReadonlyArray<PromptBlock>;\n tools: ReadonlyArray<ToolLike>;\n messages: ReadonlyArray<MessageLike>;\n}): ContextBreakdown {\n const sysTokens = input.systemPrompt.reduce((acc, b) => acc + estimateTokens(b.text ?? ''), 0);\n\n const toolBreakdown: ToolTokenEntry[] = input.tools.map((t) => {\n const schema = t.inputSchema ?? {};\n const desc = t.description ?? '';\n return {\n name: t.name,\n tokens:\n estimateTokens(t.name) + estimateTokens(desc) + estimateTokens(stringifyContent(schema)),\n };\n });\n const toolTokens = toolBreakdown.reduce((a, b) => a + b.tokens, 0);\n\n const messageBreakdown: MessageTokenEntry[] = input.messages.map((m, i) => ({\n index: i,\n role: m.role,\n tokens: messageTokens(m.content),\n preview: messagePreview(m.content),\n }));\n const msgTokens = messageBreakdown.reduce((a, b) => a + b.tokens, 0);\n\n return {\n total: sysTokens + toolTokens + msgTokens,\n systemPrompt: sysTokens,\n tools: { total: toolTokens, count: input.tools.length, breakdown: toolBreakdown },\n messages: { total: msgTokens, count: input.messages.length, breakdown: messageBreakdown },\n };\n}\n","// Server entry point for standalone WebUI.\n// Bind defaults: 127.0.0.1:3457 (loopback only). Override with WS_HOST / WS_PORT.\n// HTTP frontend defaults to 3456 (override with PORT). Run several instances on\n// different PORT/WS_PORT pairs — `webui --list` shows which are open for which\n// project (registry: ~/.wrongstack/webui-instances.json).\nimport { startWebUI } from './index.js';\nimport { formatInstances, listInstances } from './instance-registry.js';\n\nconst argv = process.argv.slice(2);\n\n// `webui --list` / `webui ls` — print running instances and exit. Cheap,\n// side-effect-free (it only prunes dead pids), so it never boots a server.\nif (argv.includes('--list') || argv.includes('-l') || argv[0] === 'ls') {\n listInstances()\n .then((instances) => {\n console.log(formatInstances(instances));\n process.exit(0);\n })\n .catch((err) => {\n console.error('[WebUI] Could not read instance registry:', err);\n process.exit(1);\n });\n} else {\n const wsPort = Number.parseInt(process.env['WS_PORT'] ?? '3457', 10);\n const wsHost = process.env['WS_HOST'] ?? '127.0.0.1';\n const open =\n argv.includes('--open') || argv.includes('-o') || process.env['WEBUI_OPEN'] === '1';\n\n console.log(`[WebUI] Starting standalone server on ${wsHost}:${wsPort}...`);\n\n startWebUI({ wsPort, wsHost, open }).catch((err) => {\n console.error('[WebUI] Fatal error:', err);\n process.exit(1);\n });\n}\n"],"mappings":";AAAA,YAAYA,SAAQ;AAEpB,YAAYC,WAAU;;;ACmBtB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,UAAU;AAgBtB,IAAM,aAAqC;AAAA,EACzC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AACV;AAcO,SAAS,aAAa,MAAc,QAAwB;AACjE,QAAM,MAAM,4CAA4C,MAAM;AAE9D,MAAI,KAAK,SAAS,2BAA2B,EAAG,QAAO;AACvD,MAAI,KAAK,SAAS,SAAS,GAAG;AAC5B,WAAO,KAAK,QAAQ,WAAW,KAAK,GAAG;AAAA,UAAa;A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AM,OACJ,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,KAAK,QAAQ,IAAI,YAAY,MAAM;AAElF,UAAQ,IAAI,yCAAyC,MAAM,IAAI,MAAM,KAAK;AAE1E,aAAW,EAAE,QAAQ,QAAQ,KAAK,CAAC,EAAE,MAAM,CAAC,QAAQ;AAClD,YAAQ,MAAM,wBAAwB,GAAG;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["fs","path","DefaultMemoryStore","DefaultModeStore","DefaultSessionStore","DefaultSkillLoader","DefaultSystemPromptBuilder","DefaultTokenCounter","HybridCompactor","TOKENS","atomicWrite","s","path","fs","resolve","fs","path","atomicWrite","broadcast","TOKENS","DefaultMemoryStore","DefaultSessionStore","DefaultTokenCounter","DefaultModeStore","DefaultSkillLoader","DefaultSystemPromptBuilder","HybridCompactor","verifyClient","resolve","provider","atomicWrite","modePrompt"]}
1
+ {"version":3,"sources":["../../src/server/index.ts","../../src/server/http-server.ts","../../src/server/file-picker.ts","../../../runtime/src/container.ts","../../src/server/boot.ts","../../src/server/autophase-ws-handler.ts","../../src/server/collaboration-ws-handler.ts","../../src/server/worktree-ws-handler.ts","../../src/server/ws-auth.ts","../../src/server/lifecycle.ts","../../src/server/instance-registry.ts","../../src/server/port-utils.ts","../../src/server/open-browser.ts","../../src/server/usage-cost.ts","../../src/server/provider-config-io.ts","../../src/server/provider-keys.ts","../../src/server/ws-utils.ts","../../src/server/provider-handlers.ts","../../src/server/setup-events.ts","../../src/server/token-estimator.ts","../../src/server/entry.ts"],"sourcesContent":["import * as fs from 'node:fs/promises';\r\nimport * as http from 'node:http';\r\nimport * as path from 'node:path';\r\nimport { createHttpServer } from './http-server.js';\r\nimport { SKIP_DIRS, isHiddenEntry, rankFiles } from './file-picker.js';\r\nimport {\r\n Agent,\r\n AutoCompactionMiddleware,\r\n Context,\r\n DefaultMemoryStore,\r\n DefaultModeStore,\r\n DefaultModelsRegistry,\r\n DefaultSessionReader,\r\n DefaultSessionStore,\r\n DefaultSkillLoader,\r\n DefaultSystemPromptBuilder,\r\n DefaultTokenCounter,\r\n AnnotationsStore,\r\n CollaborationBus,\r\n collabPauseMiddleware,\r\n collabInjectMiddleware,\r\n estimateRequestTokensCalibrated,\r\n EventBus,\r\n HybridCompactor,\r\n type ProviderConfig,\r\n type Provider,\r\n ProviderRegistry,\r\n TOKENS,\r\n ToolRegistry,\r\n atomicWrite,\r\n createDefaultPipelines,\r\n DEFAULT_CONTEXT_WINDOW_MODE_ID,\r\n DEFAULT_TOOLS_CONFIG,\r\n listContextWindowModes,\r\n repairToolUseAdjacency,\r\n resolveContextWindowPolicy,\r\n} from '@wrongstack/core';\r\nimport { ToolExecutor } from '@wrongstack/core/execution';\r\nimport { decryptConfigSecrets, encryptConfigSecrets } from '@wrongstack/core/security';\r\nimport { buildProviderFactoriesFromRegistry, makeProviderFromConfig } from '@wrongstack/providers';\r\nimport { builtinToolsPack, forgetTool, rememberTool } from '@wrongstack/tools';\r\nimport { type WebSocket, WebSocketServer } from 'ws';\r\nimport { createDefaultContainer } from '../../../runtime/src/container.js';\r\nimport { bootConfig, patchConfig, } from './boot.js';\r\nimport { AutoPhaseWebSocketHandler } from './autophase-ws-handler.js';\r\nimport { CollaborationWebSocketHandler } from './collaboration-ws-handler.js';\r\nimport { WorktreeWebSocketHandler } from './worktree-ws-handler.js';\r\nimport { verifyClient as verifyWsClient } from './ws-auth.js';\r\nimport { registerShutdownHandlers } from './lifecycle.js';\r\nimport { registerInstance, unregisterInstance } from './instance-registry.js';\r\nimport { findFreePort } from './port-utils.js';\r\nimport { openBrowser } from './open-browser.js';\r\nimport { computeUsageCost, getCostRates } from './usage-cost.js';\r\nimport { createProviderHandlers } from './provider-handlers.js';\r\nimport { setupEvents } from './setup-events.js';\r\nimport { maskedKey, normalizeKeys } from './provider-keys.js';\r\nimport { send, broadcast, sendResult, errMessage, generateAuthToken } from './ws-utils.js';\r\nimport { estimateContextBreakdown } from './token-estimator.js';\r\n\r\n\n\nfunction expectDefined<T>(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected value to be defined');\n }\n return value;\n}\n\n// Re-export types — shared message shapes and options used by both the\r\n// standalone server and the CLI's `--webui` embedded mode.\r\nexport type { WebUIOptions, BackendServices } from './types.js';\r\nexport type { WSServerMessage, WSClientMessage, ConnectedClient } from './types.js';\r\n\r\n// Re-export the static-serve + multi-instance building blocks so other packages\r\n// (the CLI's `--webui` mode) can serve the same React frontend, inject the live\r\n// WS port, pick free ports, and register in the shared instance registry —\r\n// without duplicating any of that logic.\r\nexport { createHttpServer, buildCspHeader, injectWsPort } from './http-server.js';\r\nexport { findFreePort, isPortFree } from './port-utils.js';\r\nexport { openBrowser, browserOpenCommand } from './open-browser.js';\r\nexport {\r\n registerInstance,\r\n unregisterInstance,\r\n listInstances,\r\n formatInstances,\r\n registryPath,\r\n defaultBaseDir,\r\n type WebUIInstanceRecord,\r\n} from './instance-registry.js';\r\n\r\n// WebSocket utilities shared with CLI\r\nexport {\r\n send,\r\n broadcast,\r\n sendResult,\r\n errMessage,\r\n generateAuthToken,\r\n} from './ws-utils.js';\r\n\r\n// WS auth — pure functions for verifying WebSocket connections\r\nexport {\r\n verifyClient,\r\n isLoopbackHostname,\r\n isLoopbackBind,\r\n tokenMatches,\r\n extractToken,\r\n hostHeaderOk,\r\n type VerifyClientInput,\r\n} from './ws-auth.js';\r\n\r\n// Provider/API-key record transforms (pure functions, testable without I/O)\r\nexport {\r\n normalizeKeys,\r\n writeKeysBack,\r\n maskedKey,\r\n upsertKey,\r\n deleteKey,\r\n setActiveKey,\r\n addProvider,\r\n removeProvider,\r\n type KeyOpResult,\r\n type ProvidersRecord,\r\n} from './provider-keys.js';\r\n\r\n// Provider config load/save (decrypt from / encrypt to global config)\r\nexport {\r\n loadSavedProviders,\r\n saveProviders,\r\n createProviderConfigIO,\r\n} from './provider-config-io.js';\r\n\r\n// Message + client shapes now live in ./types.ts (shared with the CLI's\r\n// embedded server). Imported here for internal use; re-exported above for\r\n// external consumers. The previous local copies shadowed these and made the\r\n// `Map<WebSocket, ConnectedClient>` passed to the extracted ws-utils helpers\r\n// nominally distinct, which TS rejected.\r\nimport type { ConnectedClient, WSClientMessage, WSServerMessage } from './types.js';\r\n\r\nexport async function startWebUI(\r\n opts: { wsPort?: number | undefined; wsHost?: string | undefined; open?: boolean | undefined } = {},\r\n): Promise<void> {\r\n const requestedWsPort = opts.wsPort ?? 3457;\r\n // Bind to loopback IP by default (not the string \"localhost\", which on some\r\n // hosts resolves to IPv6 ::1 and surprises older WS clients). Set WS_HOST or\r\n // pass opts.wsHost to override (e.g. \"0.0.0.0\" for LAN access).\r\n const wsHost = opts.wsHost ?? '127.0.0.1';\r\n const requestedHttpPort = Number.parseInt(process.env['PORT'] ?? '3456', 10);\r\n\r\n // Port resolution. Unless WEBUI_STRICT_PORT is set, auto-advance past any port\r\n // already taken by another instance so running `webui` several times \"just\r\n // works\" — the real ports are then stamped into the served HTML and the\r\n // instance registry. Strict mode keeps the requested ports and lets bind fail\r\n // loudly (useful behind a reverse proxy that expects fixed ports).\r\n const strictPort =\r\n process.env['WEBUI_STRICT_PORT'] === '1' || process.env['WEBUI_STRICT_PORT'] === 'true';\r\n let wsPort = requestedWsPort;\r\n let httpPort = requestedHttpPort;\r\n if (!strictPort) {\r\n // Resolve HTTP first, then WS excluding it, so successive instances land on\r\n // tidy adjacent pairs (3456/3457, 3458/3459, …) instead of interleaving.\r\n httpPort = await findFreePort(wsHost, requestedHttpPort);\r\n wsPort = await findFreePort(wsHost, requestedWsPort, { exclude: new Set([httpPort]) });\r\n if (httpPort !== requestedHttpPort) {\r\n console.warn(`[WebUI] HTTP port ${requestedHttpPort} in use → using ${httpPort}`);\r\n }\r\n if (wsPort !== requestedWsPort) {\r\n console.warn(`[WebUI] WS port ${requestedWsPort} in use → using ${wsPort}`);\r\n }\r\n }\r\n\r\n console.log('[WebUI] Starting backend services...');\r\n\r\n // Boot configuration\r\n const boot = await bootConfig();\r\n const { config: baseConfig, vault, globalConfigPath, projectRoot, wpaths, logger } = boot;\r\n let config = baseConfig;\r\n\r\n // Serialize concurrent config writes to prevent races between model.switch\r\n // and key.add/key.update handlers that both read-modify-write globalConfigPath.\r\n let configWriteLock: Promise<void> = Promise.resolve();\r\n\r\n console.log('[WebUI] Config loaded:', config.provider ?? '(none)', '/', config.model ?? '(none)');\r\n\r\n // If no active provider is set but there are saved providers, pick the first one.\r\n // This handles configs written in older formats or by external tools.\r\n // Guard against config.providers being a string or other non-object value\r\n // (e.g., from a corrupted config or YAML parser misreading the value).\r\n if (\r\n !config.provider &&\r\n config.providers &&\r\n typeof config.providers === 'object' &&\r\n config.providers !== null &&\r\n !Array.isArray(config.providers) &&\r\n Object.keys(config.providers).length > 0\r\n ) {\r\n const firstKey = expectDefined(Object.keys(config.providers)[0]);\r\n config = patchConfig(config, { provider: firstKey });\r\n console.log('[WebUI] No active provider — auto-selected:', firstKey);\r\n }\r\n\r\n // If still no provider, the frontend will show a no-provider welcome screen.\r\n // We still start the HTTP/WS servers so the user can configure via the UI.\r\n const needsProvider = !config.provider || !config.model;\r\n\r\n // ModelsRegistry\r\n const modelsRegistry = new DefaultModelsRegistry({\r\n cacheFile: wpaths.modelsCache,\r\n ttlSeconds: 24 * 3600,\r\n });\r\n\r\n // Container via shared factory\r\n const container = createDefaultContainer({ config, wpaths, logger, modelsRegistry });\r\n const configStore = container.resolve(TOKENS.ConfigStore);\r\n\r\n // Provider registry\r\n const providerRegistry = new ProviderRegistry();\r\n try {\r\n const factories = await buildProviderFactoriesFromRegistry({\r\n registry: modelsRegistry,\r\n log: logger,\r\n });\r\n for (const f of factories) providerRegistry.register(f);\r\n console.log('[WebUI] Provider registry loaded:', providerRegistry.list().length, 'providers');\r\n } catch (err) {\r\n console.warn('[WebUI] Failed to load provider registry:', err);\r\n }\r\n\r\n // Tool registry\r\n const toolRegistry = new ToolRegistry();\r\n toolRegistry.registerAllOrThrow([...(builtinToolsPack.tools ?? [])], builtinToolsPack.name);\r\n\r\n // Memory tools\r\n const memoryStore = new DefaultMemoryStore({ paths: wpaths });\r\n if (config.features.memory) {\r\n toolRegistry.register(rememberTool(memoryStore));\r\n toolRegistry.register(forgetTool(memoryStore));\r\n }\r\n console.log('[WebUI] Tool registry loaded:', toolRegistry.list().length, 'tools');\r\n\r\n // Event bus\r\n const events = new EventBus();\r\n events.setLogger(logger);\r\n\r\n // Session store\r\n const sessionStore = new DefaultSessionStore({ dir: wpaths.projectSessions });\r\n // Prune old sessions on server start (non-blocking).\r\n sessionStore.prune(30).then((count) => {\r\n if (count > 0) logger.info(`Pruned ${count} old session${count === 1 ? '' : 's'}.`);\r\n }).catch(() => undefined);\r\n // Session reader — same on-disk store, read-only access. Used by the\r\n // collaboration handler to replay the last N events to late-joining\r\n // observers (Phase 1.5 of idea #13).\r\n const sessionReader = new DefaultSessionReader({ store: sessionStore });\r\n // Annotations store — sidecar files for collaboration notes (Phase 2\r\n // of idea #13). Living under `projectSessions` so all per-session\r\n // data is colocated and travels with the project.\r\n const annotationsStore = new AnnotationsStore({ dir: wpaths.projectSessions });\r\n let session = await sessionStore.create({\r\n id: '',\r\n title: '',\r\n model: config.model,\r\n provider: config.provider,\r\n });\r\n // Wall-clock when the *current* session started. Updated on /new and on\r\n // /resume so /stats can report accurate elapsed time per the active\r\n // session, not the daemon process uptime.\r\n let sessionStartedAt = Date.now();\r\n console.log('[WebUI] Session created:', session.id);\r\n\r\n // Token counter\r\n const tokenCounter = new DefaultTokenCounter({\r\n registry: modelsRegistry,\r\n providerId: config.provider,\r\n });\r\n\r\n // Mode store\r\n const modeStore = new DefaultModeStore({ directory: wpaths.configDir });\r\n const activeMode = await modeStore.getActiveMode();\r\n let modeId = activeMode?.id ?? 'default';\r\n const modePrompt = activeMode?.prompt ?? '';\r\n\r\n // System prompt builder\r\n const resolvedModel = await modelsRegistry.getModel(config.provider, config.model);\r\n const modelCapabilities = resolvedModel?.capabilities\r\n ? {\r\n maxContextTokens: resolvedModel.capabilities.maxContext,\r\n supportsTools: resolvedModel.capabilities.tools,\r\n supportsVision: resolvedModel.capabilities.vision,\r\n supportsReasoning: resolvedModel.capabilities.reasoning,\r\n }\r\n : undefined;\r\n\r\n const skillLoader = config.features.skills\r\n ? new DefaultSkillLoader({ paths: wpaths })\r\n : undefined;\r\n const systemPromptBuilder = new DefaultSystemPromptBuilder({\r\n memoryStore,\r\n skillLoader,\r\n modeStore,\r\n modeId,\r\n modePrompt,\r\n modelCapabilities,\r\n });\r\n\r\n const systemPrompt = await systemPromptBuilder.build({\r\n cwd: projectRoot,\r\n projectRoot,\r\n tools: toolRegistry.list(),\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n\r\n // Build provider (only if provider is configured)\r\n let provider: ReturnType<ProviderRegistry['create']>;\r\n if (!needsProvider) {\r\n const providerConfig = config.providers?.[config.provider] ?? {\r\n type: config.provider,\r\n apiKey: config.apiKey,\r\n baseUrl: config.baseUrl,\r\n };\r\n try {\r\n const cfgWithType = { ...providerConfig, type: config.provider };\r\n if (config.features.modelsRegistry && providerRegistry.has(config.provider)) {\r\n provider = providerRegistry.create(cfgWithType);\r\n } else {\r\n provider = makeProviderFromConfig(config.provider, cfgWithType);\r\n }\r\n } catch (err) {\r\n console.error('[WebUI] Failed to create provider:', err);\r\n throw err;\r\n }\r\n } else {\r\n // No provider is actively selected, but saved providers exist.\r\n // Re-read the config to find one with a usable encrypted API key\r\n // and create a real provider from it (the vault is already initialized).\r\n const savedProviders = config.providers ?? {};\r\n const firstKey = Object.keys(savedProviders)[0];\r\n if (firstKey) {\r\n const firstProvider = expectDefined(savedProviders[firstKey]);\r\n try {\r\n provider = makeProviderFromConfig(firstKey, {\r\n ...firstProvider,\r\n type: firstKey,\r\n family: firstProvider.family,\r\n apiKey: firstProvider.apiKey,\r\n });\r\n console.log('[WebUI] Using saved provider:', firstKey);\r\n } catch (err) {\r\n console.error('[WebUI] Could not create provider stub:', err);\r\n throw err;\r\n }\r\n } else {\r\n throw new Error(\r\n 'No provider configured. Run `wrongstack init` first, or configure via the WebUI.',\r\n );\r\n }\r\n }\r\n\r\n // Context\r\n const context = new Context({\r\n systemPrompt,\r\n provider,\r\n session,\r\n signal: new AbortController().signal,\r\n tokenCounter,\r\n cwd: projectRoot,\r\n projectRoot,\r\n model: config.model,\r\n });\r\n const initialContextPolicy = resolveContextWindowPolicy(config.context);\r\n context.meta['contextWindowMode'] = initialContextPolicy.id;\r\n context.meta['contextWindowPolicy'] = initialContextPolicy;\r\n\r\n // Pipelines\r\n const pipelines = createDefaultPipelines();\r\n // Collaboration bus — process-singleton pause/resume signal. The\r\n // middleware below hooks it into the toolCall pipeline so a\r\n // `controller` participant can halt the agent before the next tool\r\n // call (Phase 3 of idea #13). The same bus instance is shared with\r\n // the CollaborationWebSocketHandler so client pause/resume requests\r\n // are routed to the kernel.\r\n const collabBus = new CollaborationBus();\r\n // prepend (not use) — the pause check must run first, before any\r\n // permission/retry middleware that would otherwise proceed.\r\n const collabPause = collabPauseMiddleware(collabBus, { logger });\r\n Object.defineProperty(collabPause, 'name', { value: 'collab-pause' });\r\n pipelines.toolCall.prepend(collabPause as never);\r\n // Phase 4 — collab-inject. Installed AFTER collab-pause so the\r\n // controller can pause + inject before the next tool runs. The\r\n // middleware checks the bus's injection queue and splices a\r\n // synthetic tool_result when a controller has queued one for\r\n // the current toolUse.id.\r\n const collabInject = collabInjectMiddleware(collabBus, { logger });\r\n Object.defineProperty(collabInject, 'name', { value: 'collab-inject' });\r\n pipelines.toolCall.prepend(collabInject as never);\r\n // Compactor\r\n const compactor = new HybridCompactor({\r\n preserveK: config.context?.preserveK ?? 20,\r\n eliseThreshold: config.context?.eliseThreshold ?? 0.7,\r\n });\r\n\r\n // Auto-compaction\r\n let autoCompactor: AutoCompactionMiddleware | undefined;\r\n if (config.context?.autoCompact !== false) {\r\n // Priority: explicit override → models.dev per-model window → family default.\r\n // The catalog lookup matters for openai-compatible providers (OpenRouter,\r\n // Groq, …) whose family default is 0; without it auto-compaction would be\r\n // disabled even though the model has a real published window. Mirrors\r\n // updateAutoCompactionMaxContext below.\r\n let effectiveMaxContext = config.context?.effectiveMaxContext ?? 0;\r\n if (!effectiveMaxContext) {\r\n try {\r\n const m = await modelsRegistry.getModel(provider.id, context.model);\r\n effectiveMaxContext = m?.capabilities?.maxContext ?? 0;\r\n } catch {\r\n // best-effort: fall through to provider capability\r\n }\r\n }\r\n if (!effectiveMaxContext) effectiveMaxContext = provider.capabilities.maxContext;\r\n autoCompactor = new AutoCompactionMiddleware(\r\n compactor,\r\n effectiveMaxContext,\r\n (ctx) => estimateRequestTokensCalibrated(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total,\r\n {\r\n warn: initialContextPolicy.thresholds.warn,\r\n soft: initialContextPolicy.thresholds.soft,\r\n hard: initialContextPolicy.thresholds.hard,\r\n },\r\n {\r\n events,\r\n aggressiveOn: initialContextPolicy.aggressiveOn,\r\n policyProvider: (ctx) => {\r\n const policy = ctx.meta['contextWindowPolicy'];\r\n return policy && typeof policy === 'object'\r\n ? (policy as ReturnType<typeof resolveContextWindowPolicy>)\r\n : initialContextPolicy;\r\n },\r\n },\r\n );\r\n pipelines.contextWindow.use({ name: 'AutoCompaction', handler: autoCompactor.handler() });\r\n }\r\n\r\n /** Refresh AutoCompactionMiddleware denominator when the active model changes. */\r\n async function updateAutoCompactionMaxContext(newProvider: Provider): Promise<void> {\r\n if (!autoCompactor) return;\r\n let newMaxContext = config.context?.effectiveMaxContext ?? newProvider.capabilities.maxContext;\r\n try {\r\n const m = await modelsRegistry.getModel(newProvider.id, context.model);\r\n newMaxContext = m?.capabilities?.maxContext ?? newMaxContext;\r\n } catch {\r\n // best-effort: use provider capability\r\n }\r\n autoCompactor.setMaxContext(newMaxContext);\r\n }\r\n\r\n // Agent\r\n const secretScrubber = container.resolve(TOKENS.SecretScrubber);\r\n const renderer = container.has(TOKENS.Renderer)\r\n ? container.resolve(TOKENS.Renderer)\r\n : undefined;\r\n const toolExecutor = new ToolExecutor(toolRegistry, {\r\n permissionPolicy: container.resolve(TOKENS.PermissionPolicy),\r\n secretScrubber,\r\n renderer,\r\n events,\r\n confirmAwaiter: undefined,\r\n iterationTimeoutMs: config.tools?.iterationTimeoutMs ?? DEFAULT_TOOLS_CONFIG.iterationTimeoutMs,\r\n perIterationOutputCapBytes: config.tools?.perIterationOutputCapBytes ?? DEFAULT_TOOLS_CONFIG.perIterationOutputCapBytes,\r\n tracer: undefined,\r\n });\r\n\r\n const agent = new Agent({\r\n container,\r\n tools: toolRegistry,\r\n providers: providerRegistry,\r\n events,\r\n pipelines,\r\n context,\r\n maxIterations: config.tools?.maxIterations ?? DEFAULT_TOOLS_CONFIG.maxIterations,\r\n iterationTimeoutMs: config.tools?.iterationTimeoutMs ?? DEFAULT_TOOLS_CONFIG.iterationTimeoutMs,\r\n executionStrategy: config.tools?.defaultExecutionStrategy ?? DEFAULT_TOOLS_CONFIG.defaultExecutionStrategy,\r\n perIterationOutputCapBytes: config.tools?.perIterationOutputCapBytes ?? DEFAULT_TOOLS_CONFIG.perIterationOutputCapBytes,\r\n confirmAwaiter: undefined,\r\n toolExecutor,\r\n });\r\n console.log('[WebUI] Agent initialized');\r\n\r\n // AutoPhase handler — manages AutoPhaseRunner lifecycle via WS messages.\r\n // Stored under the per-project autophase dir (not the shared SDD task-graphs).\r\n const autoPhaseHandler = new AutoPhaseWebSocketHandler(\r\n agent,\r\n context,\r\n logger,\r\n wpaths.projectAutophase,\r\n events,\r\n projectRoot,\r\n );\r\n\r\n // Worktree handler — subscribes to the shared EventBus `worktree.*` events\r\n // and streams live swim-lane / DAG state to connected clients.\r\n const worktreeHandler = new WorktreeWebSocketHandler(events, logger);\r\n\r\n // Collaboration handler — Phase 1 of idea #13. Lets a second client\r\n // (e.g. a senior dev) join an active agent run as a read-only\r\n // observer and watch a live mirror of kernel events. Annotated and\r\n // controller roles land in Phase 2/3. The session reader enables\r\n // replay-on-join for late observers.\r\n const collabHandler = new CollaborationWebSocketHandler(\r\n events,\r\n logger,\r\n sessionReader,\r\n annotationsStore,\r\n collabBus,\r\n );\r\n\r\n // Helper: build the rich session.start payload from current runtime state.\r\n // Centralised so initial connect, post-/new, and post-model.switch all\r\n // broadcast the same shape — frontend treats this as the single source of\r\n // truth for everything in the status bar (model, context window, project).\r\n async function sessionStartPayload(): Promise<{\r\n sessionId: string;\r\n model: string;\r\n provider: string;\r\n maxContext: number;\r\n /** USD per 1M input tokens (0 if unknown / free). */\r\n inputCost: number;\r\n /** USD per 1M output tokens. */\r\n outputCost: number;\r\n /** USD per 1M cache-read tokens. */\r\n cacheReadCost: number;\r\n projectName: string;\r\n cwd: string;\r\n mode: string;\r\n contextMode: string;\r\n wsToken: string;\r\n }> {\r\n let maxContext = 0;\r\n let inputCost = 0;\r\n let outputCost = 0;\r\n let cacheReadCost = 0;\r\n try {\r\n const m = await modelsRegistry.getModel(config.provider, config.model);\r\n maxContext = m?.capabilities?.maxContext ?? 0;\r\n // models.dev pricing is dollars per 1M tokens; some providers omit the\r\n // field for free/unmetered plans (e.g. minimax-coding-plan) — in that\r\n // case we report 0 and the cost chip just stays at $0.\r\n const rates = getCostRates(m);\r\n inputCost = rates.input;\r\n outputCost = rates.output;\r\n cacheReadCost = rates.cacheRead;\r\n } catch {\r\n // best-effort\r\n }\r\n return {\r\n sessionId: session.id,\r\n model: config.model,\r\n provider: config.provider,\r\n maxContext,\r\n inputCost,\r\n outputCost,\r\n cacheReadCost,\r\n projectName: path.basename(projectRoot) || projectRoot,\r\n cwd: projectRoot,\r\n mode: modeId,\r\n contextMode: String(context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID),\r\n wsToken,\r\n };\r\n }\r\n\r\n // WebSocket server(s).\r\n //\r\n // When the user keeps the default loopback bind (127.0.0.1), we ALSO open a\r\n // second listener on ::1 (IPv6 loopback). Reason: Chrome/Edge on Windows\r\n // resolve `localhost` to `[::1]` before `127.0.0.1`, so a single v4-only\r\n // bind causes \"ws disconnect hep\" — clients hammer the v6 socket, get\r\n // ECONNREFUSED, fall back to v4 inconsistently. Listening on both v4 and v6\r\n // loopback keeps the connection scope \"this machine only\" while removing\r\n // the resolution-order coin flip.\r\n //\r\n // When the user explicitly sets WS_HOST (e.g. 0.0.0.0 or a LAN IP), we\r\n // respect that choice exactly and don't add a second listener.\r\n // Generate a random WS auth token so only callers that know the token\r\n // can connect. Printed to console on startup; the frontend reads it from\r\n // the URL query param `?token=...`. Without a token, any client on the\r\n // network can connect and send `user_message`/`key.add`/`model.switch`.\r\n const wsToken = generateAuthToken();\r\n // Token is sent to clients via session.start payload — log only a masked\r\n // prefix so operators can correlate without leaking the full secret.\r\n console.log(`[WebUI] WS auth token: ${wsToken.slice(0, 4)}…${wsToken.slice(-4)} (masked)`);\r\n\r\n // CSWSH guard + token auth: when the user exposes the socket beyond loopback,\r\n // require the shared token; loopback connections bootstrap without one. The\r\n // policy (DNS-rebinding Host guard, constant-time token compare, loopback\r\n // bootstrap) lives in ./ws-auth.ts as pure functions — this closure just\r\n // pulls the relevant fields off the incoming request and delegates.\r\n const verifyClient = (info: {\r\n origin: string;\r\n secure: boolean;\r\n req: import('node:http').IncomingMessage;\r\n }) =>\r\n verifyWsClient({\r\n origin: info.origin,\r\n url: info.req.url ?? '',\r\n hostHeader: info.req.headers.host,\r\n remoteAddress: info.req.socket.remoteAddress,\r\n wsHost,\r\n expectedToken: wsToken,\r\n });\r\n // Cap inbound frame size (8 MiB) so a single oversized message can't exhaust\r\n // memory. Agent messages are small; large pastes/attachments stay well under.\r\n const WS_MAX_PAYLOAD = 8 * 1024 * 1024;\r\n const wssPrimary = new WebSocketServer({\r\n port: wsPort,\r\n host: wsHost,\r\n verifyClient,\r\n maxPayload: WS_MAX_PAYLOAD,\r\n } as ConstructorParameters<typeof WebSocketServer>[0]);\r\n const wssSecondary =\r\n wsHost === '127.0.0.1'\r\n ? new WebSocketServer({\r\n port: wsPort,\r\n host: '::1',\r\n verifyClient,\r\n maxPayload: WS_MAX_PAYLOAD,\r\n } as ConstructorParameters<typeof WebSocketServer>[0])\r\n : null;\r\n const clients = new Map<WebSocket, ConnectedClient>();\r\n\r\n // Per-connection message rate limiting: 60 messages per 60-second window.\r\n // Exceeding clients are temporarily blocked to prevent flooding.\r\n // Uses sessionId as the key once connected, falling back to ws for\r\n // pre-auth messages — prevents connection-reuse bypass.\r\n // Rate limit OFF by default (counted pings/list calls too and tripped during\r\n // normal use). Opt in via WEBUI_RATE_LIMIT=<messages-per-60s> for LAN exposure.\r\n const RATE_LIMIT_MESSAGES = Number.parseInt(process.env['WEBUI_RATE_LIMIT'] ?? '0', 10);\r\n const RATE_LIMIT_WINDOW_MS = 60_000;\r\n const rateLimits = new Map<string, { count: number; resetAt: number }>();\r\n\r\n function checkRateLimit(ws: WebSocket, client: ConnectedClient): boolean {\r\n if (RATE_LIMIT_MESSAGES <= 0) return true; // disabled\r\n const now = Date.now();\r\n // Prefer the per-client authenticated sessionId; fall back to the\r\n // WebSocket identity for pre-auth messages before session.start.\r\n const key = client.sessionId ?? String(ws);\r\n const limit = rateLimits.get(key);\r\n if (!limit || now > limit.resetAt) {\r\n rateLimits.set(key, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });\r\n return true;\r\n }\r\n if (limit.count >= RATE_LIMIT_MESSAGES) return false;\r\n limit.count++;\r\n return true;\r\n }\r\n\r\n /** Holds the AbortController for the currently in-flight agent.run().\r\n * Non-null while the agent is running; guarded at the user_message\r\n * handler to prevent concurrent runs that would corrupt shared state\r\n * (context, agent, tokenCounter). A second user_message while running\r\n * is answered with an inline error instead of being queued — the\r\n * caller should wait for run.result. */\r\n let runLock: AbortController | null = null;\r\n\r\n console.log(\r\n `[WebUI] WebSocket server running on ws://${wsHost}:${wsPort}` +\r\n (wssSecondary ? ` (and ws://[::1]:${wsPort})` : ''),\r\n );\r\n\r\n // Pending permission confirmations. When the agent emits\r\n // tool.confirm_needed, we store the resolve function here keyed by\r\n // toolUseId. When the client sends tool.confirm_result back, we look\r\n // it up and resolve — unblocking the agent loop.\r\n const pendingConfirms = new Map<string, (d: 'yes' | 'no' | 'always' | 'deny') => void>();\r\n\r\n const handleConnection = (ws: WebSocket): void => {\r\n const client: ConnectedClient = { ws, sessionId: session.id, connectedAt: Date.now() };\r\n clients.set(ws, client);\r\n console.log('[WebUI] Client connected, total:', clients.size);\r\n\r\n void sessionStartPayload().then((payload) => {\r\n send(ws, { type: 'session.start', payload });\r\n });\r\n\r\n // Register this client with the AutoPhase handler so it receives phase events\r\n autoPhaseHandler.addClient(ws);\r\n // …and the worktree handler for live isolation lanes.\r\n worktreeHandler.addClient(ws);\r\n // …and the collaboration handler for read-only session observation.\r\n collabHandler.addClient(ws);\r\n\r\n ws.on('message', async (data) => {\r\n if (!checkRateLimit(ws, client)) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'rate_limit',\r\n message: 'Too many messages. Please wait before sending more.',\r\n },\r\n });\r\n return;\r\n }\r\n try {\r\n // Prototype pollution guard: reject messages whose root-level payload\r\n // contains __proto__, constructor, or prototype keys. These could\r\n // cause prototype pollution via Object.assign({}, payload) or\r\n // spread {...payload}. The top-level check below catches the\r\n // dangerous keys; nested payload sub-objects are low-risk since\r\n // handlers don't do deep property merges.\r\n const rawObj = JSON.parse(data.toString());\r\n if (typeof rawObj === 'object' && rawObj !== null) {\r\n const obj = rawObj as Record<string, unknown>;\r\n if ('__proto__' in obj || 'constructor' in obj || 'prototype' in obj) {\r\n send(ws, { type: 'error', payload: { phase: 'parse', message: 'Invalid message object' } });\r\n } else {\r\n await handleMessage(ws, client, rawObj as WSClientMessage);\r\n }\r\n } else {\r\n // Non-object JSON (array, string, number…) — pass through\r\n await handleMessage(ws, client, rawObj as unknown as WSClientMessage);\r\n }\r\n } catch (err) {\r\n console.error('[WebUI] Failed to parse message', err);\r\n }\r\n });\r\n\r\n ws.on('close', () => {\r\n clients.delete(ws);\r\n rateLimits.delete(String(ws));\r\n console.log('[WebUI] Client disconnected, total:', clients.size);\r\n // If the client disconnects while a permission prompt is pending,\r\n // resolve all pending confirms with 'no' so the agent loop doesn't\r\n // hang forever waiting for a response that will never come.\r\n if (pendingConfirms.size > 0) {\r\n for (const [id, resolve] of pendingConfirms) {\r\n resolve('no');\r\n pendingConfirms.delete(id);\r\n }\r\n }\r\n });\r\n\r\n ws.on('error', (err) => {\r\n // Without this handler an errored socket would crash the process.\r\n console.warn('[WebUI] Client socket error:', err.message);\r\n });\r\n };\r\n\r\n let eventsArmed = false;\r\n const armOnce = (label: string): void => {\r\n if (eventsArmed) return;\r\n eventsArmed = true;\r\n console.log(`[WebUI] Backend ready (${label})`);\r\n setupEvents({ events, broadcast, clients, config, context, pendingConfirms });\r\n };\r\n\r\n wssPrimary.on('listening', () => armOnce(`${wsHost}:${wsPort}`));\r\n wssPrimary.on('connection', handleConnection);\r\n wssPrimary.on('error', (err) => {\r\n console.error(`[WebUI] Primary WS server error (${wsHost}):`, err);\r\n });\r\n\r\n if (wssSecondary) {\r\n wssSecondary.on('listening', () => armOnce(`::1:${wsPort}`));\r\n wssSecondary.on('connection', handleConnection);\r\n wssSecondary.on('error', (err: NodeJS.ErrnoException) => {\r\n // Best-effort secondary: if IPv6 loopback isn't available on this host\r\n // (e.g. disabled in OS), just log and continue. Primary v4 is enough.\r\n if (err.code === 'EAFNOSUPPORT' || err.code === 'EADDRNOTAVAIL') {\r\n console.warn('[WebUI] IPv6 loopback not available, v4-only:', err.code);\r\n } else {\r\n console.error('[WebUI] Secondary WS server error (::1):', err);\r\n }\r\n });\r\n }\r\n\r\n async function handleMessage(\r\n ws: WebSocket,\r\n _client: ConnectedClient,\r\n msg: WSClientMessage,\r\n ): Promise<void> {\r\n switch (msg.type) {\r\n // Collaboration messages short-circuit the user/agent flow.\r\n // They don't touch runLock, the agent loop, or the message queue —\r\n // they're pure transport for the live observer mirror.\r\n case 'collab.join':\r\n case 'collab.leave':\r\n case 'collab.annotate':\r\n case 'collab.resolve': {\r\n collabHandler.handleMessage(ws, msg as { type: string; payload?: unknown | undefined });\r\n return;\r\n }\r\n case 'user_message': {\r\n const content = (msg as { payload: { content: string } }).payload.content;\r\n\r\n // Guard against concurrent agent runs — a second user_message while\r\n // the agent is already processing would kick off two agent.run()\r\n // calls on the same shared context/agent, leading to corrupted\r\n // state (duplicate tool bubbles, mixed text_delta streams, token\r\n // counter undercount). Reject with an inline error; the frontend\r\n // should wait for run.result before sending the next message.\r\n if (runLock) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'user_message',\r\n message: 'Agent is already processing a request. Wait for the current run to finish.',\r\n },\r\n });\r\n break;\r\n }\r\n\r\n runLock = new AbortController();\r\n // Capture so the finally block only clears its own lock — a\r\n // second race could set a new runLock between await and finally.\r\n const thisRun = runLock;\r\n\r\n try {\r\n const result = await agent.run(content, { signal: thisRun.signal });\r\n send(ws, {\r\n type: 'run.result',\r\n payload: {\r\n status: result.status,\r\n iterations: result.iterations,\r\n finalText: result.finalText,\r\n error: result.error\r\n ? {\r\n code: result.error.code,\r\n message: result.error.message,\r\n recoverable: result.error.recoverable,\r\n }\r\n : undefined,\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'error',\r\n payload: {\r\n phase: 'agent.run',\r\n message: errMessage(err),\r\n },\r\n });\r\n } finally {\r\n // Only clear runLock if it's still ours — otherwise we'd wipe a\r\n // newer run's controller set after we returned.\r\n if (runLock === thisRun) {\r\n runLock = null;\r\n }\r\n }\r\n break;\r\n }\r\n\r\n case 'tool.confirm_result': {\r\n const { id, decision } = (msg as { payload: { id: string; decision: 'yes' | 'no' | 'always' | 'deny' } }).payload;\r\n const resolve = pendingConfirms.get(id);\r\n if (resolve) {\r\n pendingConfirms.delete(id);\r\n resolve(decision);\r\n }\r\n break;\r\n }\r\n\r\n case 'abort':\r\n runLock?.abort();\r\n broadcast(clients, { type: 'error', payload: { phase: 'abort', message: 'User aborted' } });\r\n break;\r\n\r\n case 'ping':\r\n send(ws, { type: 'pong', payload: {} });\r\n break;\r\n\r\n case 'session.new': {\r\n // Truly fresh chat: new on-disk session AND reset every piece of\r\n // in-memory state that survived (messages history, todos, read-file\r\n // tracking, token totals). Otherwise the model still sees the prior\r\n // turns even though the UI looks empty — that's the \"ghost context\"\r\n // bug. After this, the next user message goes out as turn 1 with no\r\n // prior history.\r\n session = await sessionStore.create({\r\n id: '',\r\n title: '',\r\n model: config.model,\r\n provider: config.provider,\r\n });\r\n context.session = session;\r\n context.state.replaceMessages([]);\r\n context.state.replaceTodos([]);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n sessionStartedAt = Date.now();\r\n broadcast(clients, { type: 'session.start', payload: await sessionStartPayload() });\r\n break;\r\n }\r\n\r\n case 'context.clear': {\r\n // Same in-memory wipe as session.new, but reuses the current session\r\n // file (so the JSONL still has the history for audit / replay). The\r\n // user wants a clean slate on the model side; the disk record stays.\r\n context.state.replaceMessages([]);\r\n context.state.replaceTodos([]);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n sendResult(ws, true, 'Context cleared');\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: { ...(await sessionStartPayload()), reset: true },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.debug': {\r\n // Per-section token estimate so users can see what's actually eating\r\n // the context window. The breakdown maths lives in ./token-estimator.ts\r\n // (4-chars-per-token heuristic); we layer the active mode/policy on top.\r\n const breakdown = estimateContextBreakdown({\r\n systemPrompt: context.systemPrompt,\r\n tools: toolRegistry.list(),\r\n messages: context.messages,\r\n });\r\n send(ws, {\r\n type: 'context.debug',\r\n payload: {\r\n ...breakdown,\r\n mode: context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID,\r\n policy: context.meta['contextWindowPolicy'],\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.compact': {\r\n const aggressive = !!(msg as { payload?: { aggressive?: boolean | undefined } }).payload?.aggressive;\r\n try {\r\n const report = await compactor.compact(context, { aggressive });\r\n send(ws, {\r\n type: 'context.compacted',\r\n payload: {\r\n before: report.before,\r\n after: report.after,\r\n saved: Math.max(0, report.before - report.after),\r\n reductions: report.reductions,\r\n repaired: report.repaired,\r\n },\r\n });\r\n sendResult(\r\n ws,\r\n true,\r\n `Compacted: ${report.before} → ${report.after} tokens (saved ~${Math.max(0, report.before - report.after)})`,\r\n );\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'context.repair': {\r\n const beforeMessages = context.messages.length;\r\n const repaired = repairToolUseAdjacency(context.messages);\r\n if (repaired.report.changed) {\r\n context.state.replaceMessages(repaired.messages);\r\n }\r\n const payload = {\r\n removedToolUses: repaired.report.removedToolUses,\r\n removedToolResults: repaired.report.removedToolResults,\r\n removedMessages: repaired.report.removedMessages,\r\n beforeMessages,\r\n afterMessages: context.messages.length,\r\n };\r\n broadcast(clients, { type: 'context.repaired', payload });\r\n const removed =\r\n payload.removedToolUses.length +\r\n payload.removedToolResults.length +\r\n payload.removedMessages;\r\n sendResult(\r\n ws,\r\n true,\r\n removed > 0\r\n ? `Context repaired: removed ${removed} orphan protocol item(s)`\r\n : 'Context repair found no orphan protocol blocks',\r\n );\r\n break;\r\n }\r\n\r\n case 'context.modes.list': {\r\n const active = String(context.meta['contextWindowMode'] ?? DEFAULT_CONTEXT_WINDOW_MODE_ID);\r\n send(ws, {\r\n type: 'context.modes.list',\r\n payload: {\r\n activeId: active,\r\n modes: listContextWindowModes().map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n description: m.description,\r\n isActive: m.id === active,\r\n thresholds: m.thresholds,\r\n preserveK: m.preserveK,\r\n eliseThreshold: m.eliseThreshold,\r\n })),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'context.mode.switch': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n const policy = resolveContextWindowPolicy({}, id);\r\n if (policy.id !== id) {\r\n sendResult(ws, false, `Unknown context mode \"${id}\"`);\r\n break;\r\n }\r\n context.meta['contextWindowMode'] = policy.id;\r\n context.meta['contextWindowPolicy'] = policy;\r\n sendResult(ws, true, `Context mode switched to ${policy.id}`);\r\n broadcast(clients, {\r\n type: 'context.mode.changed',\r\n payload: { id: policy.id, name: policy.name, policy },\r\n });\r\n break;\r\n }\r\n\r\n case 'providers.list': {\r\n const providers = await modelsRegistry.listProviders();\r\n // \"Configured\" should mean *any* working credential, not just env vars.\r\n // Users register keys with `wstack auth`, which writes apiKey/apiKeys\r\n // into config.providers[<id>] — those are decrypted in memory here.\r\n const savedIds = new Set(Object.keys(config.providers ?? {}));\r\n send(ws, {\r\n type: 'provider.catalog',\r\n payload: {\r\n providers: providers.map((p) => ({\r\n id: p.id,\r\n name: p.name,\r\n family: p.family,\r\n apiBase: p.apiBase,\r\n envVars: p.envVars,\r\n modelCount: p.models.length,\r\n hasApiKey: savedIds.has(p.id) || p.envVars.some((v) => !!process.env[v]),\r\n })),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'providers.saved': {\r\n const saved = await providerHandlers.loadConfigProviders();\r\n send(ws, {\r\n type: 'providers.saved',\r\n payload: {\r\n providers: Object.entries(saved).map(([id, cfg]) => {\r\n const keys = normalizeKeys(cfg);\r\n return {\r\n id,\r\n family: cfg.family ?? id,\r\n baseUrl: cfg.baseUrl,\r\n apiKeys: keys.map((k) => ({\r\n label: k.label,\r\n maskedKey: maskedKey(k.apiKey),\r\n isActive: k.label === cfg.activeKey,\r\n createdAt: k.createdAt,\r\n })),\r\n };\r\n }),\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'provider.models': {\r\n const providerId = (msg as { payload: { providerId: string } }).payload.providerId;\r\n const provider = await modelsRegistry.getProvider(providerId);\r\n if (provider) {\r\n send(ws, {\r\n type: 'provider.models',\r\n payload: {\r\n provider: providerId,\r\n models: provider.models.map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n releaseDate: (m as { release_date?: string | undefined }).release_date,\r\n contextWindow: (m as { limit?: { context?: number | undefined } }).limit?.context,\r\n inputCost: (m as { cost?: { input?: number | undefined } }).cost?.input,\r\n outputCost: (m as { cost?: { output?: number | undefined } }).cost?.output,\r\n capabilities: [\r\n ...((m as { tool_call?: boolean | undefined }).tool_call ? ['tools'] : []),\r\n ...((m as { reasoning?: boolean | undefined }).reasoning ? ['reasoning'] : []),\r\n ],\r\n })),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'model.switch': {\r\n const { provider: newProvider, model: newModel } = (\r\n msg as { payload: { provider: string; model: string } }\r\n ).payload;\r\n try {\r\n // Update config\r\n config = patchConfig(config, { provider: newProvider, model: newModel });\r\n configStore.update({ provider: newProvider, model: newModel });\r\n context.model = newModel;\r\n\r\n // Create new provider instance — fail loudly if the user picks a\r\n // provider with no creds rather than silently keeping the old one.\r\n const providerCfg = config.providers?.[newProvider] ?? { type: newProvider };\r\n const newProv = providerRegistry.has(newProvider)\r\n ? providerRegistry.create({ ...providerCfg, type: newProvider })\r\n : makeProviderFromConfig(newProvider, providerCfg);\r\n context.provider = newProv;\r\n\r\n // Update AutoCompactionMiddleware with the new model's maxContext so\r\n // backend threshold triggers (warn/soft/hard) use the correct denominator.\r\n // sessionStartPayload is called below (after this block) and uses\r\n // the new provider for its modelsRegistry lookup.\r\n updateAutoCompactionMaxContext?.(newProv);\r\n\r\n // Persist to global config file\r\n try {\r\n configWriteLock = configWriteLock.then(async () => {\r\n const raw = await fs.readFile(globalConfigPath, 'utf8');\r\n const parsed = JSON.parse(raw);\r\n parsed.provider = newProvider;\r\n parsed.model = newModel;\r\n await atomicWrite(globalConfigPath, JSON.stringify(parsed, null, 2));\r\n });\r\n await configWriteLock;\r\n } catch (err) {\r\n console.warn('[WebUI] Failed to save config:', err);\r\n }\r\n\r\n // Toast for the SettingsPanel\r\n send(ws, {\r\n type: 'key.operation_result',\r\n payload: { success: true, message: `Switched to ${newProvider} / ${newModel}` },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'key.operation_result',\r\n payload: {\r\n success: false,\r\n message: `Switch failed: ${errMessage(err)}`,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n broadcast(clients, { type: 'session.start', payload: await sessionStartPayload() });\r\n break;\r\n }\r\n\r\n case 'key.add':\r\n case 'key.update': {\r\n const { providerId, label, apiKey } = (\r\n msg as { payload: { providerId: string; label: string; apiKey: string } }\r\n ).payload;\r\n await providerHandlers.handleKeyUpsert(ws, providerId, label, apiKey);\r\n break;\r\n }\r\n\r\n case 'key.delete': {\r\n const { providerId, label } = (msg as { payload: { providerId: string; label: string } })\r\n .payload;\r\n await providerHandlers.handleKeyDelete(ws, providerId, label);\r\n break;\r\n }\r\n\r\n case 'key.set_active': {\r\n const { providerId, label } = (msg as { payload: { providerId: string; label: string } })\r\n .payload;\r\n await providerHandlers.handleKeySetActive(ws, providerId, label);\r\n break;\r\n }\r\n\r\n case 'provider.add': {\r\n const p = (\r\n msg as { payload: { id: string; family: string; baseUrl?: string | undefined; apiKey?: string | undefined } }\r\n ).payload;\r\n await providerHandlers.handleProviderAdd(ws, p);\r\n break;\r\n }\r\n\r\n case 'provider.remove': {\r\n const { providerId } = (msg as { payload: { providerId: string } }).payload;\r\n await providerHandlers.handleProviderRemove(ws, providerId);\r\n break;\r\n }\r\n\r\n case 'sessions.list': {\r\n // Per-project history. Sessions live under .wrongstack/sessions/ for\r\n // this project; we never enumerate cross-project state.\r\n const limit = (msg as { payload?: { limit?: number | undefined } }).payload?.limit ?? 50;\r\n try {\r\n const list = await sessionStore.list(limit);\r\n send(ws, {\r\n type: 'sessions.list',\r\n payload: {\r\n sessions: list.map((s) => ({\r\n id: s.id,\r\n title: s.title,\r\n startedAt: s.startedAt,\r\n model: s.model,\r\n provider: s.provider,\r\n tokenTotal: s.tokenTotal,\r\n isCurrent: s.id === session.id,\r\n })),\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'sessions.list',\r\n payload: { sessions: [], error: errMessage(err) },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'session.delete': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n if (id === session.id) {\r\n sendResult(ws, false, 'Cannot delete the active session');\r\n break;\r\n }\r\n await sessionStore.delete(id);\r\n sendResult(ws, true, `Session ${id} deleted`);\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'session.resume': {\r\n // Load a past session's messages + usage, swap the active session\r\n // writer, hydrate the live Context, then broadcast a session.start\r\n // payload tagged with the replayed transcript so the UI can render\r\n // the chat history.\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n if (id === session.id) {\r\n sendResult(ws, false, 'Session is already active');\r\n break;\r\n }\r\n const resumed = await sessionStore.resume(id);\r\n // Close prior writer best-effort; swallow errors so we don't block\r\n // the resume on a crashed file handle.\r\n try {\r\n await session.close();\r\n } catch {\r\n /* noop */\r\n }\r\n session = resumed.writer;\r\n context.session = session;\r\n context.state.replaceMessages(resumed.data.messages);\r\n context.readFiles.clear();\r\n context.fileMtimes.clear();\r\n tokenCounter.reset();\r\n // Replay usage so the topbar shows accurate totals after resume.\r\n tokenCounter.account(resumed.data.usage, config.model);\r\n sessionStartedAt = Date.now();\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: {\r\n ...(await sessionStartPayload()),\r\n reset: true,\r\n replayMessages: resumed.data.messages,\r\n replayUsage: resumed.data.usage,\r\n },\r\n });\r\n sendResult(ws, true, `Resumed session ${id}`);\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'session.save': {\r\n // SessionWriter already flushes after every event; this is mostly a\r\n // no-op marker so the user gets confirmation. Useful for habit\r\n // parity with the CLI /save command.\r\n sendResult(ws, true, `Session ${session.id} is auto-saved`);\r\n break;\r\n }\r\n\r\n case 'tools.list': {\r\n // Full tool registry dump for the /tools inspect view. We surface\r\n // name, description, and schema-derived param names so the user\r\n // can tell at a glance which tools the model can call right now.\r\n const list = toolRegistry.list().map((t) => {\r\n const schema =\r\n (t as { inputSchema?: { properties?: Record<string, unknown> } }).inputSchema ?? {};\r\n const params = schema.properties ? Object.keys(schema.properties) : [];\r\n return {\r\n name: t.name,\r\n description: (t as { description?: string | undefined }).description ?? '',\r\n params,\r\n };\r\n });\r\n send(ws, { type: 'tools.list', payload: { tools: list } });\r\n break;\r\n }\r\n\r\n case 'memory.list': {\r\n // All three scopes (project-agents, project-memory, user-memory)\r\n // rolled up as readAll already does. Returned as raw markdown so\r\n // the UI can render with the same style as everything else.\r\n try {\r\n const text = await memoryStore.readAll();\r\n send(ws, { type: 'memory.list', payload: { text } });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'memory.list',\r\n payload: { text: '', error: errMessage(err) },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'memory.remember': {\r\n const { text, scope } = (\r\n msg as {\r\n payload: { text: string; scope?: 'project-agents' | 'project-memory' | 'user-memory' | undefined };\r\n }\r\n ).payload;\r\n try {\r\n await memoryStore.remember(text, scope ?? 'project-memory');\r\n sendResult(ws, true, 'Saved to memory');\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'memory.forget': {\r\n const { text, scope } = (\r\n msg as {\r\n payload: { text: string; scope?: 'project-agents' | 'project-memory' | 'user-memory' | undefined };\r\n }\r\n ).payload;\r\n try {\r\n const removed = await memoryStore.forget(text, scope ?? 'project-memory');\r\n sendResult(\r\n ws,\r\n removed > 0,\r\n removed > 0\r\n ? `Removed ${removed} entr${removed === 1 ? 'y' : 'ies'}`\r\n : 'No matching entries',\r\n );\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'skills.list': {\r\n if (!skillLoader) {\r\n send(ws, { type: 'skills.list', payload: { skills: [], enabled: false } });\r\n break;\r\n }\r\n try {\r\n const manifests = await skillLoader.list();\r\n const entries = await skillLoader.listEntries();\r\n const byName = new Map(entries.map((e) => [e.name, e]));\r\n send(ws, {\r\n type: 'skills.list',\r\n payload: {\r\n enabled: true,\r\n skills: manifests.map((m) => ({\r\n name: m.name,\r\n description: m.description,\r\n version: m.version ?? '',\r\n source: m.source,\r\n path: m.path,\r\n trigger: byName.get(m.name)?.trigger ?? '',\r\n scope: byName.get(m.name)?.scope ?? [],\r\n })),\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'skills.list',\r\n payload: {\r\n skills: [],\r\n enabled: true,\r\n error: errMessage(err),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'diag.get': {\r\n // Snapshot of the moving parts so the user can debug \"why is X\r\n // not working?\" without diving into the server logs.\r\n const usage = tokenCounter.total();\r\n send(ws, {\r\n type: 'diag.get',\r\n payload: {\r\n provider: config.provider,\r\n model: config.model,\r\n cwd: projectRoot,\r\n sessionId: session.id,\r\n tools: {\r\n count: toolRegistry.list().length,\r\n names: toolRegistry.list().map((t) => t.name),\r\n },\r\n features: {\r\n memory: !!config.features?.memory,\r\n skills: !!config.features?.skills,\r\n modelsRegistry: !!config.features?.modelsRegistry,\r\n },\r\n mode: modeId ?? 'default',\r\n usage,\r\n messages: context.messages.length,\r\n todos: context.todos.length,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n case 'todos.get': {\r\n // On-demand snapshot — used when a UI surface first mounts and\r\n // needs to render the live todo list without waiting for the next\r\n // tool.executed to broadcast.\r\n send(ws, {\r\n type: 'todos.updated',\r\n payload: { todos: [...context.todos] },\r\n });\r\n break;\r\n }\r\n\r\n case 'todos.clear': {\r\n // Manual override — the agent normally curates this list via\r\n // TodoWrite, but the user might want a clean slate without losing\r\n // the rest of the context. Use state.replaceTodos so observers\r\n // (checkpoint writer) stay in sync.\r\n context.state.replaceTodos([]);\r\n sendResult(ws, true, 'Todos cleared');\r\n broadcast(clients, { type: 'todos.updated', payload: { todos: [] } });\r\n break;\r\n }\r\n\r\n case 'todos.remove': {\r\n // Remove a single todo item by id or 1-based index.\r\n const payload = msg.payload as { id?: string | undefined; index?: number | undefined } | undefined;\r\n if (!payload) { sendResult(ws, false, 'Missing id or index'); break; }\r\n const { id, index } = payload;\r\n let targetIdx = -1;\r\n if (typeof id === 'string') {\r\n targetIdx = context.todos.findIndex((t) => t.id === id);\r\n } else if (typeof index === 'number' && index > 0) {\r\n targetIdx = index - 1;\r\n }\r\n if (targetIdx < 0 || !context.todos[targetIdx]) {\r\n sendResult(ws, false, 'Todo not found');\r\n break;\r\n }\r\n const removed = expectDefined(context.todos[targetIdx]);\r\n const next = [\r\n ...context.todos.slice(0, targetIdx),\r\n ...context.todos.slice(targetIdx + 1),\r\n ];\r\n context.state.replaceTodos(next);\r\n sendResult(ws, true, `Removed: ${removed.content}`);\r\n broadcast(clients, { type: 'todos.updated', payload: { todos: next } });\r\n break;\r\n }\r\n\r\n case 'plan.get': {\r\n // On-demand plan snapshot — used when a UI surface first mounts\r\n // and needs to render the live plan without waiting for the next\r\n // tool.executed to broadcast.\r\n const planPath = (context.meta as Record<string, unknown>)['plan.path'];\r\n if (typeof planPath === 'string' && planPath) {\r\n try {\r\n const { loadPlan } = await import('@wrongstack/core');\r\n const plan = await loadPlan(planPath);\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: plan ?? { version: 1, sessionId: session.id, updatedAt: new Date().toISOString(), items: [] } },\r\n });\r\n } catch {\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: { version: 1, sessionId: session.id, updatedAt: new Date().toISOString(), items: [] } },\r\n });\r\n }\r\n } else {\r\n send(ws, {\r\n type: 'plan.updated',\r\n payload: { plan: null, error: 'Plan storage is not configured for this session.' },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'plan.template_use': {\r\n const { template } = (msg as { payload: { template: string } }).payload;\r\n const planPath = (context.meta as Record<string, unknown>)['plan.path'];\r\n if (typeof planPath !== 'string' || !planPath) {\r\n sendResult(ws, false, 'Plan storage is not configured for this session.');\r\n break;\r\n }\r\n try {\r\n const { getPlanTemplate, loadPlan, savePlan, emptyPlan, addPlanItem } = await import('@wrongstack/core');\r\n const tpl = getPlanTemplate(template);\r\n if (!tpl) {\r\n sendResult(ws, false, `Unknown template \"${template}\".`);\r\n break;\r\n }\r\n let plan = (await loadPlan(planPath)) ?? emptyPlan(session.id);\r\n for (const item of tpl.items) {\r\n ({ plan } = addPlanItem(plan, item.title, item.details));\r\n }\r\n await savePlan(planPath, plan);\r\n sendResult(ws, true, `Applied template \"${tpl.name}\" — ${tpl.items.length} items added.`);\r\n broadcast(clients, {\r\n type: 'plan.updated',\r\n payload: { plan },\r\n });\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'files.list': {\r\n // Lightweight project file picker for the chat `@` mention popup.\r\n // Walks projectRoot, skipping the heavyweight build/vcs/node_modules\r\n // dirs that would blow up the response on a real project. Applies\r\n // a fuzzy substring match against the (lowercased) query and caps\r\n // the result so the popup never has to paginate.\r\n const payload = (msg as { payload?: { query?: string | undefined; limit?: number | undefined } }).payload ?? {};\r\n const limit = payload.limit ?? 50;\r\n // Filtering (isHiddenEntry/SKIP_DIRS) and ranking (rankFiles) live in\r\n // ./file-picker.ts; the walk itself stays here since it's disk I/O.\r\n const results: string[] = [];\r\n async function walk(dir: string, rel: string, depth: number): Promise<void> {\r\n if (depth > 8 || results.length >= 600) return;\r\n let entries: import('node:fs').Dirent[] = [];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n for (const e of entries) {\r\n if (results.length >= 600) return;\r\n if (isHiddenEntry(e.name)) continue;\r\n const childRel = rel ? `${rel}/${e.name}` : e.name;\r\n if (e.isDirectory()) {\r\n if (SKIP_DIRS.has(e.name)) continue;\r\n await walk(path.join(dir, e.name), childRel, depth + 1);\r\n } else if (e.isFile()) {\r\n results.push(childRel);\r\n }\r\n }\r\n }\r\n await walk(projectRoot, '', 0);\r\n send(ws, {\r\n type: 'files.list',\r\n payload: { files: rankFiles(results, payload.query ?? '', limit) },\r\n });\r\n break;\r\n }\r\n\r\n case 'modes.list': {\r\n try {\r\n const modes = await modeStore.listModes();\r\n const active = await modeStore.getActiveMode();\r\n send(ws, {\r\n type: 'modes.list',\r\n payload: {\r\n modes: modes.map((m) => ({\r\n id: m.id,\r\n name: m.name,\r\n description: m.description,\r\n isActive: m.id === (active?.id ?? 'default'),\r\n })),\r\n activeId: active?.id ?? 'default',\r\n },\r\n });\r\n } catch (err) {\r\n send(ws, {\r\n type: 'modes.list',\r\n payload: {\r\n modes: [],\r\n activeId: 'default',\r\n error: errMessage(err),\r\n },\r\n });\r\n }\r\n break;\r\n }\r\n\r\n case 'mode.switch': {\r\n const { id } = (msg as { payload: { id: string } }).payload;\r\n try {\r\n // 'default' is the implicit no-mode state — persisting null\r\n // clears the override. Anything else has to exist in the store.\r\n if (id === 'default') {\r\n await modeStore.setActiveMode(null);\r\n } else {\r\n const found = await modeStore.getMode(id);\r\n if (!found) throw new Error(`Unknown mode \"${id}\"`);\r\n await modeStore.setActiveMode(id);\r\n }\r\n modeId = id;\r\n // Rebuild the system prompt so the next turn picks up the new\r\n // mode's instructions. The builder caches the environment block\r\n // per projectRoot (including the modeId), so we clear the cache\r\n // and rebuild. The `buildMode()` method reads this.opts.modePrompt\r\n // which is set on the builder constructor — we construct a fresh\r\n // builder with the updated mode. This is cheap (no fs/net IO in\r\n // the constructor; the real work happens in build()).\r\n const modePrompt = id === 'default' ? '' : ((await modeStore.getMode(id))?.prompt ?? '');\r\n const freshBuilder = new DefaultSystemPromptBuilder({\r\n memoryStore,\r\n skillLoader,\r\n modeStore,\r\n modeId: id,\r\n modePrompt,\r\n modelCapabilities,\r\n });\r\n context.systemPrompt = await freshBuilder.build({\r\n cwd: projectRoot,\r\n projectRoot,\r\n tools: toolRegistry.list(),\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n sendResult(ws, true, `Switched to mode \"${id}\"`);\r\n broadcast(clients, {\r\n type: 'session.start',\r\n payload: { ...(await sessionStartPayload()) },\r\n });\r\n } catch (err) {\r\n sendResult(ws, false, errMessage(err));\r\n }\r\n break;\r\n }\r\n\r\n case 'stats.get': {\r\n // Mirror of the CLI's /stats: detailed session report.\r\n const usage = tokenCounter.total();\r\n const cacheStats = tokenCounter.cacheStats();\r\n const m = await modelsRegistry.getModel(config.provider, config.model).catch(() => null);\r\n const cost = computeUsageCost(usage, getCostRates(m));\r\n send(ws, {\r\n type: 'stats.get',\r\n payload: {\r\n sessionId: session.id,\r\n provider: config.provider,\r\n model: config.model,\r\n usage,\r\n cache: cacheStats,\r\n cost,\r\n messages: context.messages.length,\r\n readFiles: context.readFiles.size,\r\n tools: toolRegistry.list().length,\r\n elapsedMs: Date.now() - sessionStartedAt,\r\n },\r\n });\r\n break;\r\n }\r\n\r\n default:\r\n if (msg.type.startsWith('autophase.')) {\r\n // Delegate all AutoPhase lifecycle messages to the handler\r\n await autoPhaseHandler.handleMessage(msg as { type: string; payload?: Record<string, unknown> });\r\n } else {\r\n send(ws, { type: 'error', payload: { phase: 'handleMessage', message: `Unknown message type: ${msg.type}` } });\r\n }\r\n }\r\n }\r\n\r\n // ---- Provider/Key management helpers (extracted to provider-handlers.ts) ----\r\n const providerHandlers = createProviderHandlers({\r\n globalConfigPath,\r\n vault,\r\n getConfigWriteLock: () => configWriteLock,\r\n setConfigWriteLock: (p) => { configWriteLock = p; },\r\n });\r\n\r\n // HTTP server for the React frontend (port 3456) — see `http-server.ts`\r\n // for the static-serve, MIME matching, path-traversal guard, and CSP\r\n // header logic. Constructed here, listen()d below alongside the WS server.\r\n const httpServer = createHttpServer({\r\n host: wsHost,\r\n distDir: path.resolve(import.meta.dirname, '../../dist'),\r\n wsPort,\r\n });\r\n // httpPort/wsPort were resolved (and possibly auto-advanced) at the top.\r\n // Base dir for the running-instance registry — keep it next to the rest of\r\n // the wstack home state (config.json lives here too).\r\n const registryBaseDir = path.dirname(globalConfigPath);\r\n httpServer.listen(httpPort, wsHost, () => {\r\n const openUrl = `http://${wsHost}:${httpPort}`;\r\n console.log(`[WebUI] HTTP server running on ${openUrl}`);\r\n // Optionally pop the browser open (best-effort; the URL is always printed).\r\n if (opts.open) openBrowser(openUrl);\r\n // Record this instance so `webui --list` (and `~/.wrongstack/\r\n // webui-instances.json`) show which ports are open for which project.\r\n // Best-effort: a registry write failure must not affect serving.\r\n void registerInstance(\r\n {\r\n pid: process.pid,\r\n httpPort,\r\n wsPort,\r\n host: wsHost,\r\n projectRoot,\r\n projectName: path.basename(projectRoot) || projectRoot,\r\n startedAt: new Date().toISOString(),\r\n url: `http://${wsHost}:${httpPort}`,\r\n },\r\n registryBaseDir,\r\n ).catch((err) => console.warn('[WebUI] Could not record instance:', errMessage(err)));\r\n });\r\n\r\n // Graceful shutdown on SIGINT/SIGTERM — see `lifecycle.ts`. The session\r\n // flush (session_end + close) is passed as a thunk so lifecycle stays\r\n // decoupled from the session/tokenCounter types.\r\n registerShutdownHandlers({\r\n flushSession: async () => {\r\n await session.append({\r\n type: 'session_end',\r\n ts: new Date().toISOString(),\r\n usage: tokenCounter.total(),\r\n });\r\n await session.close();\r\n },\r\n clients: () => clients.keys(),\r\n servers: [httpServer, wssPrimary, wssSecondary],\r\n // Drop this instance from the registry on a clean exit so the file reflects\r\n // reality. Crash exits are healed by the next register()/list() prune pass.\r\n onShutdown: () => unregisterInstance(process.pid, registryBaseDir),\r\n });\r\n}\r\n","/**\n * Static-file HTTP server for the WebUI React frontend.\n *\n * - Serves files from `distDir` (typically `<webui>/dist`).\n * - Returns `index.html` for any unknown path so client-side routing works\n * (SPA fallback) — and applies the same Content-Security-Policy to that\n * fallback as to a direct `.html` response, so deep-linked routes are\n * not unprotected.\n * - **Path-traversal guard**: `path.join` alone does NOT prevent\n * `%2e%2e%2f` escapes (the `URL` constructor decodes percent-encoding\n * before we see the path). We re-`resolve` the candidate and verify it\n * stays under `distDir`.\n * - **CSP**: `connect-src` uses explicit loopback addresses for the WS\n * server (not bare `ws:` / `wss:`) so a malicious page script cannot\n * dial an attacker-controlled WebSocket. Combined with token-in-URL\n * (C-2), this prevents cross-origin WS abuse.\n *\n * Extracted from `index.ts` so the static-serve concern can be tested\n * with a tiny fake `distDir` and asserted on path-traversal, MIME\n * matching, and CSP header presence.\n */\nimport * as fs from 'node:fs/promises';\nimport * as http from 'node:http';\nimport * as path from 'node:path';\n\nexport interface CreateHttpServerOptions {\n /** Port to listen on. Defaults to 3456 (or the `PORT` env var). */\n port?: number | undefined;\n /** Host/interface to bind. Typically the loopback for the WebUI. */\n host: string;\n /** Resolved path to the directory containing the built React assets. */\n distDir: string;\n /**\n * WS port — appears in the CSP `connect-src` directive so the browser\n * is allowed to open a WebSocket back to the local server.\n */\n wsPort: number;\n}\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Inject the live WS port into the served HTML so the frontend connects to\n * THIS instance's backend instead of a hardcoded default. Enables running\n * several WebUI instances simultaneously on different PORT/WS_PORT pairs\n * (e.g. one per project) — each instance serves HTML stamped with its own\n * WS port.\n *\n * A `<meta>` tag is used deliberately rather than an inline `<script>`: the\n * CSP sets `script-src 'self'`, which would block an inline script, but meta\n * tags are not subject to script-src. The frontend reads\n * `meta[name=\"wrongstack-ws-port\"]` (see ws-client.ts `defaultWsUrl`).\n */\nexport function injectWsPort(html: string, wsPort: number): string {\n const tag = `<meta name=\"wrongstack-ws-port\" content=\"${wsPort}\" />`;\n // Idempotent: never inject twice if the source HTML already carries one.\n if (html.includes('name=\"wrongstack-ws-port\"')) return html;\n if (html.includes('</head>')) {\n return html.replace('</head>', ` ${tag}\\n </head>`);\n }\n // No <head> (unexpected) — prepend so the tag is still in the document.\n return `${tag}\\n${html}`;\n}\n\n/** Build the Content-Security-Policy value for the given WS port. */\nexport function buildCspHeader(wsPort: number): string {\n return (\n `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; ` +\n `connect-src 'self' ws://127.0.0.1:${wsPort} wss://127.0.0.1:${wsPort} ` +\n `ws://[::1]:${wsPort} wss://[::1]:${wsPort}; ` +\n `img-src 'self' data:; font-src 'self' data:; object-src 'none'; ` +\n `base-uri 'self'; frame-ancestors 'none'; form-action 'self'`\n );\n}\n\n/**\n * Returns true when `candidate` (a fully-resolved absolute path) lies\n * strictly inside `distDir` (or equals it). Used to reject path-traversal\n * attempts after `path.resolve` has normalised any `..` segments.\n *\n * Exported so tests can assert the guard's contract without having to\n * also defeat the WHATWG URL normaliser (which strips `..` from the\n * path string *before* the request even reaches the server, making a\n * black-box test via fetch impossible).\n */\nexport function isInsideDist(candidate: string, distDir: string): boolean {\n const root = path.resolve(distDir);\n const resolved = path.resolve(candidate);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/**\n * Create the static-file HTTP server. Returns the `http.Server` (not\n * listening yet) so the caller can attach to a `shutdown()` hook and\n * coordinate the listen() with the WebSocket bootstrap.\n */\nexport function createHttpServer(opts: CreateHttpServerOptions): http.Server {\n const port = opts.port ?? Number.parseInt(process.env['PORT'] ?? '3456', 10);\n const distDir = path.resolve(opts.distDir);\n const wsPort = opts.wsPort;\n\n return http.createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);\n let filePath: string;\n\n if (url.pathname === '/' || url.pathname === '') {\n filePath = path.join(distDir, 'index.html');\n } else if (url.pathname.startsWith('/assets/')) {\n filePath = path.join(distDir, url.pathname);\n } else if (url.pathname.startsWith('/')) {\n filePath = path.join(distDir, url.pathname);\n } else {\n filePath = path.join(distDir, 'index.html');\n }\n\n // Path traversal guard: the resolved path must stay inside distDir.\n // WHATWG URL leaves percent-encoding alone in `url.pathname` (it\n // does not decode `%2e%2e` to `..`), so percent-encoded escapes\n // are *not* a concern here — but unencoded `..` segments are\n // normalised by `path.resolve` and would walk the candidate up\n // out of distDir. `isInsideDist` catches that.\n const resolvedPath = path.resolve(filePath);\n if (!isInsideDist(resolvedPath, distDir)) {\n res.writeHead(403, { 'Content-Type': 'text/plain' });\n res.end('Forbidden');\n return;\n }\n\n const ext = path.extname(resolvedPath);\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';\n res.setHeader('Content-Type', contentType);\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'DENY');\n res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');\n\n if (ext === '.html') {\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Content-Security-Policy', buildCspHeader(wsPort));\n // Stamp the live WS port into the HTML so the frontend dials this\n // instance's backend (not the hardcoded default) — required for\n // running multiple WebUI instances on different ports.\n const html = await fs.readFile(resolvedPath, 'utf8');\n res.writeHead(200);\n res.end(injectWsPort(html, wsPort));\n return;\n }\n\n const fileContent = await fs.readFile(resolvedPath);\n res.writeHead(200);\n res.end(fileContent);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n // SPA fallback: serve index.html so client-side routing still works.\n try {\n const html = await fs.readFile(path.join(distDir, 'index.html'), 'utf8');\n res.writeHead(200, {\n 'Content-Type': 'text/html',\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\n 'Content-Security-Policy': buildCspHeader(wsPort),\n });\n res.end(injectWsPort(html, wsPort));\n } catch {\n res.writeHead(404);\n res.end('Not found');\n }\n } else {\n res.writeHead(500);\n res.end('Server error');\n }\n }\n });\n}\n","/**\n * Pure filtering + ranking for the `files.list` project file picker (the chat\n * `@`-mention popup). The directory *walk* stays in index.ts (it's I/O), but\n * the two decisions that shape the result — which entries to hide and how to\n * rank matches — are pure and live here so the scoring weights, depth penalty,\n * and tie-break order can be unit tested. A silently-flipped weight would make\n * the picker feel subtly wrong with nothing to catch it.\n */\n/** Heavyweight build/vcs/dependency dirs the picker never descends into. */\nexport const SKIP_DIRS: ReadonlySet<string> = new Set([\n '.git',\n 'node_modules',\n 'dist',\n 'build',\n '.next',\n '.turbo',\n '.cache',\n 'target',\n 'coverage',\n '.nyc_output',\n 'out',\n '.pnpm-store',\n '.parcel-cache',\n]);\n\n/** Dotfiles/dirs kept despite the hide-dotfiles-by-default rule. */\nconst KEEP_DOTFILES: ReadonlySet<string> = new Set([\n '.wrongstack',\n '.env.example',\n '.gitignore',\n '.eslintrc',\n '.prettierrc',\n]);\n\n/**\n * Whether a directory entry should be hidden from the picker by its name.\n * Dotfiles are hidden by default, except a few commonly-wanted ones.\n */\nexport function isHiddenEntry(name: string): boolean {\n return name.startsWith('.') && !KEEP_DOTFILES.has(name);\n}\n\n/**\n * Rank `paths` against `query` and return up to `limit` paths, best first.\n *\n * Scoring (cheap heuristic, good enough for a picker): exact basename match\n * (100) > basename prefix (60) > path substring (20); non-matches are dropped.\n * Each match is penalized by its path depth so root files sort first. Ties\n * break by lexicographic path. An empty query keeps every path (score 0), so\n * the result is the paths sorted lexicographically, capped to `limit`.\n */\nexport function rankFiles(paths: readonly string[], query: string, limit: number): string[] {\n const q = query.toLowerCase();\n const scored: Array<{ path: string; score: number }> = [];\n for (const p of paths) {\n if (!q) {\n scored.push({ path: p, score: 0 });\n continue;\n }\n const lower = p.toLowerCase();\n const base = lower.split('/').pop() ?? lower;\n let score = 0;\n if (base === q) score = 100;\n else if (base.startsWith(q)) score = 60;\n else if (lower.includes(q)) score = 20;\n else continue;\n // Penalise depth so root files come first.\n score -= p.split('/').length;\n scored.push({ path: p, score });\n }\n scored.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n return scored.slice(0, limit).map((s) => s.path);\n}\n","import {\n type Config,\n Container,\n DefaultConfigStore,\n DefaultErrorHandler,\n DefaultMemoryStore,\n DefaultModeStore,\n DefaultPermissionPolicy,\n DefaultRetryPolicy,\n DefaultSecretScrubber,\n DefaultSessionStore,\n DefaultSkillLoader,\n DefaultSystemPromptBuilder,\n DefaultTokenCounter,\n HybridCompactor,\n type Logger,\n type ModelsRegistry,\n TOKENS,\n type Tool,\n type WstackPaths,\n} from '@wrongstack/core';\nimport type { DefaultSystemPromptBuilderOptions } from '@wrongstack/core';\n\nexport interface CreateContainerOptions {\n config: Config;\n wpaths: WstackPaths;\n logger: Logger;\n modelsRegistry: ModelsRegistry;\n permission?: {\n yolo?: boolean | undefined;\n yoloDestructive?: boolean | undefined;\n /** @deprecated Use `yoloDestructive`. */\n forceAllYolo?: boolean | undefined;\n /** When true, destructive ops prompt even in YOLO mode. */\n confirmDestructive?: boolean | undefined;\n promptDelegate?: (\n tool: Tool,\n input: unknown,\n suggestedPattern: string,\n ) => Promise<'yes' | 'no' | 'always' | 'deny'>;\n };\n compactor?: { preserveK?: number | undefined; eliseThreshold?: number | undefined };\n systemPrompt?: Partial<DefaultSystemPromptBuilderOptions> | undefined;\n /** Bundled skills directory path (resolved at boot time). */\n bundledSkillsDir?: string | undefined;\n}\n\n/**\n * Create a Container pre-bound with all default service implementations.\n * Both CLI and WebUI use this factory so container wiring stays in one place.\n */\nexport function createDefaultContainer(opts: CreateContainerOptions): Container {\n const { config, wpaths, logger, modelsRegistry } = opts;\n const container = new Container();\n\n const configStore = new DefaultConfigStore(config);\n container.bind(TOKENS.ConfigStore, () => configStore);\n container.bind(TOKENS.Logger, () => logger);\n container.bind(TOKENS.SecretScrubber, () => new DefaultSecretScrubber());\n container.bind(TOKENS.RetryPolicy, () => new DefaultRetryPolicy());\n container.bind(TOKENS.ErrorHandler, () => new DefaultErrorHandler());\n container.bind(TOKENS.ModelsRegistry, () => modelsRegistry);\n container.bind(\n TOKENS.TokenCounter,\n () => new DefaultTokenCounter({ registry: modelsRegistry, providerId: config.provider }),\n );\n\n const modeStore = new DefaultModeStore({ directory: wpaths.configDir });\n container.bind(TOKENS.ModeStore, () => modeStore);\n container.bind(\n TOKENS.SessionStore,\n () =>\n new DefaultSessionStore({\n dir: wpaths.projectSessions,\n // Scrub secrets out of persisted user/model turns (F-06). Tool output\n // is already scrubbed by the executor.\n secretScrubber: container.resolve(TOKENS.SecretScrubber),\n }),\n );\n\n const memoryStore = new DefaultMemoryStore({ paths: wpaths });\n container.bind(TOKENS.MemoryStore, () => memoryStore);\n\n const skillLoader = new DefaultSkillLoader({ paths: wpaths, bundledDir: opts.bundledSkillsDir });\n container.bind(TOKENS.SkillLoader, () => skillLoader);\n\n if (opts.systemPrompt) {\n container.bind(\n TOKENS.SystemPromptBuilder,\n () => new DefaultSystemPromptBuilder(opts.systemPrompt as DefaultSystemPromptBuilderOptions),\n );\n }\n\n container.bind(\n TOKENS.PermissionPolicy,\n () => {\n const policyOptions: ConstructorParameters<typeof DefaultPermissionPolicy>[0] = {\n trustFile: wpaths.projectTrust,\n yolo: opts.permission?.yolo ?? false,\n yoloDestructive: opts.permission?.yoloDestructive ?? opts.permission?.forceAllYolo ?? false,\n confirmDestructive: opts.permission?.confirmDestructive ?? false,\n };\n if (opts.permission?.promptDelegate !== undefined) {\n policyOptions.promptDelegate = opts.permission.promptDelegate;\n }\n return new DefaultPermissionPolicy(policyOptions);\n },\n );\n\n container.bind(\n TOKENS.Compactor,\n () =>\n new HybridCompactor({\n preserveK: opts.compactor?.preserveK ?? 20,\n eliseThreshold: opts.compactor?.eliseThreshold ?? 0.7,\n }),\n );\n\n return container;\n}\n","import {\n type Config,\n type DefaultLogger,\n type DefaultSecretVault,\n type WstackPaths,\n bootConfig as coreBootConfig,\n} from '@wrongstack/core';\n\nexport interface BootResult {\n config: Config;\n vault: DefaultSecretVault;\n globalConfigPath: string;\n projectRoot: string;\n wpaths: WstackPaths;\n logger: InstanceType<typeof DefaultLogger>;\n}\n\n/**\n * Thin WebUI wrapper over the canonical `bootConfig` in `@wrongstack/core`\n * (mirrors packages/cli/src/boot-config.ts). All real boot behavior — wstack\n * path resolution, the AES-GCM `DefaultSecretVault`, plaintext-secret\n * migration, and config load/merge — lives in core so the WebUI server and the\n * CLI can't drift. Only the secret-migration notice label (`WebUI`) differs.\n */\nexport async function bootConfig(): Promise<BootResult> {\n const { config, vault, globalConfigPath, projectRoot, wpaths, logger } = await coreBootConfig({\n appLabel: 'WebUI',\n });\n return { config, vault, globalConfigPath, projectRoot, wpaths, logger };\n}\n\nexport function patchConfig(config: Config, updates: Partial<Config>): Config {\n return Object.freeze({ ...config, ...updates });\n}\n","import { spawnSync } from 'node:child_process';\nimport type { WebSocket } from 'ws';\nimport {\n AutoPhasePlanner,\n PhaseGraphBuilder,\n PhaseOrchestrator,\n PhaseStore,\n WorktreeManager,\n type PhaseGraph,\n type PhaseTemplate,\n} from '@wrongstack/core';\nimport type { Agent, Context, EventBus, Logger } from '@wrongstack/core';\n\nfunction isGitRepo(cwd: string): boolean {\n try {\n const r = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd, encoding: 'utf8' });\n return r.status === 0 && r.stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\ninterface WSClient {\n ws: WebSocket;\n id: string;\n}\n\ninterface AutoPhaseWSMessage {\n type: string;\n payload?: Record<string, unknown>;\n}\n\n/**\n * AutoPhaseWebSocketHandler — WebSocket üzerinden AutoPhase kontrolü.\n *\n * Mesaj tipleri:\n * autophase.start → { title, phases?, autonomous? }\n * autophase.pause → {}\n * autophase.resume → {}\n * autophase.stop → {}\n * autophase.status → {}\n * autophase.selectPhase → { phaseId }\n * autophase.taskStatus → { taskId, status }\n */\nexport class AutoPhaseWebSocketHandler {\n private orchestrator: PhaseOrchestrator | null = null;\n private graph: PhaseGraph | null = null;\n private store: PhaseStore;\n private clients = new Set<WSClient>();\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n /** Aborts in-flight task agents when the run is stopped. */\n private abort: AbortController | null = null;\n /** Optional per-phase git-worktree isolation (lazily created at start). */\n private worktrees: WorktreeManager | null = null;\n\n constructor(\n private agent: Agent,\n private context: Context,\n private logger: Logger,\n storeDir: string,\n private events?: EventBus | undefined,\n private projectRoot?: string | undefined,\n ) {\n this.store = new PhaseStore({ baseDir: storeDir });\n }\n\n addClient(ws: WebSocket): void {\n const client: WSClient = { ws, id: crypto.randomUUID() };\n this.clients.add(client);\n\n ws.on('close', () => this.clients.delete(client));\n ws.on('error', () => this.clients.delete(client));\n\n // Anlık durum gönder\n this.sendState(client);\n }\n\n async handleMessage(msg: AutoPhaseWSMessage): Promise<void> {\n switch (msg.type) {\n case 'autophase.start':\n await this.handleStart(msg.payload);\n break;\n case 'autophase.pause':\n this.orchestrator?.pause();\n this.broadcast({ type: 'autophase.paused', payload: {} });\n break;\n case 'autophase.resume':\n this.orchestrator?.resume();\n this.broadcast({ type: 'autophase.resumed', payload: {} });\n break;\n case 'autophase.stop':\n this.abort?.abort();\n this.orchestrator?.stop();\n this.stopBroadcast();\n if (this.graph) void this.store.save(this.graph);\n this.broadcast({ type: 'autophase.stopped', payload: {} });\n break;\n case 'autophase.status':\n this.broadcastState();\n break;\n case 'autophase.selectPhase': {\n const phaseId = msg.payload?.phaseId as string;\n if (phaseId && this.graph) {\n this.broadcastState(phaseId);\n }\n break;\n }\n case 'autophase.taskStatus': {\n const { taskId, status } = msg.payload as { taskId: string; status: string };\n await this.handleTaskStatusChange(taskId, status);\n break;\n }\n case 'autophase.toggleAutonomous': {\n const autonomous = (msg.payload?.autonomous as boolean) ?? !this.graph?.autonomous;\n if (this.graph) {\n this.graph.autonomous = autonomous;\n await this.store.save(this.graph);\n this.broadcast({ type: 'autophase.state', payload: this.buildState() });\n }\n break;\n }\n case 'autophase.save': {\n if (this.graph) {\n await this.store.save(this.graph);\n this.broadcast({ type: 'autophase.saved', payload: { graphId: this.graph.id } });\n }\n break;\n }\n case 'autophase.list': {\n const graphs = await this.store.list();\n this.broadcast({ type: 'autophase.list', payload: { graphs } });\n break;\n }\n case 'autophase.load': {\n const graphId = msg.payload?.graphId as string | undefined;\n if (graphId) {\n const graph = await this.store.load(graphId);\n if (graph) {\n this.graph = graph;\n this.broadcast({ type: 'autophase.state', payload: this.buildState() });\n } else {\n this.broadcast({ type: 'autophase.error', payload: { message: `Graph not found: ${graphId}` } });\n }\n }\n break;\n }\n }\n }\n\n private async handleStart(payload?: Record<string, unknown>): Promise<void> {\n const title = (payload?.goal as string) || (payload?.title as string) || 'Untitled Project';\n const autonomous = (payload?.autonomous as boolean) ?? true;\n\n // Phase plan resolution:\n // 1. explicit phases in the payload win (caller override);\n // 2. otherwise the LLM plans phases+todos for the goal;\n // 3. failing that, fall back to the generic default phases.\n const phases = Array.isArray(payload?.phases)\n ? (payload.phases as PhaseTemplate[])\n : await this.planPhases(title);\n\n this.logger.info(`[AutoPhase] Starting: ${title}`);\n\n // Build the graph up-front so we have a reference for live broadcasts and\n // persistence *before* the (long-running) build begins.\n const graph = await new PhaseGraphBuilder({ title, phases, autonomous }).build();\n this.graph = graph;\n this.abort = new AbortController();\n await this.store.save(graph);\n\n // Per-phase git-worktree isolation, when enabled and inside a git repo.\n // The shared agent/context means we can't run phases in parallel here\n // (we swap a single context.cwd per task), so phases stay sequential —\n // but each phase still commits + squash-merges back through its own\n // worktree, and the lifecycle events drive the live swim-lane/DAG view.\n if (\n !this.worktrees &&\n this.events &&\n this.projectRoot &&\n process.env['WRONGSTACK_AUTOPHASE_WORKTREES'] !== '0' &&\n isGitRepo(this.projectRoot)\n ) {\n this.worktrees = new WorktreeManager({ projectRoot: this.projectRoot, events: this.events });\n }\n\n this.orchestrator = new PhaseOrchestrator({\n graph,\n ctx: {\n executeTask: async (task, phaseId, env) => {\n this.logger.info(`[AutoPhase] [${phaseId}] Executing: ${task.title}`);\n const result = await this.executeTaskWithAgent(task, phaseId, env);\n this.logger.info(`[AutoPhase] [${phaseId}] Completed: ${task.title}`);\n return result;\n },\n onPhaseComplete: (phase) => {\n this.logger.info(`[AutoPhase] Phase completed: ${phase.name}`);\n void this.store.save(graph);\n this.broadcastState();\n },\n onPhaseFail: (phase, error) => {\n this.logger.error(`[AutoPhase] Phase failed: ${phase.name} — ${error.message}`);\n void this.store.save(graph);\n this.broadcastState();\n },\n },\n worktrees: this.worktrees ?? undefined,\n autonomous,\n // Must stay 1: phase tasks run on the single shared context whose cwd we\n // swap per phase, so parallel phases would race on context.cwd.\n maxConcurrentPhases: 1,\n // Sequential within a phase: each todo is a full-tool agent editing the\n // phase worktree, so running two at once risks concurrent writes.\n maxConcurrentTasks: 1,\n });\n\n // Start the live broadcast immediately, then run the orchestrator in the\n // background. Awaiting start() would block until the *entire* build\n // finishes — the periodic broadcast (below) reads the mutating graph, so\n // clients see live progress while it runs.\n this.startBroadcast();\n this.broadcastState();\n\n void this.orchestrator\n .start()\n .then(() => {\n this.orchestrator?.stop(); // clear the autonomous tick interval\n void this.store.save(graph);\n this.stopBroadcast();\n const failed = graph.failedPhaseIds.length > 0;\n this.broadcast(\n failed\n ? { type: 'autophase.failed', payload: { title } }\n : { type: 'autophase.completed', payload: { title } },\n );\n this.broadcastState();\n })\n .catch((err: unknown) => {\n this.logger.error(`[AutoPhase] Aborted: ${err instanceof Error ? err.message : String(err)}`);\n this.stopBroadcast();\n this.broadcast({ type: 'autophase.failed', payload: { title, error: String(err) } });\n });\n }\n\n /** Generic fallback phases when the LLM planner produces nothing usable. */\n private defaultPhases(): PhaseTemplate[] {\n return [\n { name: 'Discovery', description: 'Requirements gathering', priority: 'high', estimateHours: 2, parallelizable: false },\n { name: 'Design', description: 'Architecture and design', priority: 'critical', estimateHours: 4, parallelizable: false },\n { name: 'Implementation', description: 'Core development', priority: 'critical', estimateHours: 12, parallelizable: false },\n { name: 'Testing', description: 'Unit and integration tests', priority: 'high', estimateHours: 6, parallelizable: true },\n { name: 'Deployment', description: 'Deploy to production', priority: 'medium', estimateHours: 2, parallelizable: false },\n ];\n }\n\n /** Plan phases+todos for the goal via the LLM; fall back to defaults on failure. */\n private async planPhases(goal: string): Promise<PhaseTemplate[]> {\n try {\n const planner = new AutoPhasePlanner({\n goal,\n runOnce: async (prompt) => {\n const result = (await this.agent.run(prompt, { signal: new AbortController().signal })) as {\n status: string;\n finalText?: string | undefined;\n };\n return result.status === 'done' ? (result.finalText ?? '') : '';\n },\n });\n const { phases, parseFailed } = await planner.plan();\n if (!parseFailed && phases.length > 0) {\n const todos = phases.reduce((n, p) => n + (p.taskTemplates?.length ?? 0), 0);\n this.logger.info(`[AutoPhase] Planned ${phases.length} phases / ${todos} todos for: ${goal}`);\n return phases;\n }\n this.logger.info(`[AutoPhase] Planner produced no phases; using defaults for: ${goal}`);\n } catch (err) {\n this.logger.error(`[AutoPhase] Planning failed, using defaults: ${err instanceof Error ? err.message : String(err)}`);\n }\n return this.defaultPhases();\n }\n\n private async executeTaskWithAgent(\n task: import('@wrongstack/core').TaskNode,\n phaseId: string,\n env?: { cwd?: string | undefined; branch?: string | undefined },\n ): Promise<unknown> {\n // Task'ı agent'a çalıştır\n const prompt = `Execute task: ${task.title}\\n\\nDescription: ${task.description}\\nPhase: ${phaseId}\\nPriority: ${task.priority}\\nType: ${task.type}`;\n const signal = this.abort?.signal ?? new AbortController().signal;\n // Redirect the shared context's cwd at the phase worktree for the duration\n // of this task. Safe because phases/tasks run strictly sequentially here;\n // tools read `ctx.cwd` live, so the agent operates inside the worktree.\n const prevCwd = this.context.cwd;\n if (env?.cwd) this.context.cwd = env.cwd;\n try {\n return await this.agent.run(prompt, { signal });\n } finally {\n this.context.cwd = prevCwd;\n }\n }\n\n private async handleTaskStatusChange(taskId: string, status: string): Promise<void> {\n if (!this.graph) return;\n\n for (const phase of this.graph.phases.values()) {\n const task = phase.taskGraph.nodes.get(taskId);\n if (task) {\n task.status = status as import('@wrongstack/core').TaskStatus;\n task.updatedAt = Date.now();\n this.broadcastState();\n return;\n }\n }\n }\n\n private startBroadcast(): void {\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => {\n const progress = this.orchestrator?.getProgress();\n if (progress) this.broadcast({ type: 'autophase.progress', payload: progress });\n this.broadcastState();\n }, 2000);\n }\n\n private stopBroadcast(): void {\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcastState(activePhaseId?: string): void {\n if (!this.graph) return;\n\n const state = this.buildState(activePhaseId);\n this.broadcast({ type: 'autophase.state', payload: state });\n }\n\n private buildState(activePhaseId?: string): Record<string, unknown> {\n if (!this.graph) {\n return { phases: [], tasks: [], overallPercent: 0, autonomous: true, title: '' };\n }\n\n const phases = Array.from(this.graph.phases.values());\n const currentActiveId = activePhaseId || phases.find((p) => p.status === 'running')?.id || phases[0]?.id || '';\n const activePhase = this.graph.phases.get(currentActiveId);\n\n const totalTasks = phases.reduce((sum, p) => sum + p.taskGraph.nodes.size, 0);\n const completedTasks = phases.reduce(\n (sum, p) => sum + Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length,\n 0,\n );\n\n const phaseItems = phases.map((p) => ({\n id: p.id,\n name: p.name,\n description: p.description,\n status: p.status,\n priority: p.priority,\n estimateHours: p.estimateHours,\n actualDurationMs: p.actualDurationMs,\n startedAt: p.startedAt,\n completedAt: p.completedAt,\n progressPercent: p.taskGraph.nodes.size > 0\n ? Math.round((Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length / p.taskGraph.nodes.size) * 100)\n : 0,\n taskCount: p.taskGraph.nodes.size,\n completedTasks: Array.from(p.taskGraph.nodes.values()).filter((t) => t.status === 'completed').length,\n assignedAgents: p.assignedAgents,\n isActive: p.id === currentActiveId,\n }));\n\n const taskItems = activePhase\n ? Array.from(activePhase.taskGraph.nodes.values()).map((t) => ({\n id: t.id,\n title: t.title,\n description: t.description,\n status: t.status,\n priority: t.priority,\n type: t.type,\n estimateHours: t.estimateHours,\n actualHours: t.actualHours,\n assignee: t.assignee,\n tags: t.tags || [],\n startedAt: t.startedAt,\n completedAt: t.completedAt,\n }))\n : [];\n\n const completedPhases = phases.filter((p) => p.status === 'completed').length;\n\n return {\n title: this.graph.title,\n phases: phaseItems,\n tasks: taskItems,\n activePhaseId: currentActiveId,\n overallPercent: phases.length > 0 ? Math.round((completedPhases / phases.length) * 100) : 0,\n autonomous: this.graph.autonomous,\n totalTasks,\n completedTasks,\n };\n }\n\n private sendState(client: WSClient): void {\n if (!this.graph) return;\n const state = this.buildState();\n this.send(client, { type: 'autophase.state', payload: state });\n }\n\n private broadcast(msg: { type: string; payload: unknown }): void {\n const data = JSON.stringify(msg);\n for (const client of this.clients) {\n if (client.ws.readyState === 1) { // OPEN\n client.ws.send(data);\n }\n }\n }\n\n private send(client: WSClient, msg: { type: string; payload: unknown }): void {\n if (client.ws.readyState === 1) {\n client.ws.send(JSON.stringify(msg));\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { WebSocket } from 'ws';\nimport type { CollaborationBus, EventBus, Logger } from '@wrongstack/core';\nimport type { AnnotationsStore, SessionReader } from '@wrongstack/core/storage';\nimport type {\n CollabRole,\n WSCollabParticipantJoined,\n WSCollabParticipantLeft,\n WSCollabState,\n WSServerMessage,\n} from '../types.js';\n\n/** How many historical events to replay to a late-joining observer. */\nconst REPLAY_LIMIT = 50;\n\n/** How long the middleware waits before auto-resuming (mirrors the middleware default). */\nconst PAUSE_TIMEOUT_MS = 60_000;\n\n/**\n * CollaborationWebSocketHandler — passive read-only session observer (Phase 1\n * of idea #13 from IDEAS.md). Mirrors `WorktreeWebSocketHandler` and\n * `AutoPhaseWebSocketHandler`.\n *\n * Capabilities in this phase:\n * - A second human (or any client) joins an active agent run as an\n * `observer` and receives a live mirror of the kernel's iteration /\n * tool / subagent events.\n * - The observer declares a `sessionId` on join (used for state scoping\n * and future replay-on-join). Live event routing is session-agnostic\n * for now — see the limitation note below.\n * - The observer can leave at any time; cleanup runs on WS close/error.\n * - The observer CANNOT modify the agent's state, pause it, or inject\n * tool calls. Those capabilities land in Phase 2/3.\n *\n * Limitation (documented, acceptable for Phase 1):\n * The webui server multiplexes every active session onto a single\n * EventBus, and most event payloads (`tool.started`, `iteration.*`,\n * `subagent.*`) do NOT carry a `sessionId` field. The webui's primary\n * WS path works because it is the only consumer and assumes one\n * active session at a time. We mirror that assumption here. When a\n * future multi-session \"session router\" lands, this handler will be\n * upgraded to filter by sessionId.\n *\n * Protocol additions (see `packages/webui/src/types.ts`):\n * client → server: collab.join { sessionId, role: 'observer' }\n * collab.leave { sessionId }\n * server → client: collab.state (initial + 2s periodic)\n * collab.participant.joined\n * collab.participant.left\n * collab.event (live kernel event mirror)\n */\nexport class CollaborationWebSocketHandler {\n private readonly clients = new Set<WebSocket>();\n /** sessionId → participants currently watching it. */\n private readonly bySession = new Map<string, Set<Participant>>();\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n private readonly offs: Array<() => void> = [];\n\n constructor(\n private readonly events: EventBus,\n private readonly logger: Logger,\n /**\n * Optional reader over the on-disk session log. When provided, late\n * joiners receive the last `REPLAY_LIMIT` events of the joined\n * session before live mirroring begins. Without a reader, joining\n * is still allowed — the observer simply starts from \"now\" with no\n * historical context.\n */\n private readonly reader?: SessionReader | undefined,\n /**\n * Optional sidecar store for collaboration annotations. Required\n * for the `annotator` role — without it, `collab.annotate` messages\n * are rejected with an error.\n */\n private readonly annotations?: AnnotationsStore | undefined,\n /**\n * Optional kernel-level pause/resume bus. Required for the\n * `controller` role — without it, `collab.request_pause` is rejected\n * with an error. Wired to the agent's `toolCall` pipeline via\n * `collabPauseMiddleware` in the webui server boot.\n */\n private readonly bus?: CollaborationBus | undefined,\n ) {\n this.subscribe();\n }\n\n // ── Public API (called by server/index.ts per WS connection) ───────────\n\n addClient(ws: WebSocket): void {\n this.clients.add(ws);\n this.ensureBroadcast();\n ws.on('close', () => this.handleDisconnect(ws));\n ws.on('error', () => this.handleDisconnect(ws));\n }\n\n dispose(): void {\n for (const off of this.offs) off();\n this.offs.length = 0;\n this.stopBroadcast();\n }\n\n // ── Inbound client messages ────────────────────────────────────────────\n\n /**\n * Dispatch a parsed client message. Returns true when the message was\n * recognized and handled; false when the caller should ignore / log.\n * Phase 1 only knows `collab.join` and `collab.leave`; unknown types\n * return false so the upstream router can decide.\n */\n handleMessage(\n ws: WebSocket,\n msg: { type: string; payload?: unknown | undefined },\n ): boolean {\n if (msg.type === 'collab.join') {\n const payload = msg.payload as { sessionId?: string | undefined; role?: CollabRole | undefined } | undefined;\n if (!payload?.sessionId) {\n this.send(ws, this.errorMessage('collab.join requires sessionId'));\n return true;\n }\n // The `role` field is accepted on the wire for forward-compat;\n // 'controller' (Phase 3) is not yet wired and is rejected here.\n this.join(ws, payload.sessionId, payload.role ?? 'observer');\n return true;\n }\n if (msg.type === 'collab.leave') {\n this.leave(ws);\n return true;\n }\n if (msg.type === 'collab.annotate') {\n void this.handleAnnotate(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.resolve') {\n void this.handleResolve(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.request_pause') {\n void this.handleRequestPause(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.resume') {\n void this.handleResume(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.grant_control') {\n void this.handleGrantControl(ws, msg.payload);\n return true;\n }\n if (msg.type === 'collab.inject_tool') {\n void this.handleInjectTool(ws, msg.payload);\n return true;\n }\n return false;\n }\n\n // ── Join / leave flow ──────────────────────────────────────────────────\n\n private join(ws: WebSocket, sessionId: string, role: CollabRole): void {\n if (role === 'controller' && !this.bus) {\n this.send(\n ws,\n this.errorMessage(\n `role 'controller' is not available: server has no CollaborationBus`,\n ),\n );\n return;\n }\n if (role === 'annotator' && !this.annotations) {\n this.send(\n ws,\n this.errorMessage(\n `role 'annotator' is not available: server has no annotations store`,\n ),\n );\n return;\n }\n const participant: Participant = {\n participantId: randomUUID(),\n ws,\n sessionId,\n role,\n joinedAt: new Date().toISOString(),\n };\n let bucket = this.bySession.get(sessionId);\n if (!bucket) {\n bucket = new Set();\n this.bySession.set(sessionId, bucket);\n }\n bucket.add(participant);\n\n // Per-participant hello: send the current state snapshot immediately\n // so the new observer knows who else is watching. Then broadcast the\n // join event AND a fresh state to every participant (including the\n // newcomer) so existing observers see the updated count without\n // waiting for the 2s timer.\n this.send(ws, this.stateMessage(sessionId));\n this.broadcast(sessionId, {\n type: 'collab.participant.joined',\n payload: {\n participantId: participant.participantId,\n sessionId,\n role,\n joinedAt: participant.joinedAt,\n },\n });\n this.broadcast(sessionId, this.stateMessage(sessionId));\n\n // Replay last N events to give the late joiner historical context.\n // Best-effort: failures are logged and silently ignored — the live\n // mirror continues regardless.\n if (this.reader) {\n this.replayHistory(ws, sessionId).catch((err) => {\n this.logger.debug?.(\n `collab: replay failed for ${sessionId}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n }\n this.logger.debug?.(\n `collab: participant ${participant.participantId} joined ${sessionId}`,\n );\n }\n\n private leave(ws: WebSocket): void {\n this.handleDisconnect(ws);\n }\n\n private handleDisconnect(ws: WebSocket): void {\n this.clients.delete(ws);\n // Remove from every session bucket the WS may have joined (a single\n // WS is in at most one bucket in Phase 1, but the loop is cheap and\n // future-proofs multi-session observers).\n //\n // Order matters:\n // 1. Send `participant.left` to the leaving ws so they get a\n // confirmation that their leave registered.\n // 2. Delete from bucket.\n // 3. Broadcast the fresh state to remaining observers so they\n // see the updated count without waiting for the 2s timer.\n for (const [sessionId, bucket] of this.bySession) {\n for (const p of bucket) {\n if (p.ws === ws) {\n const leftEvent = {\n type: 'collab.participant.left' as const,\n payload: { participantId: p.participantId, sessionId },\n };\n // Send directly to the leaving ws first so they get an\n // immediate confirmation, then broadcast to the rest of the\n // bucket (which is still inclusive of the leaving ws here —\n // the per-iteration below strips it out).\n this.send(ws, leftEvent);\n bucket.delete(p);\n if (bucket.size === 0) {\n this.bySession.delete(sessionId);\n } else {\n this.broadcast(sessionId, leftEvent);\n this.broadcast(sessionId, this.stateMessage(sessionId));\n }\n break;\n }\n }\n }\n if (this.bySession.size === 0) this.stopBroadcast();\n }\n\n // ── Annotation flow (Phase 2) ───────────────────────────────────────────\n\n /**\n * Look up the participant record for a given WS across all sessions.\n * Returns null when the WS hasn't joined (e.g. the client sent a\n * `collab.annotate` before `collab.join`).\n */\n private findParticipant(ws: WebSocket): Participant | null {\n for (const bucket of this.bySession.values()) {\n for (const p of bucket) {\n if (p.ws === ws) return p;\n }\n }\n return null;\n }\n\n private async handleAnnotate(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.annotations) {\n this.send(ws, this.errorMessage('annotations store is not configured'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('annotate requires an active join'));\n return;\n }\n if (participant.role !== 'annotator') {\n this.send(\n ws,\n this.errorMessage(\n `annotate requires the 'annotator' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | { sessionId?: string | undefined; atEventIndex?: number | undefined; text?: string | undefined }\n | undefined;\n if (\n !payload?.sessionId ||\n typeof payload.atEventIndex !== 'number' ||\n typeof payload.text !== 'string'\n ) {\n this.send(\n ws,\n this.errorMessage('annotate requires { sessionId, atEventIndex, text }'),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `annotate sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n try {\n const annotation = await this.annotations.add({\n sessionId: payload.sessionId,\n atEventIndex: payload.atEventIndex,\n authorId: participant.participantId,\n text: payload.text,\n });\n this.broadcast(payload.sessionId, {\n type: 'collab.annotation.added',\n payload: {\n sessionId: payload.sessionId,\n annotation: {\n id: annotation.id,\n atEventIndex: annotation.atEventIndex,\n authorId: annotation.authorId,\n authorRole: annotation.authorRole,\n text: annotation.text,\n createdAt: annotation.createdAt,\n resolved: annotation.resolved,\n },\n },\n });\n } catch (err) {\n this.send(\n ws,\n this.errorMessage(\n `annotation rejected: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n );\n }\n }\n\n private async handleResolve(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.annotations) {\n this.send(ws, this.errorMessage('annotations store is not configured'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('resolve requires an active join'));\n return;\n }\n if (participant.role !== 'annotator') {\n this.send(\n ws,\n this.errorMessage(\n `resolve requires the 'annotator' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | { sessionId?: string | undefined; annotationId?: string | undefined }\n | undefined;\n if (!payload?.sessionId || !payload.annotationId) {\n this.send(\n ws,\n this.errorMessage('resolve requires { sessionId, annotationId }'),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `resolve sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n try {\n const updated = await this.annotations.resolve({\n sessionId: payload.sessionId,\n annotationId: payload.annotationId,\n resolvedBy: participant.participantId,\n });\n if (!updated) {\n this.send(\n ws,\n this.errorMessage(`annotation not found: ${payload.annotationId}`),\n );\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.annotation.resolved',\n payload: {\n sessionId: payload.sessionId,\n annotationId: updated.id,\n resolvedBy: updated.resolvedBy ?? participant.participantId,\n resolvedAt: updated.resolvedAt ?? new Date().toISOString(),\n },\n });\n } catch (err) {\n this.send(\n ws,\n this.errorMessage(\n `resolve failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n );\n }\n }\n\n // ── Event subscription (live mirror) ───────────────────────────────────\n\n private subscribe(): void {\n // Same trick as WorktreeWebSocketHandler: bind a single typed-on helper\n // to a string-keyed signature so we can register many handlers.\n const on = this.events.on.bind(this.events) as unknown as (\n ev: string,\n fn: (p: unknown) => void,\n ) => () => void;\n\n // Mirror every event an observer would care about. Each is forwarded\n // to all joined participants as a generic `collab.event` envelope so\n // the client can render a flowing activity strip. Filtering /\n // denormalization happens on the client.\n const forwarded: Array<[string, string]> = [\n ['iteration.started', 'iteration.started'],\n ['iteration.completed', 'iteration.completed'],\n ['tool.started', 'tool.started'],\n ['tool.progress', 'tool.progress'],\n ['tool.executed', 'tool.executed'],\n ['tool.confirm_needed', 'tool.confirm_needed'],\n ['subagent.spawned', 'subagent.spawned'],\n ['subagent.task_started', 'subagent.task_started'],\n ['subagent.iteration_summary', 'subagent.iteration_summary'],\n ['subagent.task_completed', 'subagent.task_completed'],\n ['subagent.done', 'subagent.done'],\n ];\n for (const [kernelEvent, kind] of forwarded) {\n this.offs.push(\n on(kernelEvent, (raw) => {\n // Best-effort payload shape: we don't deeply validate, but we\n // make sure it's serializable. Observers must never receive\n // non-serializable objects (Functions, circular refs).\n let payload: unknown = raw;\n try {\n payload = JSON.parse(JSON.stringify(raw));\n } catch {\n // Skip unserializable payloads — better to drop than to crash\n // the broadcast loop.\n return;\n }\n this.broadcastEvent(kind, payload);\n }),\n );\n }\n }\n\n private broadcastEvent(kind: string, payload: unknown): void {\n if (this.bySession.size === 0) return; // nobody watching — no-op\n const msg: WSServerMessage = {\n type: 'collab.event',\n payload: { kind, payload, at: new Date().toISOString() },\n };\n const data = JSON.stringify(msg);\n for (const bucket of this.bySession.values()) {\n for (const p of bucket) {\n try {\n if (p.ws.readyState === 1) p.ws.send(data);\n } catch (err) {\n this.logger.debug?.(\n `collab broadcast failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n }\n\n /**\n * Replay the last `REPLAY_LIMIT` events from the on-disk session log\n * to a single observer (the late joiner). Each event is forwarded as\n * a `collab.event` with `replay: true` so the client can distinguish\n * history from the live stream.\n *\n * The session log stores typed `SessionEvent`s (`user_input`,\n * `llm_response`, `tool_result`, etc.) — different from the kernel's\n * bus events. We translate the most useful subset (`tool.*` and\n * `iteration.*`-shaped ones) into the same `kind` namespace the live\n * mirror uses, so the client can render a single activity strip.\n */\n private async replayHistory(ws: WebSocket, sessionId: string): Promise<void> {\n if (!this.reader) return;\n const all: unknown[] = [];\n try {\n for await (const ev of this.reader.replay(sessionId)) {\n all.push(ev);\n }\n } catch (err) {\n this.logger.debug?.(\n `collab: session reader rejected ${sessionId}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n return;\n }\n const tail = all.slice(-REPLAY_LIMIT);\n if (tail.length === 0) return; // nothing to replay\n for (const raw of tail) {\n const ev = raw as { type?: string | undefined; ts?: string | undefined; [k: string]: unknown };\n const kind = this.historyEventToKind(ev);\n if (!kind) continue; // skip events we don't know how to mirror\n this.send(ws, {\n type: 'collab.event',\n payload: {\n kind,\n payload: ev,\n at: ev.ts ?? new Date().toISOString(),\n replay: true,\n },\n });\n }\n }\n\n /**\n * Map a stored `SessionEvent` to a `collab.event.kind` so the live\n * strip and the history strip can share a single rendering path.\n * Returns null for events that don't have a meaningful live analog\n * (e.g. `session_start`, file-snapshot bookkeeping, rewind markers).\n */\n private historyEventToKind(ev: { type?: string | undefined }): string | null {\n switch (ev.type) {\n case 'user_input':\n return 'user_input';\n case 'llm_response':\n return 'llm_response';\n case 'tool_result':\n return 'tool.executed';\n case 'compaction':\n return 'compaction';\n case 'error':\n return 'error';\n default:\n return null;\n }\n }\n\n // ── State snapshot + periodic broadcast ────────────────────────────────\n\n private stateMessage(sessionId: string): WSCollabState {\n const bucket = this.bySession.get(sessionId);\n return {\n type: 'collab.state',\n payload: {\n sessionId,\n participants: bucket\n ? [...bucket].map((p) => ({\n participantId: p.participantId,\n role: p.role,\n joinedAt: p.joinedAt,\n }))\n : [],\n },\n };\n }\n\n private ensureBroadcast(): void {\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => {\n for (const sessionId of this.bySession.keys()) {\n this.broadcast(sessionId, this.stateMessage(sessionId));\n }\n }, 2000);\n }\n\n private stopBroadcast(): void {\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcast(sessionId: string, msg: WSServerMessage): void {\n const data = JSON.stringify(msg);\n const bucket = this.bySession.get(sessionId);\n if (!bucket) return;\n for (const p of bucket) {\n try {\n if (p.ws.readyState === 1) p.ws.send(data);\n } catch (err) {\n this.logger.debug?.(\n `collab broadcast failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n\n private send(ws: WebSocket, msg: WSServerMessage): void {\n try {\n if (ws.readyState === 1) ws.send(JSON.stringify(msg));\n } catch {\n /* client gone */\n }\n }\n\n private errorMessage(detail: string): WSServerMessage {\n return { type: 'error', payload: { phase: 'collab', message: detail } };\n }\n\n // ── Controller flow (Phase 3) ───────────────────────────────────────────\n\n private async handleRequestPause(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('pause requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('pause requires an active join'));\n return;\n }\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `pause requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as { sessionId?: string | undefined } | undefined;\n if (!payload?.sessionId || payload.sessionId !== participant.sessionId) {\n this.send(ws, this.errorMessage('pause sessionId mismatch'));\n return;\n }\n const transitioned = this.bus.requestPause(participant.participantId);\n if (!transitioned) {\n // Already paused — surface the current state to the requester.\n const s = this.bus.getState();\n this.send(ws, {\n type: 'error',\n payload: {\n phase: 'collab',\n message: `bus already paused by ${s.pausedBy ?? '?'} at ${s.pausedAt ?? '?'}`,\n },\n });\n return;\n }\n const s = this.bus.getState();\n this.broadcast(payload.sessionId, {\n type: 'collab.pause.granted',\n payload: {\n sessionId: payload.sessionId,\n pausedBy: s.pausedBy ?? participant.participantId,\n pausedAt: s.pausedAt ?? new Date().toISOString(),\n autoResumeInMs: PAUSE_TIMEOUT_MS,\n },\n });\n }\n\n private async handleResume(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('resume requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('resume requires an active join'));\n return;\n }\n // Permission: controller OR the original pauser. We do a simple\n // \"any controller can release\" check — fine for Phase 3, can be\n // tightened to \"only the pauser\" later.\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `resume requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as { sessionId?: string | undefined } | undefined;\n if (!payload?.sessionId || payload.sessionId !== participant.sessionId) {\n this.send(ws, this.errorMessage('resume sessionId mismatch'));\n return;\n }\n const transitioned = this.bus.resume();\n if (!transitioned) {\n this.send(ws, this.errorMessage('bus is not currently paused'));\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.pause.released',\n payload: {\n sessionId: payload.sessionId,\n reason: 'controller',\n at: new Date().toISOString(),\n },\n });\n }\n\n private async handleGrantControl(ws: WebSocket, raw: unknown): Promise<void> {\n // Phase 3 metadata-only: record the grant in the log; the\n // existing controller's effective permissions do not change.\n // A future iteration can wire this to a per-participant RBAC\n // table that the `handleRequestPause`/`handleResume` checks read.\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('grant_control requires an active join'));\n return;\n }\n const payload = raw as\n | { sessionId?: string | undefined; toParticipant?: string | undefined }\n | undefined;\n if (\n !payload?.sessionId ||\n !payload.toParticipant ||\n payload.sessionId !== participant.sessionId\n ) {\n this.send(ws, this.errorMessage('grant_control requires { sessionId, toParticipant }'));\n return;\n }\n this.logger.debug?.(\n `collab: control granted from ${participant.participantId} to ${payload.toParticipant} in ${payload.sessionId}`,\n );\n }\n\n /**\n * Phase 4 — handle a controller's manual tool-call injection.\n * Validates the payload, queues it on the bus, and broadcasts\n * the grant so observers see what just happened. The actual\n * splice into the agent's pipeline is performed by the\n * `collabInjectMiddleware` on the next tool call.\n */\n private async handleInjectTool(ws: WebSocket, raw: unknown): Promise<void> {\n if (!this.bus) {\n this.send(ws, this.errorMessage('inject_tool requires a CollaborationBus'));\n return;\n }\n const participant = this.findParticipant(ws);\n if (!participant) {\n this.send(ws, this.errorMessage('inject_tool requires an active join'));\n return;\n }\n if (participant.role !== 'controller') {\n this.send(\n ws,\n this.errorMessage(\n `inject_tool requires the 'controller' role (current: '${participant.role}')`,\n ),\n );\n return;\n }\n const payload = raw as\n | {\n sessionId?: string | undefined;\n toolUseId?: string | undefined;\n content?: unknown | undefined;\n isError?: boolean | undefined;\n reason?: string | undefined;\n }\n | undefined;\n if (\n !payload?.sessionId ||\n !payload.toolUseId ||\n typeof payload.isError !== 'boolean' ||\n typeof payload.reason !== 'string' ||\n payload.content === undefined\n ) {\n this.send(\n ws,\n this.errorMessage(\n 'inject_tool requires { sessionId, toolUseId, content, isError, reason }',\n ),\n );\n return;\n }\n if (payload.sessionId !== participant.sessionId) {\n this.send(\n ws,\n this.errorMessage(\n `inject_tool sessionId mismatch (joined: ${participant.sessionId})`,\n ),\n );\n return;\n }\n const queued = this.bus.injectToolResult({\n toolUseId: payload.toolUseId,\n content: payload.content,\n isError: payload.isError,\n reason: payload.reason,\n authorId: participant.participantId,\n });\n if (!queued) {\n this.send(\n ws,\n this.errorMessage(\n `an injection for toolUseId ${payload.toolUseId} is already queued`,\n ),\n );\n return;\n }\n this.broadcast(payload.sessionId, {\n type: 'collab.injection.granted',\n payload: {\n sessionId: payload.sessionId,\n toolUseId: payload.toolUseId,\n // The tool name is unknown here (the injection is queued\n // before the model produces the tool call). We surface a\n // placeholder; the middleware will emit a `consumed` event\n // with the real name on match.\n toolName: '(pending match)',\n authorId: participant.participantId,\n reason: payload.reason,\n isError: payload.isError,\n phase: 'queued',\n at: new Date().toISOString(),\n },\n });\n }\n}\n\ninterface Participant {\n participantId: string;\n ws: WebSocket;\n sessionId: string;\n role: CollabRole;\n joinedAt: string;\n}\n","import type { WebSocket } from 'ws';\nimport type { EventBus, Logger } from '@wrongstack/core';\nimport type { WorktreeHandleView, WSServerMessage } from '../types.js';\n\nconst MAX_ACTIVITY = 6;\n\n/**\n * WorktreeWebSocketHandler — mirrors AutoPhaseWebSocketHandler. Subscribes to\n * the shared EventBus `worktree.*` lifecycle events, keeps a live snapshot of\n * every worktree, and broadcasts:\n * - `worktree.event` incrementally (drives the flowing activity strip)\n * - `worktree.state` on connect + on a 2s timer (drives swim-lanes/DAG)\n */\nexport class WorktreeWebSocketHandler {\n private readonly clients = new Set<WebSocket>();\n private readonly handles = new Map<string, WorktreeHandleView>();\n private baseBranch = '';\n private broadcastInterval: ReturnType<typeof setInterval> | null = null;\n private readonly offs: Array<() => void> = [];\n\n constructor(\n private readonly events: EventBus,\n private readonly logger: Logger,\n ) {\n this.subscribe();\n }\n\n addClient(ws: WebSocket): void {\n this.clients.add(ws);\n ws.on('close', () => this.clients.delete(ws));\n ws.on('error', () => this.clients.delete(ws));\n this.send(ws, this.stateMessage());\n }\n\n dispose(): void {\n for (const off of this.offs) off();\n this.offs.length = 0;\n this.stopBroadcast();\n }\n\n // ── internals ───────────────────────────────────────────────────────────\n\n private subscribe(): void {\n const on = this.events.on.bind(this.events) as unknown as (\n ev: string,\n fn: (p: unknown) => void,\n ) => () => void;\n\n this.offs.push(\n on('worktree.allocated', (p) => {\n const e = p as { handleId: string; ownerId: string; ownerLabel: string; branch: string; baseBranch: string };\n this.baseBranch = e.baseBranch || this.baseBranch;\n this.upsert(e.handleId, {\n handleId: e.handleId,\n ownerId: e.ownerId,\n ownerLabel: e.ownerLabel,\n branch: e.branch,\n baseBranch: e.baseBranch,\n status: 'active',\n insertions: 0,\n deletions: 0,\n files: 0,\n allocatedAt: Date.now(),\n lastEventAt: Date.now(),\n recentActivity: [],\n });\n this.activity(e.handleId, 'allocated', `branch ${e.branch}`);\n this.ensureBroadcast();\n }),\n on('worktree.committed', (p) => {\n const e = p as { handleId: string; insertions: number; deletions: number; files: number; committed: boolean };\n this.patch(e.handleId, { status: 'committing', insertions: e.insertions, deletions: e.deletions, files: e.files });\n if (e.committed) this.activity(e.handleId, 'committed', `+${e.insertions}/-${e.deletions} (${e.files}f)`);\n this.broadcastState();\n }),\n on('worktree.merged', (p) => {\n const e = p as { handleId: string; baseBranch: string };\n this.patch(e.handleId, { status: 'merged' });\n this.activity(e.handleId, 'merged', `→ ${e.baseBranch}`);\n this.broadcastState();\n }),\n on('worktree.conflict', (p) => {\n const e = p as { handleId: string; conflictFiles: string[] };\n this.patch(e.handleId, { status: 'needs-review', conflictFiles: e.conflictFiles });\n this.activity(e.handleId, 'conflict', e.conflictFiles.join(', '));\n this.broadcastState();\n }),\n on('worktree.failed', (p) => {\n const e = p as { handleId: string; error: string };\n this.patch(e.handleId, { status: 'failed' });\n this.activity(e.handleId, 'failed', e.error);\n this.broadcastState();\n }),\n on('worktree.released', (p) => {\n const e = p as { handleId: string; kept: boolean };\n if (!e.kept) this.handles.delete(e.handleId);\n this.activity(e.handleId, 'released', e.kept ? 'kept for review' : 'removed');\n if (this.handles.size === 0) this.stopBroadcast();\n else this.broadcastState();\n }),\n );\n }\n\n private upsert(id: string, view: WorktreeHandleView): void {\n this.handles.set(id, view);\n }\n\n private patch(id: string, patch: Partial<WorktreeHandleView>): void {\n const cur = this.handles.get(id);\n if (!cur) return;\n this.handles.set(id, { ...cur, ...patch, lastEventAt: Date.now() });\n }\n\n private activity(id: string, kind: string, text: string): void {\n const cur = this.handles.get(id);\n if (cur) {\n const recentActivity = [...cur.recentActivity, { kind, text, at: Date.now() }].slice(-MAX_ACTIVITY);\n this.handles.set(id, { ...cur, recentActivity });\n }\n this.broadcast({ type: 'worktree.event', payload: { kind, handleId: id, text, at: Date.now() } });\n }\n\n private stateMessage(): WSServerMessage {\n return {\n type: 'worktree.state',\n payload: { worktrees: [...this.handles.values()], baseBranch: this.baseBranch },\n };\n }\n\n private broadcastState(): void {\n this.broadcast(this.stateMessage());\n }\n\n private ensureBroadcast(): void {\n this.broadcast(this.stateMessage());\n if (this.broadcastInterval) return;\n this.broadcastInterval = setInterval(() => this.broadcast(this.stateMessage()), 2000);\n }\n\n private stopBroadcast(): void {\n this.broadcast(this.stateMessage());\n if (this.broadcastInterval) {\n clearInterval(this.broadcastInterval);\n this.broadcastInterval = null;\n }\n }\n\n private broadcast(msg: WSServerMessage): void {\n const data = JSON.stringify(msg);\n for (const ws of this.clients) {\n try {\n if (ws.readyState === 1) ws.send(data);\n } catch (err) {\n this.logger.debug?.(`worktree broadcast failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n }\n\n private send(ws: WebSocket, msg: WSServerMessage): void {\n try {\n if (ws.readyState === 1) ws.send(JSON.stringify(msg));\n } catch {\n /* client gone */\n }\n }\n}\n","/**\n * WebSocket connection authentication for the WebUI server.\n *\n * Three layered defenses, all enforced in {@link verifyClient}:\n * 1. **DNS-rebinding guard** ({@link hostHeaderOk}) — on a loopback bind the\n * `Host` header must itself be a loopback name, so a rebound attacker page\n * (`Host: evil.com`) is rejected even though its TCP peer is 127.0.0.1.\n * 2. **Shared-token auth** ({@link tokenMatches}, constant-time) — required for\n * any non-loopback origin and for non-browser clients reaching a publicly\n * bound socket.\n * 3. **Loopback bootstrap** — same-machine browser origins are allowed without\n * a token (the token is delivered in `session.start` and replayed on\n * reconnect); the Host-header guard above already blocks cross-site pages.\n *\n * Extracted from `index.ts` as pure functions so the auth contract can be unit\n * tested without standing up a real `http.Server`/`WebSocketServer`. `index.ts`\n * builds a thin closure that pulls the fields below off the incoming request.\n */\nimport { Buffer } from 'node:buffer';\nimport { timingSafeEqual } from 'node:crypto';\n\n/** A hostname that refers to the local machine. */\nexport function isLoopbackHostname(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '[::1]'\n );\n}\n\n/** True when the server is bound to a loopback interface (vs. LAN/0.0.0.0). */\nexport function isLoopbackBind(wsHost: string): boolean {\n return wsHost === '127.0.0.1' || wsHost === '::1' || wsHost === 'localhost';\n}\n\n/**\n * Constant-time comparison of a provided token against the expected one.\n * A length mismatch short-circuits (lengths aren't secret); equal-length\n * inputs are compared with `timingSafeEqual` so the token can't be recovered\n * byte-by-byte via response timing.\n */\nexport function tokenMatches(provided: string | undefined, expected: string): boolean {\n if (!provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(expected);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\n/** Pull the `token` query param out of a request URL (`/?token=…`). */\nexport function extractToken(url: string): string | undefined {\n const match = url.match(/[?&]token=([^&]+)/);\n return match ? match[1] : undefined;\n}\n\n/**\n * DNS-rebinding defense. On a loopback bind, the `Host` header must resolve to\n * a loopback name. When the operator deliberately exposes the socket (wsHost is\n * a LAN/0.0.0.0 address) the Host is legitimately non-loopback, so the guard is\n * skipped and connection auth falls to the token check.\n */\nexport function hostHeaderOk(input: { hostHeader: string | undefined; wsHost: string }): boolean {\n if (!isLoopbackBind(input.wsHost)) return true; // operator opted into wider exposure\n const hostHeader = (input.hostHeader ?? '').trim();\n if (!hostHeader) return false;\n // Strip the port (handle bare host, host:port, and [::1]:port).\n let hostname: string;\n try {\n hostname = new URL(`http://${hostHeader}`).hostname;\n } catch {\n return false;\n }\n return isLoopbackHostname(hostname);\n}\n\nexport interface VerifyClientInput {\n /** Browser `Origin` header, or undefined for non-browser clients. */\n origin?: string | undefined;\n /** Request URL (`req.url`) — carries the `?token=…` query param. */\n url: string;\n /** `Host` header (`req.headers.host`). */\n hostHeader?: string | undefined;\n /** Peer address (`req.socket.remoteAddress`). */\n remoteAddress?: string | undefined;\n /** Host/interface the WS server is bound to. */\n wsHost: string;\n /** The server's generated auth token. */\n expectedToken: string;\n}\n\n/**\n * Decide whether to accept an incoming WebSocket handshake. Pure mirror of the\n * closure previously inlined in `index.ts`; see the module doc for the layered\n * policy. Returns `true` to accept, `false` to reject.\n */\nexport function verifyClient(input: VerifyClientInput): boolean {\n const { origin, url, hostHeader, remoteAddress, wsHost, expectedToken } = input;\n const tokenOk = tokenMatches(extractToken(url ?? ''), expectedToken);\n\n // DNS-rebinding guard runs first on a loopback bind — independent of token\n // and Origin. Blocks a rebound attacker page (Host = attacker domain) even\n // though the TCP peer is 127.0.0.1.\n if (!hostHeaderOk({ hostHeader, wsHost })) return false;\n\n if (!origin) {\n // Non-browser clients (curl, scripts): require token unless on loopback.\n // When wsHost=0.0.0.0 the server accepts connections from any network\n // interface — a non-loopback peer is denied outright.\n const remoteIp = remoteAddress ?? '';\n const isRemoteLoopback = remoteIp === '127.0.0.1' || remoteIp === '::1';\n if (!isRemoteLoopback && wsHost === '0.0.0.0') return false; // LAN exposure = deny\n return tokenOk || isLoopbackBind(wsHost);\n }\n try {\n const { hostname } = new URL(origin);\n // Loopback browser origins: allow without token (bootstrap). The Host-header\n // guard above already rejects cross-site/rebinding pages here.\n if (isLoopbackHostname(hostname)) return true;\n // Non-loopback origins: token is mandatory.\n return tokenOk;\n } catch {\n return false;\n }\n}\n","/**\n * Process lifecycle for the WebUI server: graceful shutdown and the\n * SIGINT/SIGTERM wiring that triggers it.\n *\n * On a termination signal we (best-effort) flush + close the active session,\n * close every connected WebSocket, stop the HTTP and WS servers, then exit.\n * A re-entrancy guard makes a second signal during shutdown a no-op (rapid\n * double Ctrl+C no longer runs the teardown twice).\n *\n * Extracted from `index.ts` as a parameterized factory so the teardown\n * sequence can be unit tested without a real process signal, server, or\n * `process.exit` — `log` and `exit` are injectable seams.\n */\n\nexport interface LifecycleResources {\n /** Persist + close the active session (best-effort; errors are logged). */\n flushSession: () => Promise<void>;\n /**\n * Returns the currently-connected client sockets to close. A thunk (not a\n * snapshot) so shutdown closes whoever is connected *at signal time*, not\n * whoever was connected when the handler was registered.\n */\n clients: () => Iterable<{ close: () => void }>;\n /** Servers to stop (HTTP + WS). `null`/`undefined` entries are skipped. */\n servers: Array<{ close: () => void } | null | undefined>;\n /**\n * Optional best-effort cleanup run after the session flush and before exit\n * (e.g. removing this process from the running-instance registry). Errors are\n * logged, never thrown — cleanup must not block a clean shutdown.\n */\n onShutdown?: (() => Promise<void> | void) | undefined;\n /** Output sink. Defaults to `console.log`. */\n log?: ((msg: string) => void) | undefined;\n /** Process exit. Defaults to `process.exit`. Injectable for tests. */\n exit?: ((code: number) => void) | undefined;\n}\n\n/**\n * Build the graceful-shutdown handler. Returns an idempotent async function:\n * the first call runs the teardown, subsequent calls (e.g. a second SIGINT)\n * return immediately.\n */\nexport function createShutdown(res: LifecycleResources): () => Promise<void> {\n const log = res.log ?? ((m: string) => console.log(m));\n const exit = res.exit ?? ((code: number) => process.exit(code));\n let shuttingDown = false;\n\n return async () => {\n if (shuttingDown) return; // a second signal during teardown is a no-op\n shuttingDown = true;\n\n log('[WebUI] Shutting down...');\n try {\n await res.flushSession();\n } catch (e) {\n log(`[WebUI] Error closing session: ${e instanceof Error ? e.message : String(e)}`);\n }\n for (const ws of res.clients()) ws.close();\n for (const server of res.servers) server?.close();\n if (res.onShutdown) {\n try {\n await res.onShutdown();\n } catch (e) {\n log(`[WebUI] Error during shutdown cleanup: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n exit(0);\n };\n}\n\n/**\n * Register the shutdown handler on SIGINT and SIGTERM. Returns an unregister\n * function that detaches both listeners (useful for tests and clean restarts).\n */\nexport function registerShutdownHandlers(res: LifecycleResources): () => void {\n const shutdown = createShutdown(res);\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n return () => {\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n };\n}\n","/**\n * Running-instance registry for the standalone WebUI server.\n *\n * Every live `webui` process records itself in a single JSON file under the\n * wstack home dir (`~/.wrongstack/webui-instances.json`) so a user running\n * several instances (one per project, or several per project on different\n * ports) can see at a glance which ports are open for which path.\n *\n * Design notes:\n * - **Self-healing**: every register/unregister/list prunes entries whose PID\n * is no longer alive (`process.kill(pid, 0)`), so a crashed instance that\n * never got to unregister doesn't leave a ghost behind.\n * - **Atomic writes**: the file is rewritten via `atomicWrite` (tmp + rename),\n * so a concurrent reader never sees a half-written file. Two instances\n * starting at the *exact* same millisecond could still race the\n * read-modify-write — acceptable for a best-effort tracking file, and the\n * next register() heals any dropped entry.\n * - **Best-effort**: a failure to read/write the registry must NEVER take the\n * server down. Callers wrap these in `.catch()`.\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as fs from 'node:fs/promises';\nimport { atomicWrite } from '@wrongstack/core';\n\n/** One running WebUI process. */\nexport interface WebUIInstanceRecord {\n /** OS process id — also the liveness key. */\n pid: number;\n /** HTTP port serving the React frontend. */\n httpPort: number;\n /** WebSocket port for the agent backend. */\n wsPort: number;\n /** Bind host (e.g. 127.0.0.1 or 0.0.0.0). */\n host: string;\n /** Absolute project root the instance booted against. */\n projectRoot: string;\n /** Display name (basename of projectRoot). */\n projectName: string;\n /** ISO timestamp when the instance registered. */\n startedAt: string;\n /** Convenience open-in-browser URL. */\n url: string;\n}\n\ninterface RegistryFile {\n version: 1;\n instances: WebUIInstanceRecord[];\n}\n\n/** Default wstack home dir (`~/.wrongstack`). Callers may override the base. */\nexport function defaultBaseDir(): string {\n return path.join(os.homedir(), '.wrongstack');\n}\n\n/** Resolve the registry file path for a given base dir. */\nexport function registryPath(baseDir: string = defaultBaseDir()): string {\n return path.join(baseDir, 'webui-instances.json');\n}\n\n/**\n * Liveness probe. `process.kill(pid, 0)` sends no signal — it only checks the\n * process exists. ESRCH ⇒ dead; EPERM ⇒ alive but owned by another user (still\n * counts as alive). Any other error is treated conservatively as \"alive\" so we\n * never prune an instance we simply failed to probe.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\nasync function load(file: string): Promise<RegistryFile> {\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as RegistryFile;\n if (parsed?.version === 1 && Array.isArray(parsed.instances)) {\n return parsed;\n }\n } catch {\n // Missing or corrupt → start fresh.\n }\n return { version: 1, instances: [] };\n}\n\nasync function save(file: string, instances: WebUIInstanceRecord[]): Promise<void> {\n await atomicWrite(file, `${JSON.stringify({ version: 1, instances }, null, 2)}\\n`, {\n mode: 0o600,\n });\n}\n\n/** Drop dead processes and (optionally) one specific pid. */\nfunction prune(instances: WebUIInstanceRecord[], excludePid?: number): WebUIInstanceRecord[] {\n return instances.filter((i) => i.pid !== excludePid && isPidAlive(i.pid));\n}\n\n/**\n * Register (or refresh) this instance. Prunes dead entries and any stale entry\n * for our own PID before adding the current record. Best-effort — rejects only\n * on a hard fs error, which callers swallow.\n */\nexport async function registerInstance(\n record: WebUIInstanceRecord,\n baseDir: string = defaultBaseDir(),\n): Promise<void> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const instances = prune(data.instances, record.pid);\n instances.push(record);\n await save(file, instances);\n}\n\n/** Remove this instance (called on graceful shutdown). Also prunes dead pids. */\nexport async function unregisterInstance(\n pid: number,\n baseDir: string = defaultBaseDir(),\n): Promise<void> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const instances = prune(data.instances, pid);\n await save(file, instances);\n}\n\n/** List live instances, pruning any dead entries encountered. */\nexport async function listInstances(\n baseDir: string = defaultBaseDir(),\n): Promise<WebUIInstanceRecord[]> {\n const file = registryPath(baseDir);\n const data = await load(file);\n const live = prune(data.instances);\n // Persist the pruned view so `cat`-ing the file also shows reality, but never\n // fail the list on a write error.\n if (live.length !== data.instances.length) {\n await save(file, live).catch(() => {});\n }\n return live;\n}\n\n/** Human-readable table of running instances for `webui --list`. */\nexport function formatInstances(instances: WebUIInstanceRecord[]): string {\n if (instances.length === 0) {\n return 'No WebUI instances are currently running.';\n }\n const lines = [`Running WebUI instances (${instances.length}):`, ''];\n for (const i of instances) {\n lines.push(\n ` • ${i.url} · ws:${i.wsPort} · pid ${i.pid}`,\n ` project: ${i.projectName} (${i.projectRoot})`,\n ` since: ${i.startedAt}`,\n );\n }\n return lines.join('\\n');\n}\n","/**\n * Free-port discovery for the standalone WebUI server.\n *\n * When a user runs several instances, the default ports (HTTP 3456 / WS 3457)\n * are taken by the first one. Rather than make the user hand-pick `PORT` /\n * `WS_PORT` for every extra instance, the server probes upward from the\n * requested port and binds the first free one — then stamps that real port into\n * the served HTML and the instance registry so everything stays consistent.\n *\n * The probe binds a throwaway `net.Server`, then closes it, so there is a tiny\n * TOCTOU window between \"found free\" and \"the real server binds it\". For local\n * single-user multi-instance use that race is negligible; if it ever loses, the\n * real bind fails loudly with EADDRINUSE exactly as before.\n */\n\nimport * as net from 'node:net';\n\n/** Resolve true when `port` can be bound on `host`, false on EADDRINUSE/EACCES. */\nexport function isPortFree(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const srv = net.createServer();\n srv.once('error', () => resolve(false));\n srv.once('listening', () => {\n srv.close(() => resolve(true));\n });\n try {\n srv.listen(port, host);\n } catch {\n resolve(false);\n }\n });\n}\n\nexport interface FindFreePortOptions {\n /** Ports to skip even if free (e.g. one already chosen for the sibling server). */\n exclude?: Set<number> | undefined;\n /** How many consecutive ports to try before giving up. Default 200. */\n maxTries?: number | undefined;\n}\n\n/**\n * Find the first free port at or above `startPort` on `host`, skipping any in\n * `exclude`. Throws if nothing is free within `maxTries` steps.\n */\nexport async function findFreePort(\n host: string,\n startPort: number,\n opts: FindFreePortOptions = {},\n): Promise<number> {\n const exclude = opts.exclude ?? new Set<number>();\n const maxTries = opts.maxTries ?? 200;\n let port = startPort;\n for (let i = 0; i < maxTries; i++) {\n // Stay inside the valid TCP range; wrap into the high ephemeral band if a\n // pathological startPort pushes us past the ceiling.\n if (port > 65535) port = 1024 + (port % 50000);\n if (!exclude.has(port) && (await isPortFree(host, port))) {\n return port;\n }\n port++;\n }\n throw new Error(\n `No free port found near ${startPort} on ${host} after ${maxTries} attempts.`,\n );\n}\n","/**\n * Best-effort \"open this URL in the default browser\" for `--webui --open`.\n *\n * Cross-platform via the OS opener (`start` / `open` / `xdg-open`). Fully\n * fire-and-forget: a missing opener, a headless box, or a spawn failure must\n * NEVER take the server down — the URL is always also printed to the console.\n */\n\nimport { spawn } from 'node:child_process';\n\n/** Resolve the platform's URL-opener command + args. */\nexport function browserOpenCommand(\n url: string,\n platform: NodeJS.Platform = process.platform,\n): { command: string; args: string[] } {\n if (platform === 'win32') {\n // `start` is a cmd builtin; the empty \"\" is the window title slot so URLs\n // containing `&` / spaces are passed through intact.\n return { command: 'cmd', args: ['/c', 'start', '', url] };\n }\n if (platform === 'darwin') {\n return { command: 'open', args: [url] };\n }\n return { command: 'xdg-open', args: [url] };\n}\n\n/** Spawn the OS browser-opener for `url`. Never throws. */\nexport function openBrowser(url: string, platform: NodeJS.Platform = process.platform): void {\n try {\n const { command, args } = browserOpenCommand(url, platform);\n const child = spawn(command, args, { stdio: 'ignore', detached: true });\n // A missing opener (e.g. xdg-open absent on a headless box) surfaces as an\n // async 'error' event — swallow it so it doesn't crash the process.\n child.on('error', () => {});\n child.unref();\n } catch {\n // Synchronous spawn failure — best-effort, ignore.\n }\n}\n","/**\n * Token-usage cost math for the WebUI server.\n *\n * models.dev pricing is expressed in **dollars per 1,000,000 tokens**, and\n * providers omit the field entirely for free/unmetered plans. Both the\n * `session.start` payload (which ships the per-token rates to the client) and\n * `stats.get` (which reports an actual dollar figure) repeated the same\n * \"read `model.cost.*` with a `?? 0` fallback, then divide by 1e6\" logic\n * inline. Pulling it here keeps the rate normalization and the cost formula in\n * one tested place — a wrong field name or a missing `/ 1e6` silently produces\n * a plausible-but-wrong number, which is exactly what a unit test should pin.\n */\n\n/** Per-1,000,000-token pricing, normalized to numbers (0 when unpriced). */\nexport interface CostRates {\n /** $ per 1M input tokens. */\n input: number;\n /** $ per 1M output tokens. */\n output: number;\n /** $ per 1M cache-read tokens. */\n cacheRead: number;\n}\n\n/** Token counts for a turn/session. `cacheRead` is optional (older counters). */\nexport interface TokenUsage {\n input: number;\n output: number;\n cacheRead?: number | undefined;\n}\n\n/**\n * Normalize a models.dev model object's pricing into {@link CostRates}.\n * Missing model, missing `cost`, or missing individual fields all yield 0 —\n * free/unmetered plans report `$0` rather than crashing.\n */\nexport function getCostRates(model: unknown): CostRates {\n const cost = (\n model as { cost?: { input?: number | undefined; output?: number | undefined; cache_read?: number | undefined } } | null | undefined\n )?.cost;\n return {\n input: cost?.input ?? 0,\n output: cost?.output ?? 0,\n cacheRead: cost?.cache_read ?? 0,\n };\n}\n\n/**\n * Dollar cost of `usage` at the given per-1M-token `rates`. Returns 0 when all\n * rates are 0 (unpriced plan).\n */\nexport function computeUsageCost(usage: TokenUsage, rates: CostRates): number {\n return (\n (usage.input * rates.input +\n usage.output * rates.output +\n (usage.cacheRead ?? 0) * rates.cacheRead) /\n 1_000_000\n );\n}\n","/**\n * Shared config I/O helpers for the `providers` map inside the global config.\n *\n * Extracted from both `packages/webui/src/server/index.ts` and\n * `packages/cli/src/webui-server.ts` so the CLI's `--webui` mode doesn't\n * duplicate the read-merge-decrypt / encrypt-write cycle. Callers supply\n * their own vault (already booted) and config path — this module is pure I/O\n * with no side-channel state.\n */\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { type ProviderConfig, type SecretVault, atomicWrite } from '@wrongstack/core';\nimport { decryptConfigSecrets, encryptConfigSecrets } from '@wrongstack/core/security';\n\n/**\n * Read the `providers` section from the global config, decrypting\n * secret-bearing fields. Returns an empty record when the config file\n * doesn't exist or has no `providers` key.\n */\nexport async function loadSavedProviders(\n configPath: string,\n vault: SecretVault,\n): Promise<Record<string, ProviderConfig>> {\n let raw: string;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch {\n return {};\n }\n let parsed: { providers?: Record<string, ProviderConfig> } = {};\n try {\n parsed = JSON.parse(raw) as { providers?: Record<string, ProviderConfig> };\n } catch {\n return {};\n }\n if (!parsed.providers) return {};\n return decryptConfigSecrets(parsed.providers, vault);\n}\n\n/**\n * Write `providers` back into the global config, encrypting secrets first.\n * Refuses to overwrite a corrupt-but-existing config file (the operator\n * should fix it manually). When the config file is missing (ENOENT), starts\n * from an empty object.\n */\nexport async function saveProviders(\n configPath: string,\n vault: SecretVault,\n providers: Record<string, ProviderConfig>,\n): Promise<void> {\n let raw: string;\n let fileExists = true;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new Error(\n `Refusing to mutate ${configPath}: ${(err as Error).message}`,\n { cause: err },\n );\n }\n fileExists = false;\n raw = '{}';\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n if (fileExists) {\n throw new Error(\n `Refusing to overwrite corrupt config at ${configPath} ` +\n `(${(err as Error).message}). Fix or move the file aside before retrying.`,\n { cause: err },\n );\n }\n parsed = {};\n }\n parsed.providers = providers;\n const encrypted = encryptConfigSecrets(parsed, vault);\n await atomicWrite(configPath, JSON.stringify(encrypted, null, 2), { mode: 0o600 });\n}\n\n// ---------------------------------------------------------------------------\n// Standalone WebUI server helpers (boot phase — not WS-connected)\n// ---------------------------------------------------------------------------\n\nimport { DefaultSecretVault } from '@wrongstack/core';\n\n/**\n * Small helper for the standalone WebUI entry point: create a\n * `{ load, save }` pair from a config path alone (uses the\n * config-directory-relative `.key` file for the vault). The `--webui`\n * CLI mode and the standalone server both need to read/write the\n * `providers` map identically.\n */\nexport function createProviderConfigIO(configPath: string) {\n const keyFile = path.join(path.dirname(configPath), '.key');\n const vault = new DefaultSecretVault({ keyFile });\n\n return {\n load: () => loadSavedProviders(configPath, vault),\n save: (providers: Record<string, ProviderConfig>) =>\n saveProviders(configPath, vault, providers),\n };\n}\n","/**\n * Pure provider/API-key record transforms for the WebUI server's `key.*` and\n * `provider.*` WebSocket handlers.\n *\n * These operate on an in-memory `providers` record (the decrypted\n * `config.providers` map) and return a `{ ok, message }` result mirroring the\n * status string the handler sends back to the client. All persistence\n * (load/decrypt, encrypt/atomic-write) and WS messaging stays in `index.ts` —\n * keeping this layer pure means the security-sensitive key bookkeeping (which\n * key is active, when a provider is dropped, how legacy single-key configs are\n * normalized) is unit-testable without a vault or a socket.\n *\n * Extracted from `index.ts`; transforms mutate the passed record in place, the\n * same way the original handlers did before calling `saveProviders`.\n */\nimport type { ProviderApiKey, ProviderConfig } from '@wrongstack/core';\n\n\n\nfunction expectDefined<T>(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected value to be defined');\n }\n return value;\n}\n\nexport type ProvidersRecord = Record<string, ProviderConfig>;\n\nexport interface KeyOpResult {\n ok: boolean;\n message: string;\n}\n\n/**\n * Normalize a provider's keys to the array form, upgrading a legacy single\n * `apiKey` string to a one-element `[{ label: 'default', ... }]` list. Returns\n * fresh copies so callers can mutate without aliasing the stored config.\n */\nexport function normalizeKeys(cfg: ProviderConfig): ProviderApiKey[] {\n if (Array.isArray(cfg.apiKeys) && cfg.apiKeys.length > 0) {\n return cfg.apiKeys.map((k) => ({ ...k }));\n }\n if (typeof cfg.apiKey === 'string' && cfg.apiKey.length > 0) {\n return [{ label: 'default', apiKey: cfg.apiKey, createdAt: '' }];\n }\n return [];\n}\n\n/**\n * Write a normalized key list back onto a provider config: drop all key fields\n * when empty, otherwise sync `apiKeys`, the legacy `apiKey` mirror (the active\n * key), and re-point `activeKey` if it no longer names a present key.\n */\nexport function writeKeysBack(cfg: ProviderConfig, keys: ProviderApiKey[]): void {\n if (keys.length === 0) {\n delete cfg.apiKeys;\n delete cfg.apiKey;\n delete cfg.activeKey;\n return;\n }\n cfg.apiKeys = keys;\n const active = keys.find((k) => k.label === cfg.activeKey) ?? expectDefined(keys[0]);\n cfg.apiKey = active.apiKey;\n if (!cfg.activeKey || !keys.some((k) => k.label === cfg.activeKey)) {\n cfg.activeKey = active.label;\n }\n}\n\n/** Mask a secret for display: `••••` for short keys, `abcd…wxyz` otherwise. */\nexport function maskedKey(key: string | undefined): string {\n if (!key) return '—';\n if (key.length <= 8) return '•'.repeat(key.length);\n return `${key.slice(0, 4)}…${key.slice(-4)}`;\n}\n\n/** Add or replace a labeled key for a provider, creating the provider if new. */\nexport function upsertKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n apiKey: string,\n nowIso: string,\n): KeyOpResult {\n const existing: ProviderConfig = providers[providerId] ?? { type: providerId };\n const keys = normalizeKeys(existing);\n const idx = keys.findIndex((k) => k.label === label);\n if (idx >= 0) {\n keys[idx] = { ...expectDefined(keys[idx]), apiKey, createdAt: nowIso };\n } else {\n keys.push({ label, apiKey, createdAt: nowIso });\n }\n writeKeysBack(existing, keys);\n if (!existing.activeKey) existing.activeKey = label;\n providers[providerId] = existing;\n return { ok: true, message: `Key \"${label}\" saved for ${providerId}` };\n}\n\n/** Remove a labeled key; drops the provider entirely when its last key goes. */\nexport function deleteKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n): KeyOpResult {\n const existing = providers[providerId];\n if (!existing) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n const keys = normalizeKeys(existing).filter((k) => k.label !== label);\n if (keys.length === 0) {\n delete providers[providerId];\n } else {\n writeKeysBack(existing, keys);\n if (existing.activeKey === label) existing.activeKey = keys[0]?.label;\n providers[providerId] = existing;\n }\n return { ok: true, message: `Key \"${label}\" deleted from ${providerId}` };\n}\n\n/** Point a provider's active key at the given label. */\nexport function setActiveKey(\n providers: ProvidersRecord,\n providerId: string,\n label: string,\n): KeyOpResult {\n const existing = providers[providerId];\n if (!existing) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n existing.activeKey = label;\n writeKeysBack(existing, normalizeKeys(existing));\n providers[providerId] = existing;\n return { ok: true, message: `Active key for ${providerId} set to \"${label}\"` };\n}\n\n/** Register a brand-new provider (optionally with an initial `default` key). */\nexport function addProvider(\n providers: ProvidersRecord,\n payload: { id: string; family: string; baseUrl?: string | undefined; apiKey?: string | undefined },\n nowIso: string,\n): KeyOpResult {\n if (providers[payload.id]) {\n return {\n ok: false,\n message: `Provider \"${payload.id}\" already exists. Use key.add to add a key.`,\n };\n }\n const newProv: ProviderConfig = {\n type: payload.id,\n family: payload.family as ProviderConfig['family'],\n baseUrl: payload.baseUrl,\n };\n if (payload.apiKey) {\n newProv.apiKeys = [{ label: 'default', apiKey: payload.apiKey, createdAt: nowIso }];\n newProv.activeKey = 'default';\n }\n providers[payload.id] = newProv;\n return { ok: true, message: `Provider \"${payload.id}\" added` };\n}\n\n/** Remove an entire provider and all its keys. */\nexport function removeProvider(providers: ProvidersRecord, providerId: string): KeyOpResult {\n if (!providers[providerId]) {\n return { ok: false, message: `Provider \"${providerId}\" not found` };\n }\n delete providers[providerId];\n return { ok: true, message: `Provider \"${providerId}\" removed` };\n}\n","/**\n * Shared WebSocket utilities for both the standalone WebUI server and the\n * CLI's `--webui` embedded server. Extracted from the duplicated `send` /\n * `broadcast` / `sendResult` / `generateAuthToken` patterns that were\n * copy-pasted between `packages/webui/src/server/index.ts` and\n * `packages/cli/src/webui-server.ts`.\n */\nimport { randomBytes } from 'node:crypto';\n// Value import (not `import type`): we reference `WebSocket.OPEN` below, which\n// is a runtime value, not just a type.\nimport { WebSocket } from 'ws';\nimport type { ConnectedClient, WSServerMessage } from './types.js';\n\n/**\n * Send a JSON message to a single WebSocket client.\n * No-op when the socket is not in OPEN state (disconnected / closing).\n */\nexport function send(ws: WebSocket, msg: WSServerMessage): void {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(msg));\n }\n}\n\n/**\n * Broadcast a JSON message to every connected client.\n * Swallows per-socket send errors — a client that disconnected between the\n * readyState check and `ws.send()` is cleaned up by its own `close` handler.\n */\nexport function broadcast(\n clients: Map<WebSocket, ConnectedClient>,\n msg: WSServerMessage,\n): void {\n const data = JSON.stringify(msg);\n for (const [ws] of clients) {\n if (ws.readyState === WebSocket.OPEN) {\n try {\n ws.send(data);\n } catch {\n // Client disconnected between the readyState check and the send —\n // let the 'close' handler remove it from the map naturally.\n }\n }\n }\n}\n\n/**\n * Send a success/failure result message (used by key.* and provider.* handlers).\n * The frontend expects `key.operation_result` with `{ success, message }`.\n */\nexport function sendResult(ws: WebSocket, success: boolean, message: string): void {\n send(ws, { type: 'key.operation_result', payload: { success, message } });\n}\n\n/**\n * Extract a human-readable message from an unknown thrown value.\n */\nexport function errMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Generate a cryptographically random WebSocket auth token (hex string).\n * Shared between standalone and CLI-embedded WebUI servers.\n */\nexport function generateAuthToken(): string {\n return randomBytes(16).toString('hex');\n}\n","import type { WebSocket } from 'ws';\nimport type { ProviderConfig } from '@wrongstack/core';\nimport { loadSavedProviders, saveProviders } from './provider-config-io.js';\nimport {\n upsertKey as upsertKeyRecord,\n deleteKey as deleteKeyRecord,\n setActiveKey as setActiveKeyRecord,\n addProvider as addProviderRecord,\n removeProvider as removeProviderRecord,\n} from './provider-keys.js';\nimport type { WSServerMessage } from './types.js';\nimport { sendResult, errMessage } from './ws-utils.js';\n\nexport interface ProviderHandlerDeps {\n globalConfigPath: string;\n vault: import('@wrongstack/core').SecretVault;\n /** Shared config write lock — serialized via chained promises */\n setConfigWriteLock: (lock: Promise<void>) => void;\n getConfigWriteLock: () => Promise<void>;\n}\n\nexport function createProviderHandlers(deps: ProviderHandlerDeps) {\n const { globalConfigPath, vault } = deps;\n let configWriteLock = deps.getConfigWriteLock();\n\n async function loadConfigProviders(): Promise<Record<string, ProviderConfig>> {\n return loadSavedProviders(globalConfigPath, vault);\n }\n\n async function saveConfigProviders(providers: Record<string, ProviderConfig>): Promise<void> {\n const next = configWriteLock.then(() => saveProviders(globalConfigPath, vault, providers));\n configWriteLock = next;\n deps.setConfigWriteLock(next);\n await next;\n }\n\n async function handleKeyUpsert(ws: WebSocket, providerId: string, label: string, apiKey: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = upsertKeyRecord(providers, providerId, label, apiKey, new Date().toISOString());\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleKeyDelete(ws: WebSocket, providerId: string, label: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = deleteKeyRecord(providers, providerId, label);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleKeySetActive(ws: WebSocket, providerId: string, label: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = setActiveKeyRecord(providers, providerId, label);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleProviderAdd(ws: WebSocket, payload: { id: string; family: string; baseUrl?: string | undefined; apiKey?: string | undefined }): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = addProviderRecord(providers, payload, new Date().toISOString());\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n async function handleProviderRemove(ws: WebSocket, providerId: string): Promise<void> {\n try {\n const providers = await loadConfigProviders();\n const result = removeProviderRecord(providers, providerId);\n if (result.ok) await saveConfigProviders(providers);\n sendResult(ws, result.ok, result.message);\n } catch (err) {\n sendResult(ws, false, errMessage(err));\n }\n }\n\n return { handleKeyUpsert, handleKeyDelete, handleKeySetActive, handleProviderAdd, handleProviderRemove, loadConfigProviders };\n}\n","import type { EventBus, Context } from '@wrongstack/core';\nimport type { WebSocket } from 'ws';\nimport type { ConnectedClient, WSServerMessage } from './types.js';\n\nexport interface SetupEventsDeps {\n events: EventBus;\n broadcast: (clients: Map<WebSocket, ConnectedClient>, msg: WSServerMessage) => void;\n clients: Map<WebSocket, ConnectedClient>;\n config: { tools?: { maxIterations?: number | undefined } };\n context: Context;\n pendingConfirms: Map<string, (d: 'yes' | 'no' | 'always' | 'deny') => void>;\n}\n\nexport function setupEvents(deps: SetupEventsDeps): void {\n const { events, broadcast, clients, config, context, pendingConfirms } = deps;\n\n events.on('iteration.started', (e) => {\n broadcast(clients, {\n type: 'iteration.started',\n payload: { index: e.index, maxIterations: config.tools?.maxIterations ?? 100 },\n });\n });\n\n events.on('provider.text_delta', (e) => {\n broadcast(clients, { type: 'provider.text_delta', payload: { text: e.text, messageId: 'current' } });\n });\n\n events.on('provider.thinking_delta', (e) => {\n broadcast(clients, { type: 'provider.thinking_delta', payload: { text: e.text } });\n });\n\n events.on('tool.started', (e) => {\n broadcast(clients, {\n type: 'tool.started',\n payload: { id: e.id, name: e.name, input: e.input, messageId: `tool_${e.id}` },\n });\n });\n\n events.on('tool.progress', (e) => {\n broadcast(clients, {\n type: 'tool.progress',\n payload: { id: e.id, name: e.name, eventType: e.event.type, text: e.event.text },\n });\n });\n\n events.on('tool.executed', (e) => {\n broadcast(clients, {\n type: 'tool.executed',\n payload: { id: e.id, name: e.name, durationMs: e.durationMs, ok: e.ok, input: e.input, output: e.output },\n });\n broadcast(clients, { type: 'todos.updated', payload: { todos: [...context.todos] } });\n });\n\n events.on('provider.response', (e) => {\n broadcast(clients, { type: 'provider.response', payload: { usage: e.usage, stopReason: e.stopReason, messageId: 'current' } });\n });\n\n events.on('context.repaired', (e) => {\n broadcast(clients, { type: 'context.repaired', payload: { removedToolUses: e.removedToolUses, removedToolResults: e.removedToolResults, removedMessages: e.removedMessages } });\n });\n\n events.on('tool.confirm_needed', (e) => {\n const id = e.toolUseId ?? `confirm_${Date.now()}`;\n pendingConfirms.set(id, e.resolve);\n broadcast(clients, { type: 'tool.confirm_needed', payload: { id, toolName: e.tool?.name ?? 'unknown', input: e.input, suggestedPattern: e.suggestedPattern } });\n });\n\n events.on('error', (e) => {\n broadcast(clients, { type: 'error', payload: { phase: e.phase, message: e.err instanceof Error ? e.err.message : String(e.err) } });\n });\n\n // Subagent fleet lifecycle\n const forwardSubagent = (kind: string, payload: Record<string, unknown>) =>\n broadcast(clients, { type: 'subagent.event', payload: { kind, ...payload } });\n\n events.on('subagent.spawned', (e) => forwardSubagent('spawned', { subagentId: e.subagentId, taskId: e.taskId, name: e.name, provider: e.provider, model: e.model, description: e.description }));\n events.on('subagent.task_started', (e) => forwardSubagent('task_started', { subagentId: e.subagentId, taskId: e.taskId, description: e.description }));\n events.on('subagent.tool_executed', (e) => forwardSubagent('tool_executed', { subagentId: e.subagentId, toolName: e.name, durationMs: e.durationMs, ok: e.ok }));\n events.on('subagent.iteration_summary', (e) => forwardSubagent('iteration_summary', { subagentId: e.subagentId, iteration: e.iteration, toolCalls: e.toolCalls, costUsd: e.costUsd, currentTool: e.currentTool }));\n events.on('subagent.budget_extended', (e) => forwardSubagent('budget_extended', { subagentId: e.subagentId, totalExtensions: e.totalExtensions }));\n events.on('subagent.ctx_pct', (e) => forwardSubagent('ctx_pct', { subagentId: e.subagentId, load: e.load, tokens: e.tokens, maxContext: e.maxContext }));\n events.on('subagent.task_completed', (e) => forwardSubagent('task_completed', { subagentId: e.subagentId, status: e.status, iterations: e.iterations, toolCalls: e.toolCalls, error: e.error ? { kind: e.error.kind, message: e.error.message } : undefined }));\n}\n","/**\n * Per-section context-window token estimate for the `context.debug` command.\n *\n * Uses the simple 4-chars-per-token heuristic — not exact, but close enough to\n * spot which section (system prompt, tool schemas, or message history) is\n * eating the context window. Tool schemas in particular are easy to overlook:\n * each tool ships its full JSON schema to the model every turn, so 20+ builtins\n * can cost 10-20k tokens on their own.\n *\n * Extracted from `index.ts` as a pure function so the breakdown maths can be\n * unit tested without standing up a Context/ToolRegistry.\n */\n\n/** 4-chars-per-token heuristic estimate for a string. */\nexport function estimateTokens(s: string): number {\n return Math.ceil(s.length / 4);\n}\n\n/** Stringify arbitrary content for length estimation (JSON, with fallbacks). */\nexport function stringifyContent(c: unknown): string {\n if (typeof c === 'string') return c;\n try {\n return JSON.stringify(c);\n } catch {\n return String(c);\n }\n}\n\ninterface PromptBlock {\n text?: string | undefined;\n}\ninterface ToolLike {\n name: string;\n inputSchema?: unknown | undefined;\n description?: string | undefined;\n}\ninterface ContentBlock {\n type?: string | undefined;\n text?: string | undefined;\n input?: unknown | undefined;\n content?: unknown | undefined;\n name?: string | undefined;\n}\ninterface MessageLike {\n role: string;\n content: unknown;\n}\n\nexport interface ToolTokenEntry {\n name: string;\n tokens: number;\n}\nexport interface MessageTokenEntry {\n index: number;\n role: string;\n tokens: number;\n preview: string;\n}\n\nexport interface ContextBreakdown {\n total: number;\n systemPrompt: number;\n tools: { total: number; count: number; breakdown: ToolTokenEntry[] };\n messages: { total: number; count: number; breakdown: MessageTokenEntry[] };\n}\n\nfunction messageTokens(content: unknown): number {\n if (typeof content === 'string') return estimateTokens(content);\n if (!Array.isArray(content)) return 0;\n let tk = 0;\n for (const b of content as ContentBlock[]) {\n if (b.type === 'text') tk += estimateTokens(b.text ?? '');\n else if (b.type === 'tool_use') tk += estimateTokens(stringifyContent(b.input));\n else if (b.type === 'tool_result') tk += estimateTokens(stringifyContent(b.content));\n else tk += estimateTokens(stringifyContent(b));\n }\n return tk;\n}\n\nfunction messagePreview(content: unknown): string {\n if (typeof content === 'string') return content.slice(0, 60);\n if (!Array.isArray(content)) return '';\n return (content as ContentBlock[])\n .map((b) =>\n b.type === 'text'\n ? (b.text ?? '').slice(0, 40)\n : b.type === 'tool_use'\n ? `[tool_use: ${b.name}]`\n : b.type === 'tool_result'\n ? '[tool_result]'\n : `[${b.type}]`,\n )\n .join(' ')\n .slice(0, 60);\n}\n\n/**\n * Compute the per-section token breakdown for the active context. Mirrors the\n * shape the `context.debug` WS reply expects (minus the `mode`/`policy` fields,\n * which the caller layers on from `context.meta`).\n */\nexport function estimateContextBreakdown(input: {\n systemPrompt: ReadonlyArray<PromptBlock>;\n tools: ReadonlyArray<ToolLike>;\n messages: ReadonlyArray<MessageLike>;\n}): ContextBreakdown {\n const sysTokens = input.systemPrompt.reduce((acc, b) => acc + estimateTokens(b.text ?? ''), 0);\n\n const toolBreakdown: ToolTokenEntry[] = input.tools.map((t) => {\n const schema = t.inputSchema ?? {};\n const desc = t.description ?? '';\n return {\n name: t.name,\n tokens:\n estimateTokens(t.name) + estimateTokens(desc) + estimateTokens(stringifyContent(schema)),\n };\n });\n const toolTokens = toolBreakdown.reduce((a, b) => a + b.tokens, 0);\n\n const messageBreakdown: MessageTokenEntry[] = input.messages.map((m, i) => ({\n index: i,\n role: m.role,\n tokens: messageTokens(m.content),\n preview: messagePreview(m.content),\n }));\n const msgTokens = messageBreakdown.reduce((a, b) => a + b.tokens, 0);\n\n return {\n total: sysTokens + toolTokens + msgTokens,\n systemPrompt: sysTokens,\n tools: { total: toolTokens, count: input.tools.length, breakdown: toolBreakdown },\n messages: { total: msgTokens, count: input.messages.length, breakdown: messageBreakdown },\n };\n}\n","// Server entry point for standalone WebUI.\n// Bind defaults: 127.0.0.1:3457 (loopback only). Override with WS_HOST / WS_PORT.\n// HTTP frontend defaults to 3456 (override with PORT). Run several instances on\n// different PORT/WS_PORT pairs — `webui --list` shows which are open for which\n// project (registry: ~/.wrongstack/webui-instances.json).\nimport { startWebUI } from './index.js';\nimport { formatInstances, listInstances } from './instance-registry.js';\n\nconst argv = process.argv.slice(2);\n\n// `webui --list` / `webui ls` — print running instances and exit. Cheap,\n// side-effect-free (it only prunes dead pids), so it never boots a server.\nif (argv.includes('--list') || argv.includes('-l') || argv[0] === 'ls') {\n listInstances()\n .then((instances) => {\n console.log(formatInstances(instances));\n process.exit(0);\n })\n .catch((err) => {\n console.error('[WebUI] Could not read instance registry:', err);\n process.exit(1);\n });\n} else {\n const wsPort = Number.parseInt(process.env['WS_PORT'] ?? '3457', 10);\n const wsHost = process.env['WS_HOST'] ?? '127.0.0.1';\n const open =\n argv.includes('--open') || argv.includes('-o') || process.env['WEBUI_OPEN'] === '1';\n\n console.log(`[WebUI] Starting standalone server on ${wsHost}:${wsPort}...`);\n\n startWebUI({ wsPort, wsHost, open }).catch((err) => {\n console.error('[WebUI] Fatal error:', err);\n process.exit(1);\n });\n}\n"],"mappings":";AAAA,YAAYA,SAAQ;AAEpB,YAAYC,WAAU;;;ACmBtB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,UAAU;AAgBtB,IAAM,aAAqC;AAAA,EACzC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AACV;AAcO,SAAS,aAAa,MAAc,QAAwB;AACjE,QAAM,MAAM,4CAA4C,MAAM;AAE9D,MAAI,KAAK,SAAS,2BAA2B,EAAG,QAAO;AACvD,MAAI,KAAK,SAAS,SAAS,GAAG;AAC5B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,MAAM,QAAQ,KAAK;AAAA,IAC5B,SAAS,CAAC,YAAY,YAAY,YAAY;AAAA;AAAA;AAAA,IAG9C,YAAY,MAAM,mBAAmB,QAAQ,KAAK,eAAe;AAAA,EACnE,CAAC;AACH;;;AoB/rDA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AAIjC,IAAI,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,CAAC,MAAM,MAAM;AACtE,gBAAc,EACX,KAAK,CAAC,cAAc;AACnB,YAAQ,IAAI,gBAAgB,SAAS,CAAC;AACtC,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,YAAQ,MAAM,6CAA6C,GAAG;AAC9D,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACL,OAAO;AACL,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,SAAS,KAAK,QAAQ,EAAE;AACnE,QAAM,SAAS,QAAQ,IAAI,SAAS,KAAK;AACzC,QAAM,OACJ,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,KAAK,QAAQ,IAAI,YAAY,MAAM;AAElF,UAAQ,IAAI,yCAAyC,MAAM,IAAI,MAAM,KAAK;AAE1E,aAAW,EAAE,QAAQ,QAAQ,KAAK,CAAC,EAAE,MAAM,CAAC,QAAQ;AAClD,YAAQ,MAAM,wBAAwB,GAAG;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["fs","path","DefaultMemoryStore","DefaultModeStore","DefaultSessionStore","DefaultSkillLoader","DefaultSystemPromptBuilder","DefaultTokenCounter","HybridCompactor","TOKENS","atomicWrite","s","path","fs","resolve","fs","path","atomicWrite","broadcast","expectDefined","TOKENS","DefaultMemoryStore","DefaultSessionStore","DefaultTokenCounter","DefaultModeStore","DefaultSkillLoader","DefaultSystemPromptBuilder","HybridCompactor","verifyClient","resolve","provider","atomicWrite","modePrompt"]}