@ordewell/web 0.13.1 → 0.13.2

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":["../../server/routes/errors.ts","../../server/routes/children.ts","../../server/pool/childStreams.ts","../../server/adapters/WebConfig.ts","../../server/utils/workspaceScanner.ts","../../server/adapters/run.ts","../../server/adapters/PoolFileSystem.ts","../../server/adapters/PoolAwareRunner.ts","../../server/pool/orchestratorPool.ts","../../server/routes/sessions.ts","../../server/routes/plans.ts","../../server/routes/runners.ts","../../server/routes/models.ts","../../server/routes/workspaces.ts","../../server/routes/approvals.ts","../../server/routes/settings.ts","../../server/routes/commands.ts","../../server/routes/workspaceRead.ts","../../server/routes/workspaceWrite.ts","../../server/ws/stream.ts","../../server/security/admission.ts","../../server/utils/serverVersion.ts","../../server/app.ts","../../server/nodeAdapter.ts","../../server/daemon.ts","../../server/main.ts"],"names":["SessionNotFoundError","SessionHeldError","NoPlanError","AlreadyExecutingError","WorkspaceNotAProjectError","WorkspaceNotFoundError","PlannerNotReadyError","PlannerTurnStoppedError","PlannerTurnDiscardedError","ConversationBusyError","WorkspaceReadError","UserGitError","ConversationEditError","PlanEditError","TaskControlError","Hono","listTaskLogAttempts","taskLogForSurface","readTaskLog","BaseConfig","isApiProvider","normalizeGeminiModel","defaultEnabledRunners","DEFAULT_RUNNERS","fs","path","os","isSea","resolve","execFile","BaseFileSystem","researchToolsPath","withPath","GREP_PCRE_PROBE_ARGS","grepRegexFromProbe","result","buildGlobArgs","capped","applyHeadLimit","formatSearchOutput","SEARCH_EXCLUSIONS","path2","buildGrepArgs","buildFallbackGrepArgs","filterFallbackByAnchoredInclude","listTree","STOPPED_TOOL_RESULT","headLines","text","randomUUID","RunnerRegistry","SettingsService","PlannerModelMemory","removedPluginNotice","StructuredRunner","RunnerInstallation","workspaceEnvOf","ModelResolver","CodexSandboxAvailability","nodeSpawn","createIsolationPreview","claudeAccountLimitCollector","codexAccountLimitCollector","openCodeGoAccountLimitCollector","detectInstalledPlanner","assertWorkspaceExists","AccountLimitMonitor","flattenTasks","task","assignedRunnerOf","processLeaseHost","savedRunLooksLive","appendUserAction","sessionRuntimeSettings","assertWorkspaceIsProject","ensureStateDirIgnored","createSession","changes","containerStatus","changeContainers","runnerForProvider","selectPlanner","PROVIDER_CREDENTIAL_ENV","forgetSignedOutRunnerAuth","configuredProviders","runnerModesFrom","migratePlanState","recordedRunnerAuth","installedPlannerAnswered","loadSession","reclaimContainers","scanWorkspaces","listSessions","discardChildRuns","createWorktreeIsolation","deleteSession","admitSettingsEnv","run","surfacePlan","surfacePlanState","resolveUserTaskRef","parseExecutionCommand","installedPlannerDetected","toApprovalDecision","isGranted","containersOffered","RunSettingsError","refuse","WebSocketServer","DAEMON_SUBPROTOCOL","tokensMatch","extractPresentedToken","seaVersion","dirname","readFileSync","join","createUserGit","landingRuns","createWorkspaceReader","DAEMON_CONTRACT","createServer","mintDaemonToken","mkdirSync","writeFileSync","unlinkSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAC1C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AAAA,EACd;AACF,CAAA;AAGO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC5C,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,mCAAmC,CAAA;AACzC,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF,CAAA;AAOA,eAAsB,WAAuD,CAAA,EAAwB;AACnG,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,MAAM,CAAA,CAAE,GAAA,CAAI,IAAA,EAAK;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAA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;AAAA,MAAqB;AAAA,IAC1D;AACA,IAAA,IAAA,CAAK,UAAA,EAAW;AAChB,IAAA,MAAA,CAAO,KAAA,EAAM;AACb,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AAIA,EAAA,OAAA,CAAQ,EAAA,CAAG,oBAAA,EAAsB,CAAC,MAAA,KAAW;AAC3C,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,MAAA,YAAkB,KAAA,GAAQ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,MAAM,CAAC,CAAA,CAAE,CAAA;AAAA,EACzH,CAAC,CAAA;AAOD,EAAA,OAAA,CAAQ,EAAA,CAAG,UAAU,MAAM;AAAE,IAAA,IAAI,CAAC,gBAAgB,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAC/D,EAAA,OAAA,CAAQ,EAAA,CAAG,WAAW,MAAM;AAAE,IAAA,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAC3C,EAAA,OAAA,CAAQ,EAAA,CAAG,UAAU,MAAM;AAAE,IAAA,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAE1C,EAAA,IAAI,cAAA,EAAgB;AAClB,IAAA,MAAM,WAAA,GAAc,YAAY,MAAM;AACpC,MAAA,IAAI;AACF,QAAA,OAAA,CAAQ,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAAA,MAChC,CAAA,CAAA,MAAQ;AACN,QAAA,aAAA,CAAc,WAAW,CAAA;AACzB,QAAA,QAAA,EAAS;AAAA,MACX;AAAA,IACF,GAAG,GAAI,CAAA;AAAA,EACT;AACF;;;ACxGA,SAAA,CAAU,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA","file":"main.js","sourcesContent":["import type { Context } from 'hono';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport {\n AlreadyExecutingError,\n ConversationBusyError,\n ConversationEditError,\n NoPlanError,\n PlanEditError,\n PlannerNotReadyError,\n PlannerTurnDiscardedError,\n PlannerTurnStoppedError,\n SessionHeldError,\n SessionNotFoundError,\n TaskControlError,\n UserGitError,\n WorkspaceNotAProjectError,\n WorkspaceNotFoundError,\n WorkspaceReadError,\n type DaemonErrorCode,\n type ErrorBody,\n} from '@ordewell/core';\n\ninterface Classified {\n status: ContentfulStatusCode;\n code: DaemonErrorCode;\n}\n\n/** A request body that is missing, not JSON, or not an object: the request's fault, never a fault of the daemon. */\nexport class InvalidBodyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidBodyError';\n }\n}\n\n/** An id the tree does not hold, whatever else it might name. */\nexport class ChildNotFoundError extends Error {\n constructor() {\n super('This tree has no such child plan.');\n this.name = 'ChildNotFoundError';\n }\n}\n\n/**\n * The body of a route that needs one object. Every route that read\n * `c.req.json()` directly turned a client's typo into a 500 with the parser's\n * message and a logged stack, while its neighbours answered 400.\n */\nexport async function jsonObject<T extends object = Record<string, unknown>>(c: Context): Promise<T> {\n let parsed: unknown;\n try {\n parsed = await c.req.json();\n } catch {\n throw new InvalidBodyError('The request body must be valid JSON.');\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new InvalidBodyError('The request body must be a JSON object.');\n }\n return parsed as T;\n}\n\n/**\n * The one table from a thrown class to a status and a stable code. A refusal is\n * the request being wrong (400) or arriving at a bad moment (409), a missing\n * session is 404, and only what falls through is a fault — collapsing these\n * into 404/500 gave the TUI and VS Code nothing to show but \"Internal error\",\n * which reads as the edit having silently done nothing.\n *\n * Order matters: `ConversationBusyError` extends `ConversationEditError`.\n */\nfunction classify(err: unknown): Classified | undefined {\n if (err instanceof InvalidBodyError) return { status: 400, code: 'refused' };\n if (err instanceof SessionNotFoundError) return { status: 404, code: 'session_not_found' };\n if (err instanceof ChildNotFoundError) return { status: 404, code: 'child_not_found' };\n // 409: the session exists; another host has it open right now (ADR-0049).\n if (err instanceof SessionHeldError) return { status: 409, code: 'session_held' };\n if (err instanceof NoPlanError) return { status: 400, code: 'no_plan' };\n if (err instanceof AlreadyExecutingError) return { status: 409, code: 'already_executing' };\n if (err instanceof WorkspaceNotAProjectError) return { status: 400, code: 'workspace_not_a_project' };\n if (err instanceof WorkspaceNotFoundError) return { status: 400, code: 'workspace_not_found' };\n // 409: the request is fine; the machine is not set up to serve it yet.\n if (err instanceof PlannerNotReadyError) return { status: 409, code: 'planner_not_ready' };\n // 409, not 5xx: the turn ending is what the user asked for (or a plan they\n // dropped), and a 5xx would log a stack for every Stop.\n if (err instanceof PlannerTurnStoppedError) return { status: 409, code: 'planner_turn_stopped' };\n if (err instanceof PlannerTurnDiscardedError) return { status: 409, code: 'planner_turn_discarded' };\n if (err instanceof ConversationBusyError) return { status: 409, code: 'conversation_busy' };\n // A user read (ADR-0064): a scope that no longer exists is gone (410), never\n // answered from another; a path outside the scope is forbidden, not missing.\n if (err instanceof WorkspaceReadError) {\n if (err.code === 'gone') return { status: 410, code: 'gone' };\n if (err.code === 'path_refused') return { status: 403, code: 'path_refused' };\n if (err.code === 'path_not_found') return { status: 404, code: 'path_not_found' };\n return { status: 400, code: 'refused' };\n }\n // A user git action (ADR-0062): what changed under the person, or a run\n // holding the branch, is a bad moment (409); git's own refusal (a hook, a\n // rejected push) is the person's repository answering, not a daemon fault.\n if (err instanceof UserGitError) {\n if (err.code === 'landing_branch_held' || err.code === 'confirm_stale' || err.code === 'stale') return { status: 409, code: err.code };\n return { status: 400, code: err.code };\n }\n if (err instanceof ConversationEditError || err instanceof PlanEditError || err instanceof TaskControlError) {\n return { status: 400, code: 'refused' };\n }\n return undefined;\n}\n\n/** A refusal the route itself decided on, in the body shape every client reads. */\nexport function refuse(c: Context, status: ContentfulStatusCode, message: string, code?: DaemonErrorCode) {\n const body: ErrorBody = code ? { error: message, code } : { error: message };\n return c.json(body, status);\n}\n\n/**\n * A JSON error response from a thrown call. What `classify` does not know is a\n * fault and takes the route's `fallback` status; only a 5xx is logged, since a\n * refusal is the request being wrong and travels to the client as-is.\n */\nexport function failure(\n c: Context,\n err: unknown,\n label: string,\n { fallback = 500, message = 'Internal error' }: { fallback?: ContentfulStatusCode; message?: string } = {},\n) {\n const classified = classify(err);\n const status = classified?.status ?? fallback;\n // Log before returning: the message alone travels to the client, so an\n // unexpected throw (a research tool crashing the whole turn, say) left no\n // stack anywhere — server.log showed nothing and the CLI showed one line.\n if (status >= 500) console.error(`[web] ${label} failed:`, err);\n const body: ErrorBody = {\n error: (err instanceof Error && err.message) || message,\n ...(classified ? { code: classified.code } : {}),\n ...(err instanceof WorkspaceNotAProjectError ? { workspace: err.workspace } : {}),\n ...(err instanceof PlannerNotReadyError ? { plannerNotReady: err.reason } : {}),\n ...(err instanceof SessionHeldError ? { sessionHeld: err.held } : {}),\n ...(err instanceof UserGitError && err.detail.held ? { landingBranchHeld: err.detail.held } : {}),\n ...(err instanceof UserGitError && err.detail.difference ? { confirmStale: err.detail.difference } : {}),\n };\n return c.json(body, status);\n}\n","import { Hono, type Context } from 'hono';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport {\n listTaskLogAttempts,\n readTaskLog,\n taskLogForSurface,\n type ChildListResponse,\n type ChildMessageResponse,\n type ChildPlanHandle,\n type ChildPlanResponse,\n type ChildControlOutcome,\n type ChildTaskControlResponse,\n type DaemonErrorCode,\n type TaskLogAttemptsResponse,\n type TaskLogResponse,\n} from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { ChildNotFoundError, failure, jsonObject, refuse } from './errors';\n\nconst ABOVE_THIS_PLAN = 'A raise or a force is the plan above this one to give: this request sets neither.';\n\nconst CONTROL_REFUSALS: Record<Extract<ChildControlOutcome, { ok: false }>['code'], { status: ContentfulStatusCode; code: DaemonErrorCode }> = {\n view_only: { status: 409, code: 'child_view_only' },\n refused: { status: 409, code: 'child_refused' },\n no_task: { status: 404, code: 'child_task_not_found' },\n not_waiting: { status: 409, code: 'checkpoint_not_waiting' },\n};\n\n/**\n * Selecting, reading and speaking to the plans below a root (ADR-0055 D20).\n * Each goes through the root a surface holds, and its directory, so an id this\n * tree does not name reads nothing. A person's message is the words and nothing\n * else: no field here raises a budget, adds a grant or approves an effect. A\n * checkpoint is answered on the plan that holds it, under what that plan's own\n * subplanner may do, and a task id is the plan's exactly: nothing here resolves\n * a reference or falls back to the root. An unloaded root answers\n * `session_not_found`, and `POST /:id/load` loads it, starting nothing.\n */\nexport function childrenRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n const childOf = async (c: Context): Promise<ChildPlanHandle> => {\n const child = await pool.session(c.req.param('id')!).children.find(c.req.param('childId')!);\n if (!child) throw new ChildNotFoundError();\n return child;\n };\n const position = (c: Context) => pool.childPosition(c.req.param('id')!, c.req.param('childId')!);\n const controlled = (c: Context, outcome: ChildControlOutcome) => {\n if (!outcome.ok) return refuse(c, CONTROL_REFUSALS[outcome.code].status, outcome.message, CONTROL_REFUSALS[outcome.code].code);\n return c.json({ message: outcome.message, ...(outcome.id ? { id: outcome.id } : {}) } satisfies ChildTaskControlResponse);\n };\n // The root's routes take these. Dropped here, a person would believe a raise\n // or a force went through; the plan above holds both (ADR-0056 M8).\n const asksAboveItsPlan = (body: object) => 'raiseTokens' in body || 'force' in body;\n\n router.get('/:id/children', async (c) => {\n try {\n return c.json({ children: await pool.session(c.req.param('id')).children.list() } satisfies ChildListResponse);\n } catch (err) {\n return failure(c, err, 'list child plans');\n }\n });\n\n router.get('/:id/children/:childId', async (c) => {\n try {\n const child = await childOf(c);\n return c.json({ ...child.view(), position: position(c) } satisfies ChildPlanResponse);\n } catch (err) {\n return failure(c, err, 'read child plan');\n }\n });\n\n router.get('/:id/children/:childId/tasks/:taskId/log', async (c) => {\n try {\n const child = await childOf(c);\n return c.json({ attempts: listTaskLogAttempts(child.logLocation(), c.req.param('taskId')), position: position(c) } satisfies TaskLogAttemptsResponse);\n } catch (err) {\n return failure(c, err, 'list child task log');\n }\n });\n\n router.get('/:id/children/:childId/tasks/:taskId/log/:attempt', async (c) => {\n try {\n const child = await childOf(c);\n const attempt = Number(c.req.param('attempt'));\n if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, 'attempt must be a positive integer');\n return c.json({ attempt, events: taskLogForSurface(readTaskLog(child.logLocation(), c.req.param('taskId'), attempt)), position: position(c) } satisfies TaskLogResponse);\n } catch (err) {\n return failure(c, err, 'read child task log');\n }\n });\n\n router.post('/:id/children/:childId/message', async (c) => {\n try {\n const child = await childOf(c);\n const body = await jsonObject<{ message?: unknown }>(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n const { message } = body;\n if (typeof message !== 'string' || !message.trim()) return refuse(c, 400, 'message must be a non-empty string');\n const outcome = child.message(message);\n if (!outcome.ok) return refuse(c, 409, outcome.message, outcome.code === 'view_only' ? 'child_view_only' : 'child_refused');\n return c.json({ status: outcome.status } satisfies ChildMessageResponse);\n } catch (err) {\n return failure(c, err, 'message child plan');\n }\n });\n\n router.post('/:id/children/:childId/tasks/:taskId/message', async (c) => {\n try {\n const child = await childOf(c);\n const body = await jsonObject<{ message?: unknown }>(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n if (typeof body.message !== 'string' || !body.message.trim()) return refuse(c, 400, 'message must be a non-empty string', 'refused');\n return controlled(c, await child.control(c.req.param('taskId'), { kind: 'message', text: body.message }));\n } catch (err) {\n return failure(c, err, 'message child task');\n }\n });\n\n for (const answer of ['approve', 'reject'] as const) {\n router.post(`/:id/children/:childId/tasks/:taskId/checkpoint/${answer}`, async (c) => {\n try {\n const child = await childOf(c);\n const body = await jsonObject<{ question?: unknown; reason?: unknown }>(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n const { question } = body;\n if (typeof question !== 'string' || !question.trim()) return refuse(c, 400, 'question must be the words the task is waiting on', 'refused');\n if (body.reason !== undefined && typeof body.reason !== 'string') return refuse(c, 400, 'reason must be a string', 'refused');\n const reason = body.reason?.trim();\n if (answer === 'reject' && !reason) return refuse(c, 400, 'A rejection needs a reason: it is all the runner has to go on.', 'refused');\n return controlled(c, await child.control(c.req.param('taskId'), { kind: 'checkpoint', answer, question, ...(reason ? { reason } : {}) }));\n } catch (err) {\n return failure(c, err, 'answer child checkpoint');\n }\n });\n }\n\n return router;\n}\n","import type { WebSocket } from 'ws';\nimport type { ChildFrame, ChildPlanHandle, RunSnapshotFrame, SessionFrame, StreamStamp } from '@ordewell/core';\n\ninterface Watched {\n sockets: Set<WebSocket>;\n stop(): void;\n}\n\n/**\n * The sockets on a child plan (ADR-0055 D20): a child's frames reach only those\n * watching it, numbered on a count of its own. The count outlives every watcher\n * and every Session of the root, so a socket that comes back never sees the\n * numbers go backward. The child's words stay on these sockets: no frame of\n * theirs enters the root's stream.\n */\nexport class ChildStreams {\n private readonly watched = new Map<string, Watched>();\n private readonly sequence = new Map<string, number>();\n\n constructor(private readonly stream: string) {}\n\n /** Snapshot and watching in one turn, as a root's socket has them: no frame can fall between. */\n join(rootId: string, childId: string, child: ChildPlanHandle, ws: WebSocket): void {\n if (ws.readyState !== ws.OPEN) return;\n const key = keyOf(rootId, childId);\n const view = child.view();\n ws.send(JSON.stringify({ type: 'connected', sessionId: childId }));\n ws.send(JSON.stringify({\n type: 'run_snapshot', sessionId: childId, view: view.run, approvals: [], ...this.position(rootId, childId),\n } satisfies RunSnapshotFrame));\n if (view.plannerCompaction) ws.send(JSON.stringify(view.plannerCompaction satisfies SessionFrame));\n const watching = this.watched.get(key);\n if (watching) {\n watching.sockets.add(ws);\n return;\n }\n const sockets = new Set([ws]);\n this.watched.set(key, { sockets, stop: child.watch((frame) => this.send(key, sockets, frame)) });\n }\n\n leave(rootId: string, childId: string, ws: WebSocket): void {\n const key = keyOf(rootId, childId);\n const watching = this.watched.get(key);\n if (!watching) return;\n watching.sockets.delete(ws);\n if (watching.sockets.size === 0) this.drop(key, watching);\n }\n\n position(rootId: string, childId: string): StreamStamp {\n return { stream: this.stream, seq: this.sequence.get(keyOf(rootId, childId)) ?? 0 };\n }\n\n closeRoot(rootId: string, code: number): void {\n for (const [key, watching] of this.watched) {\n if (!key.startsWith(keyOf(rootId, ''))) continue;\n this.drop(key, watching);\n for (const ws of watching.sockets) {\n if (ws.readyState === ws.OPEN) ws.close(code, 'Child plan closed');\n }\n }\n }\n\n private send(key: string, sockets: Set<WebSocket>, frame: ChildFrame): void {\n const seq = (this.sequence.get(key) ?? 0) + 1;\n this.sequence.set(key, seq);\n const payload = JSON.stringify({ ...frame, stream: this.stream, seq } satisfies SessionFrame);\n for (const ws of sockets) {\n if (ws.readyState === ws.OPEN) ws.send(payload);\n }\n }\n\n private drop(key: string, watching: Watched): void {\n watching.stop();\n this.watched.delete(key);\n }\n}\n\nconst keyOf = (rootId: string, childId: string) => `${rootId}\\0${childId}`;\n","import { type PlannerBackendId, BaseConfig, DEFAULT_RUNNERS, defaultEnabledRunners, isApiProvider, normalizeGeminiModel } from '@ordewell/core';\nimport type { ConfiguredPlanner, ProviderModelLists, ResolvedPlanner } from '@ordewell/core';\n\nexport interface PlannerPick {\n model: string;\n provider: PlannerBackendId;\n}\n\ninterface WebConfigOpts {\n enabledRunners?: string[];\n /**\n * The lists that route a model id to its vendor. A function is read on every\n * resolution, so a long-lived config (a session's) never routes on lists its\n * owner has since dropped for a removed key.\n */\n providerModelLists?: ProviderModelLists | (() => ProviderModelLists | undefined);\n modelOverride?: string;\n /** The model a settings write picked in this daemon and the planner it was for, read live; absent when none has. */\n pickedModel?: () => PlannerPick | undefined;\n /** The model ids a coding agent's discovery last listed, read live; empty while it is cold. */\n agentCatalog?: (provider: PlannerBackendId) => readonly string[];\n}\n\nexport class WebConfig extends BaseConfig {\n private _enabledRunnersOverride: string[] | undefined;\n private _providerModelLists: () => ProviderModelLists | undefined;\n private _modelOverride: string | undefined;\n private _pickedModel: () => PlannerPick | undefined;\n private _agentCatalog: (provider: PlannerBackendId) => readonly string[];\n\n constructor(opts?: WebConfigOpts) {\n super();\n this._enabledRunnersOverride = opts?.enabledRunners;\n const lists = opts?.providerModelLists;\n this._providerModelLists = typeof lists === 'function' ? lists : () => lists;\n this._modelOverride = opts?.modelOverride;\n this._pickedModel = opts?.pickedModel ?? (() => undefined);\n this._agentCatalog = opts?.agentCatalog ?? (() => []);\n }\n\n protected agentCatalog(provider: PlannerBackendId): readonly string[] {\n return this._agentCatalog(provider);\n }\n\n setProviderModelLists(lists: ProviderModelLists): void {\n this._providerModelLists = () => lists;\n }\n\n /**\n * Read live, not fixed at construction: a session's WebConfig lives for the\n * whole session while /planner and /key (or the headless `ordewell model`)\n * mutate process.env under it. `routedProvider` keeps that cheap.\n */\n get planner(): ResolvedPlanner {\n return this.resolvePlanner({ ...this.configuredPlanner(), override: this._modelOverride }, this._providerModelLists());\n }\n\n /**\n * What the daemon inherited at startup, or what a settings write has set\n * since; the model counts as picked only while it is the one a write picked.\n */\n private configuredPlanner(): ConfiguredPlanner {\n const model = process.env.ORCHESTRATOR_MODEL || '';\n const pick = this._pickedModel();\n return { model, effort: process.env.ORDEWELL_PLANNER_EFFORT || '', pickedFor: pick?.model === model ? pick.provider : undefined };\n }\n\n get orchestratorModel(): string {\n return this.planner.model;\n }\n\n get aiProvider(): PlannerBackendId {\n return this.planner.provider;\n }\n\n get plannerThinkingEffort(): string | undefined {\n return this.planner.effort || undefined;\n }\n\n get apiKey(): string {\n const provider = this.aiProvider;\n return isApiProvider(provider) ? this.getProviderApiKey(provider) : '';\n }\n\n get planningModel(): string {\n const model = this.plannerChoiceFor(this.aiProvider, this.configuredPlanner()).model;\n return this.aiProvider === 'google' ? normalizeGeminiModel(process.env.GEMINI_MODEL || model) : model;\n }\n\n get enabledRunners(): string[] {\n if (this._enabledRunnersOverride) return this._enabledRunnersOverride;\n\n const envRunners = process.env.ORDEWELL_ENABLED_RUNNERS;\n if (envRunners) {\n const parsed = envRunners.split(',').map((s) => s.trim()).filter(Boolean);\n if (parsed.length > 0) return parsed;\n }\n\n // The per-runner toggles that predate ORDEWELL_ENABLED_RUNNERS: three fixed\n // variables, named by runner id on purpose; a newer runner is enabled\n // through the list above. Only a toggle that is set is a choice: with none,\n // claude-code's default-on toggle would hide a Codex- or OpenCode-only host.\n const toggles = ['ORDEWELL_CLAUDE_CODE_ENABLED', 'ORDEWELL_CODEX_ENABLED', 'ORDEWELL_OPENCODE_ENABLED'];\n if (toggles.every((name) => process.env[name] === undefined)) return defaultEnabledRunners();\n const out: string[] = [];\n if (process.env.ORDEWELL_CLAUDE_CODE_ENABLED !== 'false' && process.env.ORDEWELL_CLAUDE_CODE_ENABLED !== '0') {\n out.push('claude-code');\n }\n if (process.env.ORDEWELL_CODEX_ENABLED === 'true' || process.env.ORDEWELL_CODEX_ENABLED === '1') {\n out.push('codex');\n }\n if (process.env.ORDEWELL_OPENCODE_ENABLED === 'true' || process.env.ORDEWELL_OPENCODE_ENABLED === '1') {\n out.push('opencode');\n }\n return out.length > 0 ? out : [...DEFAULT_RUNNERS];\n }\n\n}\n","import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { isSea, type SeaDeps } from '@ordewell/core';\n\nexport interface WorkspaceScannerDeps {\n fsModule: typeof fs;\n pathModule: typeof path;\n cwd: string;\n home: string;\n /** A folder never to list; undefined lists every one found. */\n projectDir: string | undefined;\n}\n\nexport function scanWorkspacesImpl(deps: WorkspaceScannerDeps): string[] {\n const { fsModule, pathModule, cwd, home, projectDir } = deps;\n const paths = new Set<string>();\n const searchRoots = [\n cwd,\n home,\n pathModule.join(home, 'projects'),\n pathModule.join(home, 'dev'),\n pathModule.join(home, 'code'),\n pathModule.join(home, 'src'),\n pathModule.join(home, 'Desktop'),\n pathModule.join(home, 'Documents'),\n ];\n for (const root of searchRoots) {\n try {\n if (fsModule.existsSync(pathModule.join(root, '.ordewell'))) paths.add(root);\n const entries = fsModule.readdirSync(root, { withFileTypes: true }).filter(e => e.isDirectory());\n for (const e of entries.slice(0, 50)) {\n const sub = pathModule.join(root, e.name);\n if (fsModule.existsSync(pathModule.join(sub, '.ordewell'))) paths.add(sub);\n }\n } catch { /* empty */ }\n }\n const hidden = projectDir === undefined ? undefined : pathModule.resolve(projectDir);\n return [...paths].filter(p => p !== hidden).sort();\n}\n\nexport function scanWorkspaces(sea: SeaDeps = {}): string[] {\n return scanWorkspacesImpl({\n fsModule: fs,\n pathModule: path,\n cwd: process.cwd(),\n // Not HOME, which Windows does not set: os.homedir() reads USERPROFILE there.\n home: os.homedir(),\n // Four up from dist/server/ is the root of an Ordewell source checkout,\n // whose own `.ordewell/` (its committed skills) is no workspace of the\n // user's. The binary has no checkout: its `__dirname` is the executable's\n // folder, and four up from there could be the home or a projects folder\n // that does hold one, so nothing is hidden (ADR-0065 C2).\n projectDir: isSea(sea) ? undefined : path.resolve(__dirname, '..', '..', '..', '..'),\n });\n}\n","import { execFile } from 'child_process';\n\nexport interface ExecResult {\n stdout: string;\n stderr: string;\n code: number | null;\n /** The child was killed at the call's time limit, rather than exiting on its own. */\n timedOut: boolean;\n /** The signal that ended the child, if one did. */\n signal: NodeJS.Signals | null;\n}\n\n/**\n * Cap on a single child's buffered output. Above this, Node kills the child\n * and invokes the callback with `err.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'`\n * — a string, so the coercion below maps it to `1` (see `run`).\n */\nexport const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;\n\n/** How long a sealed run's output may trail its exit. */\nconst SEALED_OUTPUT_GRACE_MS = 1_000;\n\n/**\n * The single primitive every search/inspection adapter in this package is\n * built on: spawn a child, never reject. Kept in its own module so the\n * contract that the planner depends on — synchronous spawn failures degrade\n * to a failed tool call, never a rejected promise that aborts the whole\n * planner turn — can be pinned by a focused test rather than exercised only\n * incidentally through the public adapter API.\n *\n * Node hands only ENOENT/EAGAIN/EMFILE/ENFILE from spawn(2) to the\n * callback; every other errno — ENOTDIR for a `cwd` that is a file, EACCES\n * for one it cannot enter — is thrown synchronously. Thrown in here that\n * rejects the promise, and no caller of `run` catches, so a single bad\n * search argument aborted the entire planner turn as \"Plan generation\n * failed: spawn ENOTDIR\". A failed spawn is a failed tool call, never a\n * failed plan.\n */\nexport function run(\n file: string,\n args: string[],\n opts: { cwd?: string; timeout: number; shell?: boolean; env?: NodeJS.ProcessEnv; signal?: AbortSignal; sealed?: boolean },\n): Promise<ExecResult> {\n return new Promise((resolve) => {\n try {\n const child = execFile(file, args, {\n cwd: opts.cwd,\n timeout: opts.timeout,\n maxBuffer: MAX_OUTPUT_BYTES,\n encoding: 'utf8',\n shell: opts.shell,\n env: opts.env,\n // A sealed run's wall-time limit is a kill, not a request it may trap\n // (ADR-0036 S1); the sandbox takes the processes it started down with it.\n ...(opts.sealed ? { killSignal: 'SIGKILL' as const } : {}),\n // Node kills the child when this aborts, and calls back with an\n // ABORT_ERR — which lands on the `code: 1` branch below, i.e. a\n // failed tool call, exactly like any other command that did not\n // finish. Stopping the planner must not leave a research `bash`\n // running out its own timeout on the server.\n signal: opts.signal,\n }, (err, stdout, stderr) => {\n const code = err && typeof (err as { code?: unknown }).code === 'number' ? (err as { code: number }).code : err ? 1 : 0;\n // Only Node's own timeout sets `killed`; an abort and a stdout overflow do not, so this names the limit exactly.\n resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code, timedOut: err?.killed === true, signal: err?.signal ?? null });\n });\n // A process that left a sealed run's process group can hold its output\n // open after the run has ended: the result is what arrived by then.\n if (opts.sealed) child.once('exit', () => setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, SEALED_OUTPUT_GRACE_MS).unref());\n } catch (err) {\n // `code: null` rather than 1 on purpose: the search adapters read 0 and 1\n // as \"ran, possibly no matches\", so a 1 here would report a confident\n // \"No matches found.\" for a search that never executed.\n resolve({ stdout: '', stderr: (err as Error).message, code: null, timedOut: false, signal: null });\n }\n });\n}","import {\n BaseFileSystem,\n buildGrepArgs,\n buildGlobArgs,\n buildFallbackGrepArgs,\n GREP_PCRE_PROBE_ARGS,\n grepRegexFromProbe,\n listTree,\n type GrepRegex,\n filterFallbackByAnchoredInclude,\n applyHeadLimit,\n formatSearchOutput,\n headLines,\n researchToolsPath,\n withPath,\n SEARCH_EXCLUSIONS,\n STOPPED_TOOL_RESULT,\n type GrepOptions,\n type ReadFileOpts,\n type ShellLaunch,\n type ToolOutcome,\n} from '@ordewell/core';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { run } from './run';\n\n/**\n * Everything here is async. It used to be `execSync`/`readFileSync`, which on\n * the web server blocked the entire Node event loop: one session running\n * `tree -L 4` over a monorepo stalled every other session's WebSocket\n * streaming, HTTP API, and plan-token delivery. It also makes the parallel\n * tool-round pre-pass in BaseAiService pointless, since concurrent calls into\n * a synchronous adapter still serialize.\n */\n\nconst SEARCH_TIMEOUT_MS = 20_000;\n/** Generous, because an approved `bash` call may legitimately be a test suite. */\nconst BASH_TIMEOUT_MS = 120_000;\n\nexport class PoolFileSystem extends BaseFileSystem {\n constructor(private workspaceRoot: string) { super(); }\n getWorkspaceRoot(): string { return this.workspaceRoot; }\n rootedAt(workspace: string): PoolFileSystem { return new PoolFileSystem(workspace); }\n\n /**\n * PATH for the search subprocesses. `execFile` starts them with no shell, so\n * on a Windows box whose POSIX tools live in the Git tree (`grep.exe` beside\n * the research shell) they are only resolvable with that directory prepended.\n * Identity on POSIX, where `utilsDir` is null. Kept in step with\n * VsCodeFileSystem.searchEnv.\n */\n private searchEnv(): NodeJS.ProcessEnv | undefined {\n const resolved = researchToolsPath(this.researchShell, process.env.PATH);\n // `withPath`, not a `PATH:` spread: on Windows the spread of `process.env`\n // carries `Path`, so adding `PATH` hands the child two and lets the OS pick.\n return resolved === (process.env.PATH ?? '') ? undefined : withPath(process.env, resolved);\n }\n\n private grepRegex: Promise<GrepRegex> | null = null;\n private fallbackGrepRegex(): Promise<GrepRegex> {\n this.grepRegex ??= run('grep', GREP_PCRE_PROBE_ARGS, { timeout: 5_000, env: this.searchEnv() })\n .then((r) => grepRegexFromProbe(r.code))\n .catch(() => 'ere' as const);\n return this.grepRegex;\n }\n\n private rgAvailable: Promise<boolean> | null = null;\n private hasRg(): Promise<boolean> {\n this.rgAvailable ??= run('rg', ['--version'], { timeout: 5_000, env: this.searchEnv() }).then((r) => r.code === 0).catch(() => false);\n return this.rgAvailable;\n }\n\n protected async readFileImpl(absPath: string, opts?: ReadFileOpts): Promise<ToolOutcome> {\n try {\n const stat = await fs.stat(absPath);\n if (!stat.isFile()) return { success: false, output: `Not a file: ${absPath}`, truncated: false };\n\n // Hard file-size cap — return an actionable error so the model switches to grep\n const maxBytes = opts?.maxBytes ?? 1024;\n if (stat.size > maxBytes * 1024) {\n const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);\n return {\n success: true,\n output: `File too large (${sizeMB} MB). Maximum is ${maxBytes} KB. Use grep to search for specific patterns instead.`,\n truncated: false,\n };\n }\n\n const content = await fs.readFile(absPath, 'utf8');\n const allLines = content.split('\\n');\n // Discard the empty element from a trailing newline\n if (allLines.length > 0 && allLines[allLines.length - 1] === '') allLines.pop();\n const totalLines = allLines.length;\n\n const startLine = opts?.offset ?? 0;\n const maxLines = opts?.limit ?? 2000;\n\n if (startLine >= totalLines) return { success: true, output: '', truncated: false };\n\n const selectedLines = allLines.slice(startLine, startLine + maxLines);\n const truncated = (startLine + maxLines) < totalLines;\n\n // Right-align line numbers so columns stay aligned across calls\n const lineWidth = String(totalLines).length;\n let output = selectedLines.map((line, i) => {\n const lineNum = String(startLine + i + 1).padStart(lineWidth);\n return `${lineNum}|${line}`;\n }).join('\\n');\n\n // Actionable hint so the model knows how to continue\n if (truncated) {\n const nextOffset = startLine + maxLines;\n output += `\\n\\n(File has more lines — use offset=${nextOffset} to read beyond line ${nextOffset})\\n`;\n }\n\n return { success: true, output, truncated };\n } catch (err) {\n return { success: false, output: `Error reading ${absPath}: ${(err as Error).message}`, truncated: false };\n }\n }\n\n protected async globImpl(pattern: string, absRoot: string, headLimit: number): Promise<ToolOutcome> {\n if (await this.hasRg()) {\n // ripgrep resolves a `--glob` pattern that contains a `/` against its own\n // cwd, not the `--` search path — without this, a daemon started outside\n // the workspace silently drops every anchored pattern (\"src/**/*\") to a\n // false \"No files matched.\".\n const { root, anchor } = await this.searchTarget(absRoot);\n const result = await run('rg', buildGlobArgs(pattern, root), { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() });\n // rg exits 1 for \"no files matched\", which is a valid empty answer.\n if (result.code !== 0 && result.code !== 1 && !result.stdout) {\n return { success: false, output: `Glob failed: ${result.stderr.trim() || 'ripgrep error'}`, truncated: false };\n }\n const capped = applyHeadLimit(result.stdout, headLimit);\n return {\n success: true,\n output: formatSearchOutput(capped, anchor, { emptyMessage: 'No files matched.', hint: 'Narrow the pattern.' }),\n truncated: capped.truncated,\n };\n }\n\n // `find -path` treats `*` as crossing `/`, so `**` is not recursive there.\n // Translating to `-name` on the basename keeps the common cases honest\n // rather than silently returning a different result set than ripgrep would.\n const basename = pattern.split('/').pop() || pattern;\n const excludeArgs = SEARCH_EXCLUSIONS.flatMap((dir) => ['-not', '-path', `*/${dir}/*`]);\n const { root: findRoot } = await this.searchTarget(absRoot);\n const result = await run('find', [findRoot, '-type', 'f', '-name', basename, ...excludeArgs], { timeout: SEARCH_TIMEOUT_MS, env: this.searchEnv() });\n if (result.code !== 0 && !result.stdout) {\n return { success: false, output: `Glob failed: ${result.stderr.trim() || 'find error'}`, truncated: false };\n }\n const capped = applyHeadLimit(result.stdout, headLimit);\n return {\n success: true,\n output: formatSearchOutput(capped, findRoot, { emptyMessage: 'No files matched.' }),\n truncated: capped.truncated,\n };\n }\n\n /**\n * The search path and a directory to anchor it in. `cwd` exists only so\n * anchored `--glob`/`--include` patterns resolve against the search root, and\n * spawn(2) rejects a `cwd` that is a file with ENOTDIR.\n *\n * `grep`'s `path` is documented as a directory, but the tool description\n * tells the model to survey with output_mode=\"files\" and then re-run \"on a\n * narrower path\" — and what that survey hands back are files. rg and grep\n * both search a single file happily, so anchor at the parent rather than\n * failing a legitimately file-scoped search.\n *\n * The root is resolved through symlinks because the OS reports a child's cwd\n * as the resolved path (macOS tmpdir is `/var/...` -> `/private/var/...`),\n * and ripgrep matches an anchored glob against the search path as written: a\n * root that goes through a link never matches and yields a false empty\n * result. Result rows then carry the resolved prefix, which is why callers\n * strip `anchor` rather than the path they were handed.\n */\n private async searchTarget(absRoot: string): Promise<{ root: string; anchor: string }> {\n try {\n const root = await fs.realpath(absRoot);\n return { root, anchor: (await fs.stat(root)).isDirectory() ? root : path.dirname(root) };\n } catch {\n return { root: absRoot, anchor: absRoot };\n }\n }\n\n protected async grepImpl(pattern: string, absRoot: string, opts: GrepOptions): Promise<ToolOutcome> {\n const headLimit = opts.headLimit ?? 100;\n const useRg = await this.hasRg();\n // Same anchored-glob-vs-cwd hazard as globImpl: an `include` filter with a\n // `/` in it would otherwise resolve against the daemon's cwd, not absRoot.\n const { root, anchor } = await this.searchTarget(absRoot);\n // GNU grep's `--include` only matches a basename, so an anchored pattern\n // like `subdir/*.txt` never matches there — strip it from the grep call\n // and filter matches by relative path afterward instead.\n const anchoredInclude = !useRg && opts.include?.includes('/') ? opts.include : undefined;\n const result = useRg\n ? await run('rg', buildGrepArgs(pattern, opts, root).args, { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() })\n : await run('grep', buildFallbackGrepArgs(pattern, anchoredInclude ? { ...opts, include: undefined } : opts, root, await this.fallbackGrepRegex()), { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() });\n\n // Exit 1 is \"no matches\" for both tools — a successful search with an empty\n // result, not a failure. Anything else with no stdout is a real error.\n if (result.code !== 0 && result.code !== 1 && !result.stdout) {\n return { success: false, output: `Search failed: ${result.stderr.trim() || 'search error'}`, truncated: false };\n }\n\n const filteredStdout = anchoredInclude\n ? filterFallbackByAnchoredInclude(result.stdout, anchoredInclude, anchor, opts.outputMode)\n : result.stdout;\n const capped = applyHeadLimit(filteredStdout, headLimit);\n const hint = opts.outputMode === 'content'\n ? 'Re-run with output_mode=\"files\" to see the full breadth, or narrow with include/path.'\n : 'Narrow with include/path.';\n return {\n success: true,\n output: formatSearchOutput(capped, anchor, { emptyMessage: 'No matches found.', hint }),\n truncated: capped.truncated,\n };\n }\n\n protected async listDirImpl(absPath: string, depth: number): Promise<ToolOutcome> {\n try {\n return await listTree(absPath, depth, async (abs) =>\n (await fs.readdir(abs, { withFileTypes: true })).map((e) => ({ name: e.name, directory: e.isDirectory() })));\n } catch (err) {\n return { success: false, output: `Error listing ${absPath}: ${(err as Error).message}`, truncated: false };\n }\n }\n\n protected async execBashImpl(command: string, shell: ShellLaunch, signal: AbortSignal | undefined, cwd: string): Promise<ToolOutcome> {\n // `shell: true` is required now that approved commands may legitimately\n // contain pipes; the tier classifier in core (not string filtering here)\n // is what decides whether this command was allowed to reach the shell.\n //\n // `file: null` is that host default, unchanged on POSIX where no sandbox\n // runs. A resolved file is the sandbox launcher around the POSIX shell, or\n // the POSIX shell found on a Windows box: either way the command goes last,\n // in the dialect `BaseFileSystem` classified it under.\n const { file, args, env, wallTimeMs } = shell;\n const result = file === null\n ? await run(command, [], { cwd, timeout: BASH_TIMEOUT_MS, shell: true, env, signal })\n : await run(file, [...args, command], { cwd, timeout: wallTimeMs ?? BASH_TIMEOUT_MS, env, signal, sealed: wallTimeMs !== undefined });\n const out = (result.stdout || '').trim();\n const err = (result.stderr || '').trim();\n\n // A stopped turn reports as a stop, not as a mysterious non-zero exit: the\n // child was killed on purpose and there is nothing here to diagnose.\n if (signal?.aborted) return { success: false, output: STOPPED_TOOL_RESULT, truncated: false };\n\n if (result.code !== 0) {\n const detail = err || out || `exited with code ${result.code}`;\n // A failing command is still research: the model asked to diagnose, and\n // the failure output is usually the answer. Report it, do not swallow it.\n // Whole lines only: executeTool redacts what this returns, and a cut inside\n // a line can leave a credential's value with no name to recognise it by.\n return { success: false, output: `Command exited ${result.code}:\\n${headLines(detail, 20_000)}`, truncated: detail.length > 20_000, ...(result.timedOut ? { timedOut: true } : {}), ...(result.signal ? { signal: result.signal } : {}) };\n }\n\n const combined = err ? `${out}\\n[stderr]\\n${err}` : out;\n return { success: true, output: combined || '(no output)', truncated: combined.length > 20_000 };\n }\n}\n","import type { IRunner, IRunnerSession, RunnerSpawnOptions } from '@ordewell/core';\nimport type { SessionBroadcaster } from '@ordewell/core';\n\nexport class PoolAwareRunner implements IRunner {\n /**\n * Sessions this plan spawned. The inner runner is shared by every plan in\n * the pool, so \"stop everything\" and \"how many are running\" must be\n * answered from this set, never delegated — delegating would let one plan's\n * /stop kill another plan's tasks.\n */\n private owned = new Set<string>();\n\n constructor(\n private sessionId: string,\n private broadcast: SessionBroadcaster,\n private inner: IRunner,\n ) {}\n\n get activeCount(): number { return this.owned.size; }\n\n async spawn(opts: RunnerSpawnOptions): Promise<IRunnerSession> {\n const session = await this.inner.spawn({ ...opts, planSessionId: this.sessionId });\n this.owned.add(session.id);\n session.onExit(() => this.owned.delete(session.id));\n this.broadcast({ type: 'task_started', taskId: opts.taskId, order: opts.order ?? 0, title: opts.title ?? '', runner: opts.runner, modelId: opts.modelId });\n session.onOutput((text) => {\n this.broadcast({ type: 'task_output', taskId: opts.taskId, text });\n });\n return session;\n }\n\n stop(sessionId: string): Promise<void> {\n this.owned.delete(sessionId);\n return this.inner.stop(sessionId);\n }\n\n stopAll(): void {\n for (const id of this.owned) void this.inner.stop(id);\n this.owned.clear();\n }\n}\n","import { spawn as nodeSpawn } from 'child_process';\nimport { randomUUID } from 'crypto';\nimport { resolve } from 'path';\nimport { WebSocket } from 'ws';\nimport {\n AccountLimitMonitor,\n claudeAccountLimitCollector,\n codexAccountLimitCollector,\n openCodeGoAccountLimitCollector,\n assignedRunnerOf,\n flattenTasks,\n type AccountLimitCollector,\n type AccountLimitsFrame,\n Session,\n createSession,\n type ConversationCompaction,\n type ChildTreeFrame,\n type ConversationFork,\n type RunView,\n type SessionMessage,\n type SessionNotice,\n type SessionRuntimeSettings,\n type SessionFrame,\n type ApprovalRequestMessage,\n type StreamStamp,\n ModelResolver,\n RunnerRegistry,\n removedPluginNotice,\n RunnerInstallation,\n listSessions,\n loadSession,\n appendUserAction,\n processLeaseHost,\n savedRunLooksLive,\n deleteSession,\n reclaimContainers,\n changeContainers,\n containerStatus,\n type ContainerChange,\n type ContainerChangeResponse,\n type ContainerStatus,\n type DockerCli,\n SettingsService,\n sessionRuntimeSettings,\n type GlobalRunSettings,\n type PlanState,\n type LegacyPlanState,\n migratePlanState,\n type RunnerId,\n type DiscoveredModel,\n type ModelsResponse,\n type RunnersResponse,\n type SettingsResponse,\n type SettingsUpdateResponse,\n SessionNotFoundError,\n runnerModesFrom,\n configuredProviders,\n assertWorkspaceExists,\n assertWorkspaceIsProject,\n WorkspaceNotAProjectError,\n ensureStateDirIgnored,\n runnerForProvider,\n PlannerModelMemory,\n selectPlanner,\n admitSettingsEnv,\n PROVIDER_CREDENTIAL_ENV,\n forgetSignedOutRunnerAuth,\n type PlannerBackendId,\n type PlannerModelCandidate,\n type PlannerSelectionChange,\n type PlannerSelectionCurrent,\n StructuredRunner,\n CodexSandboxAvailability,\n detectInstalledPlanner,\n installedPlannerAnswered,\n PlannerNotReadyError,\n PlannerTurnDiscardedError,\n PlannerTurnStoppedError,\n type LeaseHost,\n workspaceEnvOf,\n recordedRunnerAuth,\n createIsolationPreview,\n createWorktreeIsolation,\n discardChildRuns,\n type IIsolationPreview,\n type IsolationPreview,\n} from '@ordewell/core';\nimport { ChildStreams } from './childStreams';\nimport { WebConfig, type PlannerPick } from '../adapters/WebConfig';\nimport { scanWorkspaces as scanWorkspacesImpl } from '../utils/workspaceScanner';\nimport { PoolFileSystem } from '../adapters/PoolFileSystem';\nimport { PoolAwareRunner } from '../adapters/PoolAwareRunner';\nimport type { ApprovalAnswer, RunnerRegistry as CoreRunnerRegistry, IRunner } from '@ordewell/core';\n\n/** A fork the pool has adopted: addressable at once, its plan read back from the file it was written to. */\nexport interface AdoptedFork {\n sessionId: string;\n goal: string;\n plan: LegacyPlanState;\n}\n\n/**\n * The installation checks a host supplies the pool. `refresh` is optional so a\n * test may hand in only the two probes; the real `RunnerInstallation` always\n * has it, and a refresh then re-probes a CLI installed since the last look.\n */\ntype RunnerInstall = Pick<RunnerInstallation, 'filterInstalled' | 'plannerUsability' | 'runnerUsability'> & Partial<Pick<RunnerInstallation, 'refresh'>>;\n\nexport interface OrchestratorPoolDeps {\n /** Inject acquisition boundaries without reading real accounts in host lifecycle tests. */\n accountLimitCollectors?: (workspace: string) => readonly AccountLimitCollector[];\n /**\n * Where every plan's tasks run (ADR-0018), shared across sessions behind\n * each plan's `PoolAwareRunner`. Defaulted to a real one; tests inject a fake.\n */\n runner?: IRunner;\n /**\n * Overrides the pool's own `ModelResolver`. Left undefined, behavior is\n * unchanged; tests inject one built with fake exec/fetch impls so a\n * planner-switch catalog lookup can be seeded without spawning real CLIs.\n */\n modelResolver?: ModelResolver;\n /** Overrides the docker CLI a containers status or change asks; tests inject one so no engine is needed. */\n dockerCli?: DockerCli;\n /** Overrides the pool's Codex sandbox probe; tests inject one so no real `codex` is started. */\n codexSandbox?: Pick<CodexSandboxAvailability, 'ensure' | 'refresh'>;\n /** Overrides the pool's installation checks; tests inject one so no real agent binary is asked. */\n runnerInstallation?: RunnerInstall;\n /**\n * The host whose leases the pool's sessions hold (ADR-0049); this process's\n * unless a test runs two pools as two hosts.\n */\n leaseHost?: LeaseHost;\n /**\n * The read-only repository look a surface shows before any run. Defaulted to\n * one built from the daemon's config; tests inject a fake so no real git runs.\n */\n isolationPreview?: IIsolationPreview;\n}\n\nexport class OrchestratorPool {\n // A daemon serves several workspaces; login selection must never follow\n // whichever session was opened most recently (ADR-0051).\n private readonly sessionWorkspaces = new Map<string, string>();\n private readonly accountLimits = new Map<string, AccountLimitMonitor>();\n private readonly accountLimitCollectors: (workspace: string) => readonly AccountLimitCollector[];\n private limitsRevision = 0;\n private sessions = new Map<string, Session>();\n private clients = new Map<string, Set<WebSocket>>();\n /**\n * This process's broadcast numbering (see `StreamStamp`), per session id\n * rather than per Session object: a session replaced under the same id\n * keeps counting up, so a client never mistakes its first broadcast for one\n * of the old session's it already showed.\n */\n private readonly stream = randomUUID();\n private sequence = new Map<string, number>();\n private readonly childStreams = new ChildStreams(this.stream);\n private registry: CoreRunnerRegistry = new RunnerRegistry();\n private modelResolver: ModelResolver;\n /** A host that supplied its own resolver answers for every workspace, as a supplied probe does. */\n private suppliedModelResolver: boolean;\n private runnerInstallation: RunnerInstall;\n /**\n * A host that supplied its own probe (a test, or a surface that owns one).\n * Everything else asks {@link installationFor}, which keys a real probe by\n * the workspace whose account it is judging (ADR-0016).\n */\n private suppliedRunnerInstallation: RunnerInstall | undefined;\n private workspaceInstallations = new Map<string, RunnerInstall>();\n private cachedProviderLists: Record<string, string[]> | undefined;\n private settingsService = new SettingsService();\n private plannerModelMemory = new PlannerModelMemory(this.settingsService);\n /**\n * The model a settings write picked in this daemon, and the workspace it was\n * picked in. The environment's model is otherwise inherited, and an agent\n * planning only because detection found it does not plan with an inherited\n * model it cannot be shown to run. The pick is that workspace's: another\n * may name another account, whose catalog judges the model afresh.\n */\n private pickedModel: (PlannerPick & { workspace: string }) | undefined;\n /**\n * The last planner write a route made, so each lands after the ones made\n * before it: a switch still waiting for its catalog must not write over a\n * pick made while it waited (ADR-0040).\n */\n private plannerWrites: Promise<unknown> = Promise.resolve();\n private runner: IRunner;\n /** One probe per daemon, asked again whenever the runner list is refreshed (ADR-0033). */\n private codexSandbox: Pick<CodexSandboxAvailability, 'ensure' | 'refresh'>;\n private readonly leaseHost: LeaseHost | undefined;\n private readonly isolationPreview: IIsolationPreview;\n private readonly suppliedDockerCli: DockerCli | undefined;\n\n constructor(deps: OrchestratorPoolDeps = {}) {\n const pluginNotice = removedPluginNotice();\n if (pluginNotice) console.warn(pluginNotice);\n this.suppliedDockerCli = deps.dockerCli;\n this.runner = deps.runner ?? new StructuredRunner();\n // The login probe must ask the account the planner will use (ADR-0016).\n // This installation is the daemon's own cwd for detection; a runner list\n // request naming a workspace is judged by that workspace's own probe.\n this.suppliedRunnerInstallation = deps.runnerInstallation;\n this.runnerInstallation = deps.runnerInstallation\n ?? new RunnerInstallation(this.registry, undefined, undefined, {\n env: () => workspaceEnvOf(process.cwd()),\n workspace: () => process.cwd(),\n });\n // Read from the account the runners use, as the login probe above is.\n this.suppliedModelResolver = deps.modelResolver !== undefined;\n this.modelResolver = deps.modelResolver ?? new ModelResolver(this.registry, new WebConfig(), {\n env: async () => ({ ...process.env, ...(await workspaceEnvOf(process.cwd())) }),\n });\n this.codexSandbox = deps.codexSandbox\n ?? new CodexSandboxAvailability(this.registry, { spawn: nodeSpawn, fetch: globalThis.fetch }, { cwd: process.cwd(), env: process.env });\n this.leaseHost = deps.leaseHost;\n // What worktreeIsolation and workspaceRepos mean here, which is the config\n // the sessions plan with: the daemon's own environment, not a guess from\n // the workspace a request happens to name.\n this.isolationPreview = deps.isolationPreview ?? createIsolationPreview({ config: new WebConfig() });\n this.accountLimitCollectors = deps.accountLimitCollectors ?? ((workspace) => {\n const workspaceRoot = () => workspace;\n const isInstalled = (runner: string) => async () => (await this.runnerInstallation.filterInstalled([runner])).includes(runner);\n const server = this.registry.getManifest('codex')?.modelDiscovery.appServer;\n return [\n claudeAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('claude-code') }),\n codexAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('codex'), command: server?.command, args: server?.args }),\n openCodeGoAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('opencode') }),\n ];\n });\n }\n\n /**\n * Not awaited: planning must start at once, and the daemon already warms the\n * probe at startup through the catalog. This only covers a daemon that was\n * asked to plan before that finished.\n */\n private warmCodexSandbox(): void {\n this.codexSandbox.ensure().catch((err) => console.error(`[web] codex sandbox probe failed: ${err instanceof Error ? err.message : err}`));\n }\n\n /**\n * Find the coding agent that plans when the user has chosen no planner and\n * set no vendor key (ADR-0009), for the daemon to start as it starts. Every\n * planner turn waits on it, so a goal typed the instant the TUI opens\n * does not plan with an openrouter key nobody set.\n */\n detectInstalledPlanner(): Promise<PlannerBackendId | null> {\n return detectInstalledPlanner(this.runnerInstallation);\n }\n\n /**\n * A read-only look at the repositories and branches a run would isolate in\n * `workspace`. Free of side effects on purpose: a first screen may ask before\n * any plan or run exists, and asking must not create one.\n */\n previewIsolation(workspace: string): Promise<IsolationPreview> {\n assertWorkspaceExists(workspace);\n return this.isolationPreview.preview(workspace);\n }\n\n /**\n * A new session's first planner turn. It waits for that probe at the\n * session's own planner gate, where a reply sent meanwhile queues behind\n * it, and a Stop or the session closing or being replaced ends the wait.\n */\n private async firstTurn<T>(sessionId: string, session: Session, turn: () => Promise<T>): Promise<T> {\n try {\n return await turn();\n } catch (err) {\n // Judged once the probe answered: a refused session is never left\n // addressable, as when it is judged before it is registered.\n if (err instanceof PlannerNotReadyError && this.sessions.get(sessionId) === session) this.destroy(sessionId);\n // Stopped before it opened, the session holds no conversation for a\n // reply to continue: for the client its goal was discarded.\n if (err instanceof PlannerTurnStoppedError && !session.planState) throw new PlannerTurnDiscardedError();\n throw err;\n }\n }\n\n subscribe(sessionId: string, ws: WebSocket): void {\n if (!this.clients.has(sessionId)) this.clients.set(sessionId, new Set());\n this.clients.get(sessionId)!.add(ws);\n this.connectAccountLimits(sessionId, ws);\n const session = this.sessions.get(sessionId);\n if (session) void this.tellTree(sessionId, session, [ws]);\n }\n\n unsubscribe(sessionId: string, ws: WebSocket): void {\n this.clients.get(sessionId)?.delete(ws);\n if (this.clients.get(sessionId)?.size === 0) this.clients.delete(sessionId);\n this.releaseUnusedAccountLimits();\n }\n\n private connectAccountLimits(sessionId: string, ws: WebSocket): void {\n const workspace = this.sessionWorkspaces.get(sessionId);\n if (!workspace) {\n this.sendAccountLimits(sessionId, ws, []);\n return;\n }\n let monitor = this.accountLimits.get(workspace);\n if (!monitor) {\n monitor = new AccountLimitMonitor({ collectors: this.accountLimitCollectors(workspace) });\n this.accountLimits.set(workspace, monitor);\n monitor.subscribe((limits) => {\n for (const [id, clients] of this.clients) {\n if (this.sessionWorkspaces.get(id) !== workspace) continue;\n for (const client of clients) this.sendAccountLimits(id, client, limits);\n }\n });\n }\n this.sendAccountLimits(sessionId, ws, monitor.snapshots());\n monitor.setForeground(true);\n monitor.surfaceConnected();\n }\n\n private sendAccountLimits(sessionId: string, ws: WebSocket, limits: AccountLimitsFrame['limits']): void {\n if (ws.readyState !== ws.OPEN) return;\n ws.send(JSON.stringify({ type: 'account_limits', sessionId, limits, stream: this.stream, revision: ++this.limitsRevision } satisfies AccountLimitsFrame));\n }\n\n private releaseUnusedAccountLimits(): void {\n for (const [workspace, monitor] of this.accountLimits) {\n if ([...this.clients.keys()].some((id) => this.sessionWorkspaces.get(id) === workspace)) continue;\n monitor.dispose();\n this.accountLimits.delete(workspace);\n }\n }\n\n private registerSession(sessionId: string, workspace: string, session: Session): void {\n this.sessions.set(sessionId, session);\n this.sessionWorkspaces.set(sessionId, workspace);\n for (const ws of this.clients.get(sessionId) ?? []) this.connectAccountLimits(sessionId, ws);\n session.children.onChange(() => void this.tellTree(sessionId, session));\n }\n\n /** The tree as it stands. A failed read tells nothing: the list route is where a surface hears why. */\n private async tellTree(sessionId: string, session: Session, sockets?: WebSocket[]): Promise<void> {\n const children = await session.children.list().catch(() => []);\n if (children.length === 0 || this.sessions.get(sessionId) !== session) return;\n const payload = JSON.stringify({ type: 'child_tree', sessionId, children } satisfies ChildTreeFrame);\n for (const ws of sockets ?? this.clients.get(sessionId) ?? []) {\n if (ws.readyState === ws.OPEN) ws.send(payload);\n }\n }\n\n /** False for a child this root does not hold, or a root no longer loaded (ADR-0055 D20). */\n async watchChild(rootId: string, childId: string, ws: WebSocket): Promise<boolean> {\n const session = this.sessions.get(rootId);\n const child = await session?.children.find(childId);\n if (!child || this.sessions.get(rootId) !== session) return false;\n this.childStreams.join(rootId, childId, child, ws);\n return true;\n }\n\n unwatchChild(rootId: string, childId: string, ws: WebSocket): void { this.childStreams.leave(rootId, childId, ws); }\n /** What a read of the child taken now accounts for on its socket. */\n childPosition(rootId: string, childId: string): StreamStamp { return this.childStreams.position(rootId, childId); }\n\n private broadcast(sessionId: string, msg: SessionMessage | SessionNotice): void {\n const workspace = this.sessionWorkspaces.get(sessionId);\n const monitor = workspace ? this.accountLimits.get(workspace) : undefined;\n if (msg.type === 'planner_usage') monitor?.invalidate();\n else if (msg.type === 'task_log' && msg.events.some((event) => event.type === 'turn_end')) {\n const task = flattenTasks(this.sessions.get(sessionId)?.planTasks ?? []).find((task) => task.id === msg.taskId);\n const runner = task && assignedRunnerOf(task);\n if (runner) monitor?.invalidate(runner);\n }\n const seq = (this.sequence.get(sessionId) ?? 0) + 1;\n this.sequence.set(sessionId, seq);\n const payload = JSON.stringify({ ...msg, stream: this.stream, seq } satisfies SessionFrame);\n for (const ws of this.clients.get(sessionId) ?? []) {\n if (ws.readyState === ws.OPEN) ws.send(payload);\n }\n }\n\n hasSession(sessionId: string): boolean { return this.sessions.has(sessionId); }\n\n /** The session open here under this id for this workspace, if any: an id names a session only within its workspace. */\n private heldHere(sessionId: string, workspace: string): Session | undefined {\n const held = this.sessionWorkspaces.get(sessionId);\n return held !== undefined && resolve(held) === resolve(workspace) ? this.sessions.get(sessionId) : undefined;\n }\n\n /**\n * Whether a session's run holds its landing branch (ADR-0062 G7): this\n * host's own word for a session open here; for one another live host holds,\n * that host's word in its lease record, or the saved record where the holder\n * says nothing; and for one nobody holds, nothing is at work.\n */\n userRunIsLive(sessionId: string, workspace: string, plan: LegacyPlanState): boolean {\n const session = this.heldHere(sessionId, workspace);\n if (session) return session.runIsLive;\n const held = (this.leaseHost ?? processLeaseHost()).peek(sessionId, workspace);\n return held !== null && (held.holder.runLive === true || savedRunLooksLive(plan));\n }\n\n /**\n * A user git action into the session's timeline (ADR-0062 G6): straight in\n * for a session open here, else left in its directory for whichever host\n * holds it, or next opens it, to fold (ADR-0049 L5).\n */\n recordUserAction(sessionId: string, workspace: string, text: string): void {\n const session = this.heldHere(sessionId, workspace);\n if (session?.planState) session.recordUserAction(text);\n else appendUserAction(sessionId, workspace, { text, at: new Date().toISOString() });\n }\n\n /** Answer an approval prompt, the planner's or a task runner's. False means the id was unknown or already settled. */\n resolveApproval(sessionId: string, approvalId: string, answer: ApprovalAnswer): boolean {\n return this.sessions.get(sessionId)?.resolveApproval(approvalId, answer) ?? false;\n }\n\n outstandingApprovals(sessionId: string) {\n return this.sessions.get(sessionId)?.outstandingApprovals() ?? [];\n }\n\n approvedScopes(sessionId: string): string[] {\n return this.sessions.get(sessionId)?.approvedScopes() ?? [];\n }\n isExecuting(sessionId: string): boolean { return this.sessions.get(sessionId)?.isExecuting ?? false; }\n /** Work under way in any session held here, which stopping this daemon would cut off: a run not settled, or a planner turn answering. */\n workLive(): boolean {\n for (const session of this.sessions.values()) {\n if (session.runIsLive || session.plannerTurnId !== undefined) return true;\n }\n return false;\n }\n getPlan(sessionId: string): LegacyPlanState | null { return this.sessions.get(sessionId)?.planState ?? null; }\n /**\n * The plan of a session this process is holding, straight from its store —\n * null for an id the pool never adopted. Reading it through the saved file\n * instead answers as if nothing were running.\n */\n getPlanState(sessionId: string): PlanState | null {\n return this.sessions.get(sessionId)?.currentPlanState ?? null;\n }\n getGoal(sessionId: string): string { return this.sessions.get(sessionId)?.currentGoal ?? ''; }\n /** Null for a session this process is not holding: there is no run to describe. */\n runSnapshot(sessionId: string): RunView | null { return this.sessions.get(sessionId)?.runSnapshot() ?? null; }\n /** The planner turn answering in a session this process holds, if one is. */\n plannerTurnId(sessionId: string): string | undefined { return this.sessions.get(sessionId)?.plannerTurnId; }\n /** The planner compaction running in a session this process holds, as its start was announced; it has no turn to name. */\n plannerCompaction(sessionId: string): ReturnType<Session['plannerCompaction']> { return this.sessions.get(sessionId)?.plannerCompaction(); }\n plannerDetection(sessionId: string): ReturnType<Session['plannerDetection']> | undefined { return this.sessions.get(sessionId)?.plannerDetection(); }\n /** The planner's approval requests still waiting, as they were announced. */\n announcedApprovals(sessionId: string): ApprovalRequestMessage[] { return this.sessions.get(sessionId)?.announcedApprovals() ?? []; }\n /** The last broadcast of the session so far: a snapshot taken now accounts for it and everything before. */\n streamPosition(sessionId: string): StreamStamp { return { stream: this.stream, seq: this.sequence.get(sessionId) ?? 0 }; }\n\n private runtimeSettings(): SessionRuntimeSettings {\n return sessionRuntimeSettings(this.settingsService.getAll());\n }\n\n private createSessionFor(sessionId: string, workspace: string, modelOverride?: string, options: { allowInit?: boolean } = {}): Session {\n // Rejected here rather than left to the planner: a non-existent workspace\n // otherwise reaches the harness adapter's `spawn` as an ENOENT that reads\n // as a missing agent binary, not a missing directory.\n assertWorkspaceExists(workspace);\n // Rejected here too: without a project marker, the filesystem root or an\n // arbitrary system directory becomes the confinement boundary for every\n // read, search and permitted command the planner runs. `allowInit` only\n // ever arrives here on the retry of a call the user already saw and\n // explicitly confirmed (the TUI's \"initialize this as a new workspace?\"\n // prompt) — never as a default, so an unmarked directory is still never\n // admitted silently.\n try {\n assertWorkspaceIsProject(workspace);\n } catch (err) {\n if (!(err instanceof WorkspaceNotAProjectError) || !options.allowInit) throw err;\n ensureStateDirIgnored(workspace);\n assertWorkspaceIsProject(workspace);\n }\n const config = this.plannerConfig(modelOverride, workspace);\n const fsAdapter = new PoolFileSystem(workspace);\n const broadcast = (msg: SessionMessage) => this.broadcast(sessionId, msg);\n const runner = new PoolAwareRunner(sessionId, broadcast, this.runner);\n return createSession({\n config,\n notifications: { info() {}, warn() {}, error() {}, async confirm() { return undefined; } },\n runner,\n registry: this.registry,\n workspaceRoot: () => workspace,\n fsAdapter,\n broadcast,\n // The notification channel above is silent here; this is how a client hears how the run isolates.\n onNotice: (notice) => this.broadcast(sessionId, notice),\n modelResolver: this.resolverFor(workspace),\n settings: () => this.runtimeSettings(),\n sessionId,\n ...(this.leaseHost ? { leaseHost: this.leaseHost } : {}),\n });\n }\n\n /**\n * The one way the pool builds a config that answers \"who plans\": sessions,\n * the settings response and the switch judgement all route through it, so\n * what the settings route reports is what the next turn plans with. The\n * lists are handed over as a reader, not a snapshot, so a credential change\n * reaches a session that is already open.\n */\n private plannerConfig(\n modelOverride?: string,\n workspace?: string,\n catalog: (provider: PlannerBackendId) => PlannerModelCandidate[] = (provider) => this.plannerCatalogFor(provider, workspace),\n ): WebConfig {\n return new WebConfig({\n enabledRunners: this.enabledRunnerOverride(),\n modelOverride,\n providerModelLists: () => this.cachedProviderLists,\n pickedModel: () => (this.pickedModel?.workspace === workspaceKey(workspace) ? this.pickedModel : undefined),\n agentCatalog: (provider) => catalog(provider).map((model) => model.id),\n });\n }\n\n /**\n * The user's runner choice, or undefined when they have never made one —\n * which is what lets `WebConfig` fall back to the environment's defaults.\n * Read per call rather than cached: the settings file is shared with the\n * VS Code extension host, and `getAll()` already invalidates on mtime.\n */\n private enabledRunnerOverride(): string[] | undefined {\n return this.settingsService.getEnabledRunners();\n }\n\n /**\n * Persisted, not held in memory: the daemon dies with the TUI, and a\n * process-local override meant every reopen silently reinstated the\n * environment's defaults over what the user had chosen.\n */\n setRunnerEnabled(id: string, enabled: boolean): void {\n // Worked out from the file as it is when written, not from an earlier read.\n this.settingsService.updateEnabledRunners((saved) => {\n const current = saved ?? new WebConfig().enabledRunners;\n return enabled\n ? (current.includes(id) ? current : [...current, id])\n : current.filter((r) => r !== id);\n });\n }\n\n /**\n * What `sessionId`, or a client in `workspace`, plans with: the planner's\n * model is judged against that workspace's runner catalog (see\n * {@link settingsWorkspace}).\n */\n getSettings(sessionId?: string, workspace?: string): SettingsResponse {\n const config = this.plannerConfig(undefined, this.settingsWorkspace(sessionId, workspace));\n const userSettings = this.settingsService.getAll();\n const live = sessionId ? this.sessions.get(sessionId) : undefined;\n return {\n orchestratorModel: config.orchestratorModel,\n // Who plans (ADR-0009) — a vendor id, or one of the three harness\n // planners. Surfaces need it to render the planner picker and to know\n // whether the planner model comes from a runner catalog or a vendor one.\n aiProvider: config.aiProvider,\n // A harness planner's thinking effort (ADR-0009). Surfaces need it back\n // to render the current level; without it the picker shows \"default\"\n // for a planner that is running at \"high\".\n plannerThinkingEffort: config.plannerThinkingEffort ?? '',\n // The saved level, read through the service so an environment override\n // is reported the way the next plan will read it (ADR-0001, ADR-0030).\n autonomousMode: this.settingsService.autonomousMode(),\n maxParallel: config.maxParallelSessions,\n modelAllowlist: userSettings.modelAllowlist,\n // The model remembered per planner backend (this task), so a surface can\n // render what's remembered without a second round-trip.\n plannerModels: userSettings.plannerModels,\n // An open session shows what it was opened with; a closed or unknown id\n // falls back to the file, which is what a new session starts from (ADR-0030).\n run: live?.runSettings() ?? this.settingsService.getRunSettings(),\n };\n }\n\n /**\n * Save the user's run settings, and apply them at once to `sessionId`'s run\n * when that session is open here (ADR-0030). Other sessions keep the values\n * they were opened with. Throws a {@link RunSettingsError}, saving nothing,\n * for a value out of range.\n */\n updateRunSettings(changes: Partial<GlobalRunSettings>, sessionId?: string, workspace?: string): SettingsResponse {\n this.settingsService.updateRunSettings(changes);\n if (sessionId) this.sessions.get(sessionId)?.applyRunSettings(changes);\n return this.getSettings(sessionId, workspace);\n }\n\n /** The `containers` setting as a surface shows it: `prove` starts a throwaway container to measure (ADR-0059 L3). */\n containerStatus(prove: boolean, workspace?: string): Promise<ContainerStatus> {\n const { worktreeSetupCommand: setupCommand } = this.plannerConfig(undefined, workspace);\n return containerStatus(this.settingsService.getAll().containers, { prove, ...this.docker(), ...(setupCommand ? { setupCommand } : {}) });\n }\n\n /** The way a surface changes that setting, and where it then stands; a running Session keeps what it opened with. */\n async changeContainers(change: ContainerChange, workspace?: string): Promise<ContainerChangeResponse> {\n const refused = await changeContainers(change, { settings: this.settingsService, ...this.docker() });\n return { refused, status: await this.containerStatus(false, workspace) };\n }\n\n private docker(): { cli?: DockerCli } {\n return this.suppliedDockerCli ? { cli: this.suppliedDockerCli } : {};\n }\n\n /**\n * The workspace whose runner catalog a settings read or write is judged\n * against: an open session's own, else the one the client says it is in.\n * Without either the daemon's cwd stands in. One daemon serves several\n * workspaces, and each may name another Claude account in its environment.\n */\n private settingsWorkspace(sessionId: string | undefined, workspace: string | undefined): string | undefined {\n return (sessionId ? this.sessions.get(sessionId)?.workspaceRoot : undefined) ?? workspace;\n }\n\n /**\n * The catalog `selectPlanner` should judge `provider`'s\n * remembered model against — a harness planner's own runner catalog, or the\n * cross-provider picker list for a vendor (ADR-0009), same split as\n * `plannerModelItems` in the TUI reducer. Read from whatever the resolver\n * has already cached so this stays synchronous; the routes discover it\n * first where it decides the answer ({@link discoverPlannerCatalogs},\n * {@link writeSettings}), and a catalog still cold degrades to an empty one\n * rather than kicking off discovery mid-settings-write.\n */\n private plannerCatalogFor(provider: PlannerBackendId, workspace?: string): PlannerModelCandidate[] {\n return this.resolverFor(workspace).cachedPlannerCatalog(provider);\n }\n\n /**\n * Discover the runner catalog a settings read for `workspace` is judged\n * against, when the read consults one not yet held. Most reads consult\n * none — a vendor planner, a model picked in that workspace, an agent's\n * alias or remembered pick — and answer at once, however slow the runner\n * is to list its models (ADR-0040). Only a configured model whose owner\n * only the catalog can tell waits: a cold one would report the wrong model.\n * Never throws: a catalog that cannot be discovered stays empty.\n */\n async discoverPlannerCatalogs(sessionId: string | undefined, requestWorkspace: string | undefined): Promise<void> {\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n const consulted: PlannerBackendId[] = [];\n void this.plannerConfig(undefined, workspace, (provider) => {\n consulted.push(provider);\n return this.plannerCatalogFor(provider, workspace);\n }).planner;\n await this.discoverUnheld(workspace, consulted);\n }\n\n /**\n * {@link updateSettings} as a route makes it. A write that changes who plans\n * lands after the planner writes made before it and, where its judgement\n * reads a catalog not yet held, waits for that one; every other write — a\n * key, an allowlist, a limit — lands at once (ADR-0040).\n */\n async writeSettings(changes: Record<string, unknown>, sessionId?: string, requestWorkspace?: string): Promise<SettingsUpdateResponse> {\n const change = plannerChangeOf(changes, admittedEnv(changes)?.accepted);\n if (!changesPlanner(change)) return this.updateSettings(changes, sessionId, requestWorkspace);\n const turn = this.plannerWrites.then(async () => {\n // Judged once the writes before it have landed: one may have switched.\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n const judging = this.catalogJudging(change, workspace);\n await this.discoverUnheld(workspace, judging ? [judging] : []);\n return this.updateSettings(changes, sessionId, requestWorkspace);\n });\n this.plannerWrites = turn.catch(() => undefined);\n return turn;\n }\n\n /**\n * The provider whose catalog `selectPlanner` reads to judge `change`: a\n * switch with no model of its own restores the remembered pick only from\n * the incoming catalog, and an agent's effort alone survives only where its\n * model in effect offers it. An explicit model is the user's word whatever\n * the catalog lists, and a cold catalog refuses no effort, so it reads none.\n */\n private catalogJudging(change: PlannerSelectionChange, workspace: string | undefined): PlannerBackendId | undefined {\n const current = this.plannerProviderInEffect(workspace);\n const provider = change.provider ?? current;\n const model = change.model?.trim();\n if (provider !== current) return model ? undefined : provider;\n return model === undefined && change.effort !== undefined && runnerForProvider(provider) ? provider : undefined;\n }\n\n /**\n * Discover the catalogs of `providers` that `workspace`'s resolver does not\n * hold yet; a held one, or a degraded one discovery still remembers,\n * answers at once. Never throws.\n */\n private async discoverUnheld(workspace: string | undefined, providers: PlannerBackendId[]): Promise<void> {\n const resolver = this.resolverFor(workspace);\n await Promise.all([...new Set(providers)].map((provider) => resolver.plannerCatalog(provider)));\n }\n\n /**\n * The provider planning right now. A vendor planner is resolved from its\n * model id, so this is read again after a write rather than carried over.\n */\n private plannerProviderInEffect(workspace: string | undefined): PlannerBackendId {\n return this.plannerConfig(undefined, workspace).aiProvider;\n }\n\n updateSettings(changes: Record<string, unknown>, sessionId?: string, requestWorkspace?: string): SettingsUpdateResponse {\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n // Read before any of this call's changes land, so a switch is judged\n // against what was actually in effect a moment ago. The model and effort\n // too, with where they came from: a detected agent does not plan with a\n // vendor model left in the environment, and judging against it would\n // remember that model as the agent's own pick.\n const current: PlannerSelectionCurrent = this.plannerConfig(undefined, workspace).planner;\n\n // Only allowlisted keys reach `process.env`, and everything else comes back\n // to the caller by name — the daemon's environment is inherited by every\n // runner it spawns, so this write is the whole of `admitSettingsEnv`'s\n // reason to exist. All downstream reads below use `envChanges`, which is\n // the admitted subset, never the raw body.\n const admission = admittedEnv(changes);\n const envChanges = admission ? admission.accepted : undefined;\n\n const plannerChange = plannerChangeOf(changes, envChanges);\n // Judged against the incoming provider's catalog as already discovered —\n // before the credential refresh below clears the resolver's cache — so\n // the write itself never waits on (async) discovery.\n const selection = changesPlanner(plannerChange)\n ? selectPlanner(current, plannerChange, this.plannerModelMemory, this.plannerCatalogFor(plannerChange.provider ?? current.provider, workspace))\n : undefined;\n\n if (envChanges) {\n let touched = false;\n for (const [key, value] of Object.entries(envChanges)) {\n process.env[key] = value;\n // Only a credential or endpoint change touches what a catalog\n // contains. A planner, model or effort pick does not, and invalidating\n // on one would wipe the very cache `plannerCatalogFor` reads\n // synchronously, right before the next call's switch needs it.\n if (PROVIDER_CREDENTIAL_ENV.has(key)) touched = true;\n }\n // The scheduler reads the limit on every tick, but a raised one would\n // only be seen at the next verdict; the runs waiting for a slot start now.\n if (envChanges.ORDEWELL_MAX_PARALLEL !== undefined) {\n for (const [id, session] of this.sessions) {\n session.reschedule().catch((err) => {\n console.error(`[web] reschedule failed for session ${id}: ${err instanceof Error ? err.message : err}`);\n });\n }\n }\n // A new/changed provider key or base URL must re-probe the catalog, every\n // workspace's included; without this the picker keeps serving the\n // pre-key cache until restart.\n if (touched) {\n this.modelResolver.invalidate();\n this.dropUnkeyedProviderLists();\n // A saved key can sign an agent in with no login of its own (ADR-0060,\n // R9): a signed-out verdict taken before it, recorded or cached, is no\n // longer evidence, and the next start must not be refused on it.\n forgetSignedOutRunnerAuth();\n for (const installation of new Set([this.runnerInstallation, ...this.workspaceInstallations.values()])) installation.refresh?.();\n }\n }\n\n if (selection) {\n // An effort on its own leaves the configured model as it was: a\n // detected agent's model in effect can be its remembered one, which a\n // key added later must not find written over the configured model.\n if (plannerChange.provider !== undefined || plannerChange.model !== undefined) process.env.ORCHESTRATOR_MODEL = selection.next.model;\n process.env.ORDEWELL_PLANNER_EFFORT = selection.next.effort;\n // Read once the env above is written: the pick is for whoever that\n // routes to, which a switch or the model's own catalog may have changed.\n if (plannerChange.model !== undefined) {\n this.pickedModel = { model: selection.next.model, provider: this.plannerProviderInEffect(workspace), workspace: workspaceKey(workspace) };\n }\n }\n\n if (changes.modelAllowlist && typeof changes.modelAllowlist === 'object') {\n const allowlist = changes.modelAllowlist as Record<string, unknown>;\n for (const [runner, ids] of Object.entries(allowlist)) {\n if (Array.isArray(ids)) {\n this.settingsService.setModelAllowlist(runner, ids.map(String));\n } else if (ids === null) {\n this.settingsService.setModelAllowlist(runner, undefined);\n }\n }\n }\n\n // Full/Guarded is a saved user setting (ADR-0030), not an environment\n // write: ORDEWELL_AUTONOMOUS_MODE is refused below on purpose.\n if (typeof changes.autonomousMode === 'boolean') {\n this.settingsService.setAutonomousMode(changes.autonomousMode);\n }\n\n if (envChanges) for (const monitor of this.accountLimits.values()) monitor.refresh();\n\n if (selection?.remember) {\n const { provider, model, effort } = selection.remember;\n // Without a switch a vendor pick is keyed by the provider its model id\n // resolves to now, which the env written above already reflects.\n const switched = provider !== current.provider;\n this.plannerModelMemory.remember(switched ? provider : this.plannerProviderInEffect(workspace), model, effort);\n }\n\n // Refused keys are named back rather than dropped: a client that sent one\n // wrote it to `.env` on the strength of this response, and would otherwise\n // reinstate the refusal as the next daemon's startup environment.\n const rejectedEnvKeys = admission?.rejected ?? [];\n const settings: SettingsUpdateResponse = this.getSettings(sessionId, workspace);\n if (rejectedEnvKeys.length > 0) settings.rejectedEnvKeys = rejectedEnvKeys;\n if (selection?.recall) settings.switchRecall = selection.recall;\n return settings;\n }\n\n /**\n * A vendor whose credential is gone keeps no list to route a model to it,\n * or the next turn would be sent to a planner the settings response no\n * longer names. Pruned rather than cleared: the vendors that still hold a\n * key keep routing their models until the catalog is discovered again, so\n * adding a second key does not move the planner off the first.\n */\n private dropUnkeyedProviderLists(): void {\n if (!this.cachedProviderLists) return;\n const keyed = new Set<string>(configuredProviders(new WebConfig()));\n this.cachedProviderLists = Object.fromEntries(\n Object.entries(this.cachedProviderLists).filter(([provider]) => keyed.has(provider)),\n );\n }\n\n setOrchestratorModel(model: string): string {\n process.env.ORCHESTRATOR_MODEL = model;\n return model;\n }\n\n /**\n * The catalog as `workspace`'s runners see it: Claude Code's picker lineup\n * follows the `CLAUDE_CONFIG_DIR` that workspace's environment sets.\n * Without a workspace the daemon's cwd stands in.\n */\n async getProviderModels(workspace?: string): Promise<ModelsResponse> {\n const config = new WebConfig();\n const resolver = this.resolverFor(workspace);\n\n const runnerIds = this.registry.list().map((p) => p.manifest.name);\n const sandbox = this.codexSandbox.ensure();\n // Awaited below; marked handled now, so a failed catalog load before then\n // does not leave its rejection unhandled.\n sandbox.catch(() => {});\n // The vendor catalogs first: a runner started on a key Ordewell holds can\n // be handed the model that key's catalog says its account is served\n // (Qwen's, ADR-0060 R9), and a discovery begun before the catalog is held\n // would list a model the account may be refused, until the next refresh.\n const providerLists = await resolver.refresh();\n const [runnerModels] = await Promise.all([resolver.modelsForRunners(runnerIds), sandbox]);\n\n // `refresh()` populates the picker cache, so this is the same fetch — no\n // second network round-trip. Errors are whatever that fetch recorded.\n const orchestratorModels = await resolver.pickerOptions();\n const providerErrors = resolver.getDiscoveryErrors();\n const runnerErrors = resolver.getRunnerDiscoveryErrors();\n\n this.cachedProviderLists = providerLists;\n\n const allModels: DiscoveredModel[] = [];\n const seen = new Set<string>();\n const modelsByRunner: Record<string, DiscoveredModel[]> = {};\n\n for (const id of runnerIds) {\n modelsByRunner[id] = runnerModels[id] ?? [];\n for (const m of modelsByRunner[id]) {\n if (!seen.has(m.modelId)) {\n seen.add(m.modelId);\n allModels.push(m);\n }\n }\n }\n\n const providers = configuredProviders(config);\n\n return {\n models: allModels,\n modelsByRunner,\n modesByRunner: runnerModesFrom(this.registry, runnerIds),\n orchestratorModel: this.plannerConfig(undefined, workspace).orchestratorModel,\n providers,\n orchestratorModels,\n providerErrors,\n runnerErrors,\n };\n }\n\n getRunnerState(workspace?: string): { enabledRunners: RunnerId[]; orchestratorModel: string } {\n const config = this.plannerConfig(undefined, workspace);\n return { enabledRunners: config.enabledRunners, orchestratorModel: config.orchestratorModel };\n }\n\n /**\n * The resolver whose runner catalogs are discovered under `workspace`'s\n * environment, the one its tasks are launched with. Kept per workspace,\n * since one daemon serves several and a catalog is cached until refreshed;\n * the vendor catalogs are shared by all of them.\n */\n private resolverFor(workspace: string | undefined): ModelResolver {\n if (this.suppliedModelResolver || !workspace) return this.modelResolver;\n const key = workspaceKey(workspace);\n if (key === workspaceKey(undefined)) return this.modelResolver;\n return this.modelResolver.withRunnerEnv(key, async () => ({ ...process.env, ...(await workspaceEnvOf(key)) }));\n }\n\n /**\n * The probe that judges a login for `workspace`, cached so its install and\n * auth verdicts survive between runner-list refreshes. Without a workspace\n * the daemon's cwd is what the request would plan with anyway.\n */\n private installationFor(workspace: string | undefined): RunnerInstall {\n if (this.suppliedRunnerInstallation) return this.suppliedRunnerInstallation;\n if (!workspace) return this.runnerInstallation;\n const key = resolve(workspace);\n let installation = this.workspaceInstallations.get(key);\n if (!installation) {\n installation = new RunnerInstallation(this.registry, undefined, undefined, {\n env: () => workspaceEnvOf(key),\n workspace: () => key,\n });\n this.workspaceInstallations.set(key, installation);\n }\n return installation;\n }\n\n /**\n * Runners whose CLI is actually installed on the host, with display name and\n * enabled state. Only these should be offered for selection — an uninstalled\n * runner can't be spawned. `workspace` names whose account the auth verdict\n * is about; without it the daemon's cwd stands in.\n */\n async getInstalledRunners(workspace?: string): Promise<RunnersResponse['runners']> {\n // The runner list is the one place a user who just fixed their host looks\n // again, so every cached answer is asked afresh: the Codex sandbox, the\n // install verdicts, and the agent detection behind the no-choice defaults.\n await this.codexSandbox.refresh();\n const installation = this.installationFor(workspace);\n installation.refresh?.();\n await this.detectInstalledPlanner();\n\n const config = new WebConfig({ enabledRunners: this.enabledRunnerOverride() });\n const enabled = new Set(config.enabledRunners);\n const runners = this.registry.list();\n const installedIds = new Set(\n await installation.filterInstalled(runners.map((p) => p.manifest.name)),\n );\n // The auth verdict rides along, never gating the list: a signed-out agent\n // is installed and offered, and a surface flags it. The probe was just\n // asked above and its answer is cached, so this costs no second spawn.\n // An installed CLI that cannot be started — a Windows `.cmd` shim, or an\n // ACP agent below its minimum version — stays in the list as unavailable\n // with its reason, so a surface can say why instead of hiding it (ADR-0009,\n // ADR-0060).\n return Promise.all(\n runners\n .filter((p) => installedIds.has(p.manifest.name))\n .map(async (p): Promise<RunnersResponse['runners'][number]> => {\n const { usable, reason, auth, version } = await installation.runnerUsability(p.manifest.name);\n return {\n id: p.manifest.name,\n name: p.manifest.displayName,\n enabled: enabled.has(p.manifest.name),\n ...(usable ? {} : { usable: false, ...(reason ? { reason } : {}) }),\n ...(auth ? { auth } : {}),\n ...(version ? { version } : {}),\n };\n }),\n );\n }\n\n async generatePlan(sessionId: string, goal: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Promise<PlanState> {\n const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride).aiProvider);\n if (recheck) await recheck;\n const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);\n return migratePlanState(await this.firstTurn(sessionId, session, () => session.generatePlan(goal, runners)));\n }\n\n /**\n * Judge the planner as the workspace's account is now, not as it was when the\n * list was last read: the signed-out refusal itself offers the runner's own\n * `auth login` as a way back, and that happens in another process. Only a\n * recorded signed-out verdict is asked again — unknown never blocks, and a\n * signed-in one is the runner's own failure to report. Null when there is\n * nothing to ask, so the turn registers at once as it always did.\n */\n private recheckSignedOutPlanner(workspace: string, provider: PlannerBackendId): Promise<void> | null {\n const runner = runnerForProvider(provider);\n if (!runner || recordedRunnerAuth(runner, workspace)?.state !== 'signed-out') return null;\n const installation = this.installationFor(workspace);\n installation.refresh?.();\n return installation.plannerUsability(runner).then(() => undefined);\n }\n\n /**\n * Build the session a new planning conversation runs in and register it in\n * place of any live one, for {@link firstTurn} to run its first turn on.\n */\n private openPlanningSession(sessionId: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Session {\n const session = this.createSessionFor(sessionId, workspace, modelOverride, options);\n // Judged on the new session's config (which carries the request's model)\n // and before the old session is destroyed, so a refusal leaves it alone.\n // Not while the installed-planner probe is out: its answer can be the\n // planner, and judging the openrouter fallback now would refuse the very\n // keyless first run the probe exists for, so that judgement is the first\n // turn's own gate. The runners are judged on the same terms: before the\n // probe answers, the enabled set is a guess a refusal must not rest on.\n if (installedPlannerAnswered()) {\n session.assertPlannerReady();\n session.assertRunnersEnabled(runners);\n }\n // After the new session is built, so a refusal above leaves the live one\n // alone; before the set, so its runners and planner turn stop broadcasting.\n this.destroy(sessionId);\n // Registered before the blocking call, not after: research inside\n // the first planner turn can raise an approval and await the answer, and\n // that answer arrives over POST /api/approvals/:sessionId — which 404s\n // until the session is in this map. Registering only on return made the\n // first approval of every session unanswerable until its 5-minute timeout.\n this.registerSession(sessionId, workspace, session);\n this.warmCodexSandbox();\n return session;\n }\n\n /**\n * Conversational planning (ADR-0002): start the planner dialogue for a\n * session. Returns the current plan state — a committed plan when the\n * planner had enough context, otherwise the dialogue so far (last\n * assistant message lives in conversationHistory).\n */\n async startPlanning(sessionId: string, goal: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Promise<LegacyPlanState> {\n const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride).aiProvider);\n if (recheck) await recheck;\n const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);\n return this.firstTurn(sessionId, session, () => session.startPlanning(goal, runners));\n }\n\n /**\n * Continue the planner dialogue with the user's reply: queued behind the\n * first turn, even while it waits for the installed-planner probe, and\n * refused only while a turn of another kind holds the conversation. The\n * session's own planner gate waits for the probe and judges the planner, as\n * it does for every turn.\n */\n async continuePlanning(sessionId: string, message: string): Promise<LegacyPlanState> {\n const session = this.session(sessionId);\n // A reply is a planner turn like any other: the signed-out refusal offers\n // the runner's own login, which runs outside this process, so ask the\n // workspace's account again before the session's synchronous gate judges.\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.continueConversation(message);\n }\n\n /** Condense a session's conversation. The summary turn is a planner turn, so `cancelPlanning` stops it. */\n async compactConversation(sessionId: string): Promise<ConversationCompaction & { plan: LegacyPlanState }> {\n const session = this.session(sessionId);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n const compaction = await session.compactConversation();\n return { ...compaction, plan: session.planState! };\n }\n\n /**\n * Send now (ADR-0023): the Session stops the planner turn in flight and\n * answers this message in the turn that replaces it, ahead of anything\n * waiting. The recheck is the one a reply does before the gate: a login done\n * with the runner's own command is seen here too.\n */\n async forceSendPrompt(sessionId: string, message: string): Promise<LegacyPlanState> {\n const session = this.session(sessionId);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.forceSendPrompt(message);\n }\n\n /** Retry a compaction paused on the planner's context: a planner turn, and gated as one. */\n async retryPlannerCompaction(sessionId: string): Promise<LegacyPlanState> {\n const session = this.session(sessionId);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.retryPlannerCompaction();\n }\n\n /**\n * Abort the planner turn in flight for a session, if any. Answers whether\n * there was one to cancel — the route reports that rather than 404ing a\n * session that simply is not planning right now.\n */\n cancelPlanning(sessionId: string): boolean {\n // A first turn still waiting for the probe is the session's to stop too.\n return this.sessions.get(sessionId)?.abortPlannerTurn() ?? false;\n }\n\n /**\n * Register a session persisted on disk so its plan becomes executable and\n * editable. Only sessions planned in this process are otherwise addressable,\n * which left a restored plan readable but inert — every task endpoint\n * answered \"Session not found\".\n *\n * No LLM call happens here: the plan is adopted as saved, and the planner is\n * only contacted when the user next sends a message.\n */\n adoptSavedSession(sessionId: string, workspace: string): LegacyPlanState {\n // Re-adopting would clear the execution log and drop a running plan back to\n // its saved state, so a live session wins over the file.\n const live = this.sessions.get(sessionId);\n if (live?.planState) return live.planState;\n\n const saved = loadSession(sessionId, workspace);\n if (!saved) throw new SessionNotFoundError();\n\n const session = this.createSessionFor(sessionId, workspace);\n // The saved id is adopted too, so later persists rewrite the same file\n // instead of forking the session under a fresh identity. Refused while\n // another live host runs the session (ADR-0049); the session built for\n // it is let go, and the one live here, if any, keeps running.\n try {\n session.loadPlan(saved.plan, saved.meta.goal, workspace, { sessionId: saved.meta.id });\n } catch (err) {\n session.destroy();\n throw err;\n }\n // A live session with no plan yet is mid-planning; replacing it must stop that turn.\n this.destroy(sessionId);\n this.registerSession(sessionId, workspace, session);\n // What another host recorded while it held the session, before this one took it (ADR-0062 G6).\n session.foldUserActions();\n\n return session.planState ?? saved.plan;\n }\n\n /**\n * Fork a session's conversation into a new session and adopt it, so the\n * fork is addressable at once — through the same path a saved session is\n * adopted by, reading back the file the fork was written to. The original\n * keeps running, or planning, untouched.\n */\n forkConversation(sessionId: string): AdoptedFork {\n return this.adoptFork(this.session(sessionId).forkConversation());\n }\n\n /** A rewind is a fork from an earlier point, so it is adopted the same way. */\n rewindConversation(sessionId: string, index: number): AdoptedFork & { rewoundMessage: string } {\n const fork = this.session(sessionId).rewindConversation(index);\n return { ...this.adoptFork(fork), rewoundMessage: fork.rewoundMessage };\n }\n\n private adoptFork(fork: ConversationFork): AdoptedFork {\n return { sessionId: fork.sessionId, goal: fork.goal, plan: this.adoptSavedSession(fork.sessionId, fork.workspace) };\n }\n\n /**\n * Direct access to a session's interface — routes call the Session; the\n * pool only registers sessions and fans broadcasts out to WS clients.\n */\n session(sessionId: string): Session {\n const session = this.sessions.get(sessionId);\n if (!session) throw new SessionNotFoundError();\n return session;\n }\n\n /**\n * Stop a session and drop it. A replacement under the same id (re-planning,\n * adopting) keeps its subscribers: they are watching the id, and the new\n * session's broadcasts continue on the same socket. An explicit delete or\n * close is different — the surface must stop drawing a session that no\n * longer exists — so those pass `notifyClients`.\n */\n destroy(sessionId: string, options?: { notifyClients?: boolean }): void {\n this.sessions.get(sessionId)?.destroy();\n this.sessions.delete(sessionId);\n this.sessionWorkspaces.delete(sessionId);\n this.releaseUnusedAccountLimits();\n // A root's socket outlives a replacement, its broadcasts arriving on it. A\n // child's cannot: it reads a directory that went with the old Session.\n this.childStreams.closeRoot(sessionId, options?.notifyClients ? 1001 : 1012);\n if (!options?.notifyClients) return;\n const clients = this.clients.get(sessionId);\n if (!clients) return;\n this.broadcast(sessionId, { type: 'notice', level: 'info', message: 'Session closed.' });\n for (const ws of clients) {\n if (ws.readyState === ws.OPEN) ws.close(1001, 'Session closed');\n }\n this.clients.delete(sessionId);\n }\n\n /** Close a session for a surface that is done with it: it is dropped now, and this resolves once all it started has gone. */\n async close(sessionId: string): Promise<void> {\n const session = this.sessions.get(sessionId);\n this.destroy(sessionId, { notifyClients: true });\n await session?.gone;\n }\n\n /** Stop a session's whole tree, and wait until it has gone; the session stays open (ADR-0055 D16). */\n async stopTree(sessionId: string): Promise<void> {\n await this.sessions.get(sessionId)?.stopSubtree();\n }\n\n /** What a session's tree left in the engine, which only the `containers` setting says to look for (ADR-0059 L6). */\n reclaim(sessionId: string): Promise<void> {\n return reclaimContainers(sessionId, this.settingsService.getAll().containers);\n }\n\n destroyAll(): void { for (const id of this.sessions.keys()) this.destroy(id); }\n}\n\nexport const scanWorkspaces = scanWorkspacesImpl;\n\nexport function getSessionList(workspace: string) { return listSessions(workspace); }\nexport function getSession(sessionId: string, workspace: string) { return loadSession(sessionId, workspace); }\n\n/**\n * A session and the children saved under it. Its tree stops first, since a\n * child at work cannot have its worktrees taken from under it (ADR-0055 D16).\n * Their runs go next: the files that follow are the only record that names\n * their worktrees and branches (D11). What git could not let go stops the\n * delete, with the records still in place and `close` not called, and is named\n * in the error. What the tree left in an engine goes last: its volumes are\n * nothing a person could go back to once its records have gone. That waits for\n * the session to have gone, not only stopped: a closing attempt still brings its\n * work back, and a helper that names a volume already taken makes it again, with\n * no label for anything to find it by.\n */\nexport async function removeSession(sessionId: string, workspace: string, stop: () => Promise<void>, close: () => Promise<void>, reclaim: () => Promise<void>): Promise<boolean> {\n await stop();\n const { refused } = await discardChildRuns(sessionId, workspace, createWorktreeIsolation({ config: new WebConfig() }));\n if (refused.length > 0) throw new Error(`The session was kept: ${refused.map(({ worktree, reason }) => `${worktree} (${reason})`).join(', ')}`);\n await close();\n await reclaim();\n return deleteSession(sessionId, workspace);\n}\n\n/** A write's `env`, split into what may reach `process.env` and what may not. */\nfunction admittedEnv(changes: Record<string, unknown>): ReturnType<typeof admitSettingsEnv> | undefined {\n const raw = changes.env;\n return raw && typeof raw === 'object' && !Array.isArray(raw) ? admitSettingsEnv(raw as Record<string, unknown>) : undefined;\n}\n\n/**\n * What a settings write asks of who plans. A pick arrives either as a\n * top-level field (a vendor model, `ordewell model set`) or through env\n * (`ordewell planner-effort`, the TUI's pickers); env wins, as it did when\n * both were written in that order. The provider is the name the client sent,\n * never re-derived from the model: a switch may have just cleared that model.\n * An `inherited` write is no pick at all: it is the environment a client was\n * started under, which the daemon would have inherited had the client spawned\n * it, so it is written as it stands and nothing in it is remembered.\n */\nfunction plannerChangeOf(changes: Record<string, unknown>, envChanges: Record<string, string> | undefined): PlannerSelectionChange {\n return changes.inherited === true ? {} : {\n provider: envChanges?.AI_PROVIDER,\n model: envChanges?.ORCHESTRATOR_MODEL ?? stringField(changes.orchestratorModel),\n effort: envChanges?.ORDEWELL_PLANNER_EFFORT ?? stringField(changes.plannerThinkingEffort),\n };\n}\n\nfunction changesPlanner(change: PlannerSelectionChange): boolean {\n return Object.values(change).some((v) => v !== undefined);\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** One spelling per workspace; a request that names none is the daemon's cwd's. */\nfunction workspaceKey(workspace: string | undefined): string {\n return resolve(workspace ?? process.cwd());\n}\n","import { Hono } from 'hono';\nimport { OrchestratorPool, getSessionList, removeSession } from '../pool/orchestratorPool';\nimport {\n listTaskLogAttempts,\n loadSession,\n migratePlanState,\n readTaskLog,\n surfacePlan,\n surfacePlanState,\n taskLogForSurface,\n type AdoptSessionResponse,\n type OkResponse,\n type SessionListResponse,\n type SessionResponse,\n type TaskLogAttemptsResponse,\n type TaskLogResponse,\n} from '@ordewell/core';\nimport { failure, refuse } from './errors';\n\nexport function sessionsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n const sessions: SessionListResponse = getSessionList(ws);\n return c.json(sessions);\n });\n\n /**\n * The saved file answers for a session nobody is holding. While the pool has\n * one, its store is the only honest source of task status: the file is\n * normalized as if nothing were running (`in_progress` → `pending`), so\n * serving it mid-run told every surface that the tasks it is watching had\n * never started.\n */\n router.get('/:id', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n const id = c.req.param('id');\n const saved = loadSession(id, ws);\n if (!saved) return refuse(c, 404, 'Session not found', 'session_not_found');\n const run = pool.runSnapshot(id);\n const plannerTurnId = pool.plannerTurnId(id);\n const plannerCompaction = pool.plannerCompaction(id);\n // The phase-tagged plan keeps no transcript: a client that joins or only reads the session redraws its chat from this.\n const { conversationHistory, researchLog, plannerUsage, pendingTurns } = surfacePlan(pool.getPlan(id) ?? saved.plan);\n return c.json({\n meta: saved.meta,\n plan: surfacePlanState(pool.getPlanState(id) ?? migratePlanState(saved.plan)),\n conversation: { conversationHistory, researchLog, plannerUsage, pendingTurns },\n ...(run ? { run } : {}),\n ...(plannerTurnId ? { plannerTurnId } : {}),\n ...(plannerCompaction ? { plannerCompaction } : {}),\n } satisfies SessionResponse);\n });\n\n /**\n * Adopt a saved session into the running server. `GET /:id` only reads the\n * file; until a session is registered with the pool there is no orchestrator\n * behind it, so execution and task control answer \"Session not found\".\n */\n router.post('/:id/load', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n try {\n const id = c.req.param('id');\n const plan = pool.adoptSavedSession(id, ws);\n const run = pool.runSnapshot(id);\n const plannerTurnId = pool.plannerTurnId(id);\n const plannerCompaction = pool.plannerCompaction(id);\n return c.json({\n ok: true,\n plan: surfacePlan(plan),\n goal: pool.getGoal(id),\n ...(run ? { run } : {}),\n ...(plannerTurnId ? { plannerTurnId } : {}),\n ...(plannerCompaction ? { plannerCompaction } : {}),\n } satisfies AdoptSessionResponse);\n } catch (err: unknown) {\n return failure(c, err, 'load session', { message: 'Failed to load session' });\n }\n });\n\n /**\n * A structured task's saved log (ADR-0018, P1), read off disk whether or\n * not the pool holds the session: every attempt is written as it happens,\n * so the file is as current as the stream a reopened view catches up with.\n */\n router.get('/:id/tasks/:taskId/log', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n return c.json({ attempts: listTaskLogAttempts({ baseDir: ws, sessionId: c.req.param('id') }, c.req.param('taskId')), position: pool.streamPosition(c.req.param('id')) } satisfies TaskLogAttemptsResponse);\n });\n\n router.get('/:id/tasks/:taskId/log/:attempt', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n const attempt = Number(c.req.param('attempt'));\n if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, 'attempt must be a positive integer');\n return c.json({ attempt, events: taskLogForSurface(readTaskLog({ baseDir: ws, sessionId: c.req.param('id') }, c.req.param('taskId'), attempt)), position: pool.streamPosition(c.req.param('id')) } satisfies TaskLogResponse);\n });\n\n // The live session goes before its files: it persists as it changes, so one\n // left running would write its file back and reappear in the list. A delete\n // refused before that point leaves it open, its tree stopped.\n router.delete('/:id', async (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n const id = c.req.param('id');\n const held = pool.hasSession(id);\n let removed: boolean;\n try {\n removed = await removeSession(id, ws, () => pool.stopTree(id), () => pool.close(id), () => pool.reclaim(id));\n } catch (err) {\n return c.json({ ok: false, message: err instanceof Error ? err.message : String(err) } satisfies OkResponse);\n }\n const ok = held || removed;\n return c.json({\n ok,\n ...(ok ? {} : { message: `No session \"${id}\" was found in ${ws}.` }),\n } satisfies OkResponse);\n });\n\n // Stops the orchestrator (killing every runner it spawned, and every container\n // with what serves it) and drops the in-memory planner conversation, answering\n // once they have gone. No-op if already closed/unregistered.\n router.post('/:id/close', async (c) => {\n await pool.close(c.req.param('id'));\n return c.json({ ok: true } satisfies OkResponse);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport {\n flattenTasks,\n NoPlanError,\n parseExecutionCommand,\n resolveUserTaskRef,\n surfacePlan,\n surfacePlanState,\n TaskControlError,\n type CommandOutcome,\n type ConversationCompactResponse,\n type ConversationForkResponse,\n type ConversationRewindResponse,\n type ApproveReviewResponse,\n type AnswerEscalationRequest,\n type ErrorBody,\n type EscalationsResponse,\n type ExecuteCommandResponse,\n type ExecuteResponse,\n type ExecutionCommand,\n type GeneratePlanResponse,\n type IsolationDiffResponse,\n type IsolationMergeResponse,\n type MergeGateResponse,\n type TaskRevertPreviewResponse,\n type OkResponse,\n type PlanResponse,\n type PrdResponse,\n type ResolveConflictResponse,\n type RewindTargetsResponse,\n type StopResponse,\n type TaskMessageResponse,\n type Task,\n type CancelPlanningResponse,\n type CancelResumeResponse,\n} from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\n\nconst NO_CHECKPOINT = 'The task is not waiting at a checkpoint: it was answered already, withdrawn, or has no runner left to hear it.';\n\n/** The id of the task a reference names, as the seam resolves it — the user's unique id prefix included; the reference itself when the plan holds no such task, for the seam to refuse. */\nfunction idOfRef(session: ReturnType<OrchestratorPool['session']>, ref: string): string {\n return resolveUserTaskRef(session.planState?.tasks ?? [], ref)?.id ?? ref;\n}\n\n/** One execution button's command, run as the user (ADR-0029): a refusal becomes the 400 the surface already shows. */\nasync function runUserCommand(session: ReturnType<OrchestratorPool['session']>, command: ExecutionCommand): Promise<Extract<CommandOutcome, { ok: true }>> {\n const outcome = await session.execute(command, { kind: 'user' });\n if (!outcome.ok) throw new TaskControlError(outcome.message);\n return outcome;\n}\n\nexport function plansRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.post('/:sessionId/generate', async (c) => {\n try {\n const { goal, runners, workspace, model, allowInit } = await jsonObject<{\n goal?: string; runners?: string[]; workspace?: string; model?: string; allowInit?: boolean;\n }>(c);\n if (!goal) return c.json({ error: 'goal is required' }, 400);\n const ws = workspace || c.req.query('workspace') || process.cwd();\n const queryRunners = c.req.query('runners');\n // No runners in the request means \"whatever is enabled\", not claude-code:\n // a hard-coded default here contradicts the /runners toggle state and\n // fails planning for anyone who disabled claude-code. Left undefined for\n // the session to read after its planner gate, since before the installed\n // agents are detected the enabled default is not known yet.\n const runnerList: string[] | undefined = Array.isArray(runners) ? runners : (runners ? [runners] : (queryRunners ? queryRunners.split(',').map(s => s.trim()).filter(Boolean) : undefined));\n const plan = await pool.generatePlan(c.req.param('sessionId'), goal, runnerList, ws, model, { allowInit });\n const { models, modelsByRunner } = await pool.getProviderModels(ws);\n const notes = (pool.session(c.req.param('sessionId')).planState?.conversationHistory ?? [])\n .filter((e) => e.kind === 'system')\n .map((e) => e.content);\n return c.json({ plan: surfacePlanState(plan), models, modelsByRunner, ...(notes.length > 0 ? { notes } : {}) } satisfies GeneratePlanResponse);\n } catch (err) {\n return failure(c, err, 'generate', { message: 'Plan generation failed' });\n }\n });\n\n router.post('/:sessionId/execute', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'));\n // The daemon contract keeps `no_plan` distinct from a plain refusal; the\n // seam refuses either way, so the code it cannot carry is kept here. A\n // run under way is no refusal: executing then approves what waits (#95).\n if (!session.planState || session.planTasks.length === 0) throw new NoPlanError('execute');\n const { message } = await runUserCommand(session, { command: 'run_plan' });\n return c.json({ status: 'running', message } satisfies ExecuteResponse);\n } catch (err) {\n return failure(c, err, 'execute');\n }\n });\n\n router.post('/:sessionId/stop', async (c) => {\n try {\n if (pool.hasSession(c.req.param('sessionId'))) {\n const session = pool.session(c.req.param('sessionId'));\n const outcome = await session.execute({ command: 'stop_run' }, { kind: 'user' });\n // A refused stop is no failure while nothing can start: \"stopped\" is still true (ADR-0029).\n if (!outcome.ok && (session.isExecuting || session.startsPending)) throw new TaskControlError(outcome.message);\n return c.json({ status: 'stopped', message: outcome.message } satisfies StopResponse);\n }\n return c.json({ status: 'stopped' } satisfies StopResponse);\n } catch (err) {\n return failure(c, err, 'stop');\n }\n });\n\n // Distinct from the stop route above, which halts *execution* (running\n // tasks). This aborts a planning turn in flight — a harmless no-op, not a\n // 404, when the session simply isn't planning right now.\n router.post('/:sessionId/planning/stop', (c) => {\n const cancelled = pool.cancelPlanning(c.req.param('sessionId'));\n return c.json({ cancelled } satisfies CancelPlanningResponse);\n });\n\n // Every execution button that is no more than \"this command, as the user\"\n // (ADR-0029, ADR-0006): the body is an ExecutionCommand, the answer is the\n // seam's own line and payload, and a refusal is the one 400 every route gives.\n // The routes beside it stay because they answer more than the seam does: a\n // `no_plan` code, the 409 for a checkpoint nobody waits at, the Merge all card.\n router.post('/:sessionId/execute-command', async (c) => {\n try {\n const parsed = parseExecutionCommand(await jsonObject(c));\n if (!parsed.ok) return refuse(c, 400, parsed.message, 'refused');\n const outcome = await pool.session(c.req.param('sessionId')).execute(parsed.command, { kind: 'user' });\n if (!outcome.ok) {\n // Not through TaskControlError: a Merge all that git stopped keeps the result it stopped with.\n return c.json({ error: outcome.message, code: 'refused', ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ErrorBody, 400);\n }\n return c.json({ ok: true, message: outcome.message, ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ExecuteCommandResponse);\n } catch (err) {\n return failure(c, err, 'execute-command');\n }\n });\n\n router.get('/:sessionId/escalations', (c) => {\n try {\n return c.json({ escalations: pool.session(c.req.param('sessionId')).escalations() } satisfies EscalationsResponse);\n } catch (err) {\n return failure(c, err, 'escalations');\n }\n });\n\n // Always the user's: a planner or a supervisor has no route here (ADR-0053).\n router.post('/:sessionId/escalations/answer', async (c) => {\n try {\n const { id, option, note, confirmed } = await jsonObject<Partial<AnswerEscalationRequest>>(c);\n if (typeof id !== 'string' || typeof option !== 'string') return refuse(c, 400, 'id and option are required', 'refused');\n const outcome = await pool.session(c.req.param('sessionId')).answerEscalation(id, option, typeof note === 'string' ? note : undefined, confirmed === true);\n if (!outcome.ok) return c.json({ error: outcome.message, code: 'refused', ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ErrorBody, 400);\n return c.json({ ok: true, message: outcome.message, ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ExecuteCommandResponse);\n } catch (err) {\n return failure(c, err, 'escalations');\n }\n });\n\n // The task runner's own slash command (#66): carried to the runner, never\n // one of Ordewell's. A task that cannot take one is refused with the reason.\n router.post('/:sessionId/tasks/:taskId/commands', async (c) => {\n try {\n const body: unknown = await c.req.json().catch(() => ({}));\n const fields = typeof body === 'object' && body !== null ? body as { name?: unknown; args?: unknown } : {};\n if (typeof fields.name !== 'string' || !fields.name.trim()) return c.json({ error: 'name is required' }, 400);\n const args = typeof fields.args === 'string' ? fields.args : '';\n const id = pool.session(c.req.param('sessionId')).invokeTaskCommand(c.req.param('taskId'), fields.name.trim(), args);\n return c.json({ id } satisfies TaskMessageResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // Answer the checkpoint a task waits at: approve lets it go on, a delegated\n // task's child with its words and a raise, reject sends it the reason. Nothing\n // waiting — settled elsewhere, withdrawn, or no runner left to hear it — is a\n // 409, so a surface says so instead of claiming success.\n // The seam refuses a checkpoint nobody waits at too; this route keeps that\n // case apart as its own 409 and code.\n for (const answer of ['approve', 'reject'] as const) {\n router.post(`/:sessionId/tasks/:taskId/checkpoint/${answer}`, async (c) => {\n try {\n const body: unknown = await c.req.json().catch(() => ({}));\n const reason = typeof body === 'object' && body !== null && 'reason' in body && typeof body.reason === 'string' ? body.reason.trim() : '';\n const raiseTokens = typeof body === 'object' && body !== null && 'raiseTokens' in body ? body.raiseTokens : undefined;\n const raise = typeof raiseTokens === 'number' && Number.isSafeInteger(raiseTokens) && raiseTokens > 0 ? raiseTokens : undefined;\n if (raiseTokens !== undefined && raise === undefined) return refuse(c, 400, 'A raise is a whole number of tokens, 1 or more.', 'refused');\n const session = pool.session(c.req.param('sessionId'));\n const taskId = idOfRef(session, c.req.param('taskId'));\n // Resolved once: the pre-check and the seam judge the same task, the\n // user's unique id prefix included (ADR-0029).\n if (!session.awaitsCheckpoint(taskId)) return refuse(c, 409, NO_CHECKPOINT, 'checkpoint_not_waiting');\n const { message } = await runUserCommand(session, { command: 'answer_checkpoint', task: taskId, answer, ...(reason ? { reason } : {}), ...(raise !== undefined ? { raiseTokens: raise } : {}) });\n return c.json({ ok: true, message } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n }\n\n // What a task waits on at its merge gate (ADR-0020), for a surface that asks\n // before a force start passes it. Empty when nothing gates the task.\n router.get('/:sessionId/tasks/:taskId/merge-gate', (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'));\n const tasks = flattenTasks(session.planState?.tasks ?? []);\n // Named as the seam names a task, so a surface asks about the reference the user typed.\n const mergeGate = session.mergeGate(idOfRef(session, c.req.param('taskId'))).map((id) => {\n const dep = tasks.find((t) => t.id === id);\n return { id, order: dep?.order ?? 0, title: dep?.title ?? id };\n });\n return c.json({ mergeGate } satisfies MergeGateResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // What reverting a task would do now (ADR-0054), for a surface that confirms\n // before it sends `revert_task`. A refusal is the answer here, not an error.\n router.get('/:sessionId/tasks/:taskId/revert-preview', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'));\n return c.json((await session.revertPreview(idOfRef(session, c.req.param('taskId')))) satisfies TaskRevertPreviewResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // Isolated-run handoff (ADR-0013). A merge that conflicts or fails is an\n // outcome the surface reports, not a malformed request, so it answers 200.\n router.get('/:sessionId/isolation/diff', async (c) => {\n try {\n return c.json({ diff: await pool.session(c.req.param('sessionId')).reviewRunDiff() } satisfies IsolationDiffResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/isolation/merge', async (c) => {\n try {\n // A merge git stopped is still an outcome the Merge all card shows: the seam refuses it, with the result.\n const body: unknown = await c.req.json().catch(() => ({}));\n const pastChecks = typeof body === 'object' && body !== null && 'pastChecks' in body && body.pastChecks === true;\n const outcome = await pool.session(c.req.param('sessionId')).execute(pastChecks ? { command: 'merge_all', pastChecks: true } : { command: 'merge_all' }, { kind: 'user' });\n if (outcome.payload?.kind === 'merge') return c.json(outcome.payload.result satisfies IsolationMergeResponse);\n // Not a refusal of the request: the user is asked, the checks named, and the yes comes in the body.\n if (outcome.payload?.kind === 'merge_hold') return refuse(c, 409, outcome.message, 'merge_past_check');\n if (!outcome.ok) throw new TaskControlError(outcome.message);\n throw new Error('Merge all answered without its result.');\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n for (const [segment, run] of [\n ['discard', (s: ReturnType<typeof pool.session>) => s.discardRun()],\n ['cleanup', (s: ReturnType<typeof pool.session>) => s.cleanupRun()],\n ['stash-and-continue', (s: ReturnType<typeof pool.session>) => s.continueWithStash()],\n ['run-without', (s: ReturnType<typeof pool.session>) => s.continueWithoutIsolation()],\n ] as const) {\n router.post(`/:sessionId/isolation/${segment}`, async (c) => {\n try {\n await run(pool.session(c.req.param('sessionId')));\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n }\n\n router.post('/:sessionId/tasks/:taskId/resolve-conflict', async (c) => {\n try {\n const plan = await pool.session(c.req.param('sessionId')).resolveConflictAsTask(c.req.param('taskId'));\n return c.json({ plan: plan && surfacePlan(plan) } satisfies ResolveConflictResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.put('/:sessionId/tasks/:taskId', async (c) => {\n try {\n const changes = await jsonObject<Partial<Task>>(c);\n // JSON cannot carry undefined, so a null is a client clearing the model.\n if (changes.assignedModel === null) changes.assignedModel = undefined;\n // One edit, whatever it holds: the session takes the fields a direct\n // edit may set, moves the runner with what it scopes, checks the\n // dependency list against the whole plan, and lands it as one save. An\n // empty patch still asks whether the task exists at all.\n const result = await pool.session(c.req.param('sessionId')).updateTask(c.req.param('taskId'), changes);\n if (!result) return refuse(c, 404, 'Task not found', 'task_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.delete('/:sessionId/tasks/:taskId', async (c) => {\n try {\n const result = await pool.session(c.req.param('sessionId')).removeTask(c.req.param('taskId'));\n if (!result) return refuse(c, 404, 'Task not found', 'task_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/tasks', async (c) => {\n try {\n const body = await jsonObject<Partial<Task>>(c);\n const result = await pool.session(c.req.param('sessionId')).addTask(body);\n if (!result) return refuse(c, 404, 'Session not found', 'session_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/review/approve', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'));\n const plan = session.planState;\n if (!plan) throw new NoPlanError('review');\n const { message } = await runUserCommand(session, { command: 'approve_review' });\n return c.json({ plan: surfacePlan(plan), message } satisfies ApproveReviewResponse);\n } catch (err) {\n return failure(c, err, 'review approve');\n }\n });\n\n // Conversational planning (ADR-0002): start the planner dialogue. The\n // response's plan carries conversationHistory; when tasks are non-empty the\n // planner committed the plan.\n router.post('/:sessionId/converse/start', async (c) => {\n try {\n const { goal, runners, workspace, model, allowInit } = await jsonObject<{\n goal?: string; runners?: string[]; workspace?: string; model?: string; allowInit?: boolean;\n }>(c);\n if (!goal) return c.json({ error: 'goal is required' }, 400);\n const ws = workspace || c.req.query('workspace') || process.cwd();\n // As in generate: none requested is read by the session, after its gate.\n const runnerList: string[] | undefined = Array.isArray(runners) ? runners : (runners ? [runners] : undefined);\n const plan = await pool.startPlanning(c.req.param('sessionId'), goal, runnerList, ws, model, { allowInit });\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'converse start', { message: 'Planning failed' });\n }\n });\n\n // One branch for every user reply — clarifying answers, outline confirm.\n // The planner decides what happens next.\n router.post('/:sessionId/converse/message', async (c) => {\n try {\n const { message } = await jsonObject<{ message?: string }>(c);\n if (!message) return c.json({ error: 'message is required' }, 400);\n const plan = await pool.continuePlanning(c.req.param('sessionId'), message);\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'conversation message');\n }\n });\n\n // Send now (ADR-0023): stops the planner turn in flight — never the run's\n // tasks — and answers this message in the turn that replaces it, ahead of\n // anything waiting. With no turn in flight it is the plain send above.\n router.post('/:sessionId/converse/message/now', async (c) => {\n try {\n const { message } = await jsonObject<{ message?: string }>(c);\n if (!message) return c.json({ error: 'message is required' }, 400);\n const plan = await pool.forceSendPrompt(c.req.param('sessionId'), message);\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'conversation message');\n }\n });\n\n // What waits on the planner's usage limit then goes with the user's next\n // message instead of at the reset; `cancelled` is false when nothing waited.\n router.post('/:sessionId/converse/resend/cancel', (c) => {\n try {\n const cancelled = pool.session(c.req.param('sessionId')).cancelPlannerResend();\n return c.json({ cancelled } satisfies CancelResumeResponse);\n } catch (err) {\n return failure(c, err, 'cancel resend', { fallback: 404, message: 'Not found' });\n }\n });\n\n // Fork and rewind act on the conversation, never on the plan: the task list\n // rides along as-is (ADR-0002, update of 2026-09-25). A rewind is a fork from\n // just before a user message; the original session is left as it was.\n router.post('/:sessionId/conversation/fork', (c) => {\n try {\n const fork = pool.forkConversation(c.req.param('sessionId'));\n return c.json({ ...fork, plan: surfacePlan(fork.plan) } satisfies ConversationForkResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n router.get('/:sessionId/conversation/rewind-targets', (c) => {\n try {\n return c.json({ targets: pool.session(c.req.param('sessionId')).rewindTargets() } satisfies RewindTargetsResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n router.post('/:sessionId/conversation/rewind', async (c) => {\n try {\n const { index } = await jsonObject<{ index?: number }>(c);\n if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) return c.json({ error: 'index must be a non-negative integer' }, 400);\n const rewound = pool.rewindConversation(c.req.param('sessionId'), index);\n return c.json({ ...rewound, plan: surfacePlan(rewound.plan) } satisfies ConversationRewindResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n // The summary is one planner call, so this can take as long as a reply and\n // fail like one — a failure leaves the conversation exactly as it was.\n router.post('/:sessionId/conversation/compact', async (c) => {\n try {\n const compacted = await pool.compactConversation(c.req.param('sessionId'));\n return c.json({ ...compacted, plan: surfacePlan(compacted.plan) } satisfies ConversationCompactResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n // Retry compaction of a planner paused on its context (ADR-0002): the\n // paused turn opens again on the inputs it kept, and this answers once it\n // has landed — or paused again, which the plan's pause says. A stop of the\n // planner ends it, as it ends any turn.\n router.post('/:sessionId/conversation/compact/retry', async (c) => {\n try {\n const plan = await pool.retryPlannerCompaction(c.req.param('sessionId'));\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'retry compaction');\n }\n });\n\n router.get('/:sessionId/prd', (c) => {\n const plan = pool.getPlan(c.req.param('sessionId'));\n if (!plan?.prdMarkdown) return refuse(c, 404, 'No PRD found');\n return c.json({ prdMarkdown: plan.prdMarkdown } satisfies PrdResponse);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { installedPlannerDetected, type OkResponse, type RunnersResponse } from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\n\nexport function runnersRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', async (c) => {\n // getInstalledRunners re-probes the host first, so the state read after it\n // reflects the fresh answer rather than the stale default. A workspace's\n // own `.envrc` can choose the account, so the probe and the planner's\n // model are judged for the one that will plan rather than the daemon's cwd.\n const workspace = c.req.query('workspace');\n const runners = await pool.getInstalledRunners(workspace);\n await pool.discoverPlannerCatalogs(undefined, workspace);\n const state = pool.getRunnerState(workspace);\n return c.json({\n runners,\n orchestratorModel: state.orchestratorModel,\n } satisfies RunnersResponse);\n });\n\n router.put('/:id', async (c) => {\n try {\n // A toggle saves the enabled set it changes; built on the stale default,\n // it would save claude-code over the installed agents the probe finds.\n await installedPlannerDetected();\n const id = c.req.param('id');\n const { enabled } = await jsonObject<{ enabled?: unknown }>(c);\n // A missing value is not `false`: before this, `{}` disabled the runner\n // while answering 200.\n if (typeof enabled !== 'boolean') return refuse(c, 400, 'enabled must be true or false');\n pool.setRunnerEnabled(id, enabled);\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'runner toggle', { fallback: 400 });\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport type { ModelsResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\n\nexport function modelsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', async (c) => {\n // The catalog of the workspace's own runner environment, as its login verdict is.\n const result: ModelsResponse = await pool.getProviderModels(c.req.query('workspace'));\n return c.json(result);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { assertWorkspaceExists, type IsolationPreviewResponse, type WorkspacesResponse } from '@ordewell/core';\nimport { OrchestratorPool, scanWorkspaces } from '../pool/orchestratorPool';\nimport { failure } from './errors';\n\nexport function workspacesRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n // A read-only sibling of the list: it names the repositories behind one\n // workspace, while `/` keeps listing the workspaces sessions are saved under.\n router.get('/isolation-preview', async (c) => {\n try {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n const preview = await pool.previewIsolation(workspace);\n return c.json({ preview } satisfies IsolationPreviewResponse);\n } catch (err) {\n return failure(c, err, 'read isolation preview', { message: 'Could not read the repositories' });\n }\n });\n\n router.get('/', (c) => {\n const workspaces = scanWorkspaces();\n return c.json({ workspaces } satisfies WorkspacesResponse);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { isGranted, toApprovalDecision, type ApprovalAnswer, type ApprovalAnswerResponse, type ApprovalsResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { refuse } from './errors';\n\n/**\n * A body's answer. `{ decision, note? }` carries a runner request's whole\n * answer (ADR-0018, A1); `{ granted }` is the planner prompt's yes/no.\n * Anything else — absent, malformed, an unknown decision — is a denial,\n * never consent.\n */\nfunction answerOf(body: unknown): ApprovalAnswer {\n if (typeof body !== 'object' || body === null) return false;\n const { decision, note, granted } = body as { decision?: unknown; note?: unknown; granted?: unknown };\n if (decision === undefined) return granted === true;\n if (decision === 'allow' || decision === 'allowForTask') return { decision };\n if (decision === 'deny' && typeof note === 'string' && note.trim()) return { decision, note: note.trim() };\n return { decision: 'deny' };\n}\n\n/**\n * The answer channel for approval prompts — the planner's, and a task\n * runner's tool requests.\n *\n * Requests go out over the session WebSocket (they are ordinary\n * SessionMessages), but answers come back here rather than over the socket:\n * the CLI and TUI already speak HTTP to this server, a prompt can outlive the\n * socket that announced it, and a plain POST is answerable from any surface —\n * including `curl` in a pinch.\n */\nexport function approvalsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/:sessionId', (c) => {\n const sessionId = c.req.param('sessionId');\n if (!pool.hasSession(sessionId)) return refuse(c, 404, `Unknown session: ${sessionId}`, 'session_not_found');\n\n return c.json({\n pending: pool.outstandingApprovals(sessionId),\n approvedScopes: pool.approvedScopes(sessionId),\n } satisfies ApprovalsResponse);\n });\n\n router.post('/:sessionId/:approvalId', async (c) => {\n const sessionId = c.req.param('sessionId');\n const approvalId = c.req.param('approvalId');\n if (!pool.hasSession(sessionId)) return refuse(c, 404, `Unknown session: ${sessionId}`, 'session_not_found');\n\n const answer = answerOf(await c.req.json().catch(() => null));\n const decided = toApprovalDecision(answer);\n // A runner request goes through the command seam as the user's answer, so\n // their action is kept in the timeline (ADR-0029). The planner's own\n // prompt is no execution action and is answered directly.\n const request = pool.outstandingApprovals(sessionId).find((pending) => pending.id === approvalId)?.request;\n if (request?.taskId) {\n const outcome = await pool.session(sessionId).execute(\n { command: 'answer_approval', task: request.taskId, approval: approvalId, answer: decided.decision, ...(decided.decision === 'deny' && decided.note ? { note: decided.note } : {}) },\n { kind: 'user' },\n );\n if (!outcome.ok) return refuse(c, 400, outcome.message, 'refused');\n } else if (!pool.resolveApproval(sessionId, approvalId, answer)) {\n return refuse(c, 409, 'Approval is no longer outstanding: it timed out or was already answered.', 'approval_not_outstanding');\n }\n return c.json({ ok: true, granted: isGranted(decided), decision: decided.decision } satisfies ApprovalAnswerResponse);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { RunSettingsError, containersOffered, installedPlannerDetected, type ContainerChange, type ContainerChangeResponse, type ContainerStatus, type GlobalRunSettings, type SettingsResponse, type SettingsUpdateResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\n\n/** One change, so a surface cannot half-apply two; `changeContainers` judges what it holds. */\nfunction containerChange(body: Record<string, unknown>): ContainerChange | null {\n const change = Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'workspace'));\n if (Object.keys(change).length !== 1) return null;\n if (typeof change.on === 'boolean') return { on: change.on };\n if (typeof change.image === 'string') return { image: change.image };\n return 'login' in change ? { login: change.login } : null;\n}\n\nexport function settingsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n // Not there at all in a build that does not offer containers (ADR-0059 L5):\n // the same answer as any other route it does not have.\n router.use('/containers', async (c, next) => {\n if (!containersOffered()) return refuse(c, 404, 'This build does not offer containers');\n return next();\n });\n\n router.get('/containers', async (c) => {\n try {\n const status: ContainerStatus = await pool.containerStatus(c.req.query('prove') === '1', c.req.query('workspace') || undefined);\n return c.json(status);\n } catch (err) {\n return failure(c, err, 'containers status');\n }\n });\n\n router.patch('/containers', async (c) => {\n try {\n const body = await jsonObject(c);\n const change = containerChange(body);\n if (!change) return refuse(c, 400, 'One of on, image or login is required');\n const { workspace } = body;\n const result: ContainerChangeResponse = await pool.changeContainers(change, typeof workspace === 'string' ? workspace || undefined : undefined);\n return c.json(result);\n } catch (err) {\n return failure(c, err, 'containers change', { fallback: 400 });\n }\n });\n\n // Both wait for the startup probe (ADR-0009): the TUI reads the planner from\n // here the moment it opens, and a /planner switch is judged against the\n // planner in effect, which the probe may be about to change.\n router.get('/', async (c) => {\n await installedPlannerDetected();\n // An open session answers with its own run settings; no id or an id it no\n // longer holds answers with the file's, which a new session starts from\n // (ADR-0030). The planner's model is judged against the runner catalog of\n // the session's workspace, else of the one the client is in, waited for\n // only where it decides that model (ADR-0040).\n const sessionId = c.req.query('sessionId') || undefined;\n const workspace = c.req.query('workspace') || undefined;\n await pool.discoverPlannerCatalogs(sessionId, workspace);\n const settings: SettingsResponse = pool.getSettings(sessionId, workspace);\n return c.json(settings);\n });\n\n router.patch('/', async (c) => {\n try {\n await installedPlannerDetected();\n const body = await jsonObject(c);\n // Every client names its workspace, which is not itself a change.\n if (Object.keys(body).every((key) => key === 'workspace')) {\n return refuse(c, 400, 'At least one setting field is required');\n }\n // Run settings (ADR-0030) are named fields under `run`, never environment\n // variables; `sessionId` is the session the change was made in, and\n // `workspace` the one the client is in, whose catalog a pick is judged by.\n const { run, sessionId: namedSession, workspace: namedWorkspace, ...rest } = body;\n if (namedSession !== undefined && typeof namedSession !== 'string') return refuse(c, 400, 'sessionId must be a string');\n if (namedWorkspace !== undefined && typeof namedWorkspace !== 'string') return refuse(c, 400, 'workspace must be a string');\n const sessionId = namedSession || undefined;\n const workspace = namedWorkspace || undefined;\n if (run !== undefined) {\n if (!run || typeof run !== 'object' || Array.isArray(run)) return refuse(c, 400, 'run must be an object of run settings');\n try {\n pool.updateRunSettings(run as Partial<GlobalRunSettings>, sessionId, workspace);\n } catch (err) {\n if (err instanceof RunSettingsError) return refuse(c, 400, err.message);\n throw err;\n }\n }\n // Only a planner switch waits for a catalog, the one it is judged\n // against, which no client has asked for yet when it switches (ADR-0040).\n const result: SettingsUpdateResponse = Object.keys(rest).length > 0\n ? await pool.writeSettings(rest, sessionId, workspace)\n : pool.getSettings(sessionId, workspace);\n return c.json(result);\n } catch (err) {\n return failure(c, err, 'settings update', { fallback: 400 });\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport type { CommandDescriptor, CommandsResponse } from '@ordewell/core';\nimport { refuse } from './errors';\n\n// Every command this route ran was a mode toggle, and none is left; the\n// route stays so a client listing commands still gets an answer.\nconst COMMANDS: CommandDescriptor[] = [];\n\nexport function commandsRoute() {\n const router = new Hono();\n\n router.get('/', (c) => {\n return c.json({ commands: COMMANDS } satisfies CommandsResponse);\n });\n\n router.post('/:name', (c) => {\n const name = c.req.param('name');\n return refuse(c, 404, `Unknown command: ${name}`);\n });\n\n return router;\n}\n","import { Hono, type Context } from 'hono';\nimport {\n assertWorkspaceExists,\n WorkspaceReadError,\n type FileContentResponse,\n type FileFindResponse,\n type FileTreeResponse,\n type GitBranchesResponse,\n type GitCommitResponse,\n type GitDiffResponse,\n type GitLogResponse,\n type GitReposResponse,\n type GitStatusResponse,\n type ReadTarget,\n type TaskDiffResponse,\n type ViewScopeKind,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { failure } from './errors';\n\n/*\n * The user principal's reads of a workspace's files and git (ADR-0064): every\n * route is a GET, takes its workspace per request, and answers from the\n * reader alone. None touches the pool, so none takes or waits on a session's\n * lease (R4), and a session another host holds is read all the same.\n */\n\nconst SCOPES: readonly ViewScopeKind[] = ['checkout', 'integration', 'task'];\n\nfunction workspaceOf(c: Context): string {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n return workspace;\n}\n\nfunction targetOf(c: Context): ReadTarget {\n const scope = c.req.query('scope');\n if (scope !== undefined && !(SCOPES as readonly string[]).includes(scope)) {\n throw new WorkspaceReadError('refused', `Unknown scope \"${scope}\": name ${SCOPES.join(', ')}.`);\n }\n const target: ReadTarget = { workspace: workspaceOf(c) };\n const repo = c.req.query('repo');\n const sessionId = c.req.query('sessionId');\n const taskId = c.req.query('taskId');\n if (repo) target.repo = repo;\n if (scope) target.scope = scope as ViewScopeKind;\n if (sessionId) target.sessionId = sessionId;\n if (taskId) target.taskId = taskId;\n return target;\n}\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name);\n if (!value) throw new WorkspaceReadError('refused', `Name the ${name} to read.`);\n return value;\n}\n\nfunction flag(c: Context, name: string): boolean {\n const value = c.req.query(name);\n return value === '1' || value === 'true';\n}\n\nfunction count(c: Context, name: string): number | undefined {\n const value = c.req.query(name);\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isInteger(n) || n < 1) throw new WorkspaceReadError('refused', `\"${name}\" must be a positive whole number.`);\n return n;\n}\n\nfunction optional(c: Context, name: string): string | undefined {\n return c.req.query(name) || undefined;\n}\n\n/** A route body that answers what the reader read, or the classified refusal. */\nfunction read<T>(label: string, answer: (c: Context) => Promise<T>) {\n return async (c: Context) => {\n try {\n return c.json(await answer(c));\n } catch (err) {\n return failure(c, err, label, { message: 'Could not read the workspace' });\n }\n };\n}\n\n/** `/api/files`: a scope's tree, one file's content, and search by name or text. */\nexport function filesRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/tree', read('read tree', (c) => reader.tree(targetOf(c), c.req.query('dir') ?? '') satisfies Promise<FileTreeResponse>));\n router.get('/content', read('read file', async (c) => {\n const target = targetOf(c);\n return reader.content(target, required(c, 'path')) satisfies Promise<FileContentResponse>;\n }));\n router.get('/find', read('find files', async (c) => {\n const target = targetOf(c);\n return reader.find(target, { query: required(c, 'query'), text: flag(c, 'text'), limit: count(c, 'limit') }) satisfies Promise<FileFindResponse>;\n }));\n return router;\n}\n\n/** `/api/git`: the workspace's repositories, and per repository its status, diffs, history and branches. */\nexport function gitRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/repos', read('read repositories', (c) => reader.repos(workspaceOf(c)) satisfies Promise<GitReposResponse>));\n router.get('/status', read('read status', (c) => reader.status(targetOf(c)) satisfies Promise<GitStatusResponse>));\n router.get('/diff', read('read diff', async (c) => {\n const target = targetOf(c);\n const kind = c.req.query('kind');\n if (kind !== undefined && kind !== 'staged' && kind !== 'unstaged') throw new WorkspaceReadError('refused', `Unknown diff kind \"${kind}\": name staged or unstaged.`);\n return reader.diff(target, { kind, from: optional(c, 'from'), to: optional(c, 'to'), path: optional(c, 'path') }) satisfies Promise<GitDiffResponse>;\n }));\n router.get('/log', read('read log', async (c) => {\n const target = targetOf(c);\n return reader.log(target, { ref: optional(c, 'ref'), cursor: optional(c, 'cursor'), limit: count(c, 'limit') }) satisfies Promise<GitLogResponse>;\n }));\n router.get('/commit', read('read commit', async (c) => {\n const target = targetOf(c);\n return reader.commit(target, required(c, 'sha'), optional(c, 'path')) satisfies Promise<GitCommitResponse>;\n }));\n router.get('/branches', read('read branches', (c) => reader.branches(targetOf(c)) satisfies Promise<GitBranchesResponse>));\n return router;\n}\n\n/**\n * `GET /api/plans/:sessionId/tasks/:taskId/diff`: one task's diff from the\n * saved run, as `readTaskDiff` reads it for a verdict. Mounted beside\n * `plansRoute` rather than in it, since it reads the saved session and never\n * the pool's live one.\n */\nexport function taskDiffRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/:sessionId/tasks/:taskId/diff', read('read task diff', (c) => reader.taskDiff(workspaceOf(c), c.req.param('sessionId') ?? '', c.req.param('taskId') ?? '', {\n repo: optional(c, 'repo'), path: optional(c, 'path'), names: flag(c, 'names'),\n }) satisfies Promise<TaskDiffResponse>));\n return router;\n}\n","import { Hono, type Context } from 'hono';\nimport {\n assertWorkspaceExists,\n type GitActionResponse,\n type MergePreflightResponse,\n type UserGit,\n type UserGitScope,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { failure, InvalidBodyError, jsonObject } from './errors';\n\n/*\n * The user's git actions on their own checkout (ADR-0062). Each takes its\n * workspace and repository in the body and acts through the user's git. None\n * touches a session's lease: an action asks the pool only whether a run is\n * live and where its timeline is, so a session another host holds is no bar.\n */\n\ntype Body = Record<string, unknown>;\n\n/** The service trusts its types, so every body field is checked here: a wrong one is the request's fault, never a fault of git. */\nfunction bad(message: string): never {\n throw new InvalidBodyError(message);\n}\n\nfunction text(body: Body, name: string): string {\n const value = body[name];\n if (typeof value !== 'string') bad(`\"${name}\" must be a string.`);\n return value;\n}\n\nfunction optionalText(body: Body, name: string): string | undefined {\n return body[name] === undefined ? undefined : text(body, name);\n}\n\nfunction texts(body: Body, name: string): string[] | undefined {\n const value = body[name];\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || !value.every((v): v is string => typeof v === 'string')) bad(`\"${name}\" must be a list of strings.`);\n return value;\n}\n\nfunction yes(body: Body, name: string): boolean | undefined {\n const value = body[name];\n if (value === undefined) return undefined;\n if (typeof value !== 'boolean') bad(`\"${name}\" must be true or false.`);\n return value;\n}\n\n/** The `confirm` the surface echoes back: what it showed the person (G3). Absent reads as an empty one, so every field it lacks is stale. */\nfunction confirmOf(body: Body): Body {\n const value = body.confirm;\n if (value === undefined) return {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) bad('\"confirm\" must be an object.');\n return value as Body;\n}\n\nfunction scopeOf(body: Body): UserGitScope {\n const workspace = optionalText(body, 'workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n const repo = optionalText(body, 'repo');\n return repo ? { workspace, repo } : { workspace };\n}\n\nfunction changes(body: Body) {\n const paths = texts(body, 'paths');\n const hunks = optionalText(body, 'hunks');\n if ((paths === undefined) === (hunks === undefined)) bad('Name either \"paths\" or \"hunks\".');\n return hunks !== undefined ? { hunks } : { paths };\n}\n\n/** A route body that answers the repository's state after the action, or the classified refusal. */\nfunction act(label: string, action: (scope: UserGitScope, body: Body) => Promise<GitActionResponse>) {\n return async (c: Context) => {\n try {\n const body = await jsonObject(c);\n return c.json(await action(scopeOf(body), body) satisfies GitActionResponse);\n } catch (err) {\n return failure(c, err, label, { message: 'Could not act on the repository' });\n }\n };\n}\n\n/** `PUT /api/files/content`: a save of a file read at `baseHash` (G10). */\nexport function fileWriteRoute(git: UserGit) {\n const router = new Hono();\n router.put('/content', act('save file', (scope, body) => {\n const baseHash = body.baseHash === null ? null : text(body, 'baseHash');\n return git.save(scope, { path: text(body, 'path'), text: text(body, 'text'), baseHash });\n }));\n return router;\n}\n\n/** `POST /api/git/*`: the v1 action set, each on the user's checkout of one repository. */\nexport function gitWriteRoute(git: UserGit) {\n const router = new Hono();\n router.post('/stage', act('stage', (scope, body) => git.stage(scope, changes(body))));\n router.post('/unstage', act('unstage', (scope, body) => git.unstage(scope, changes(body))));\n router.post('/commit', act('commit', (scope, body) => {\n const amend = yes(body, 'amend');\n const head = confirmOf(body).head;\n return git.commit(scope, {\n message: text(body, 'message'),\n ...(amend !== undefined ? { amend } : {}),\n ...(typeof head === 'string' ? { confirm: { head } } : {}),\n });\n }));\n router.post('/discard', act('discard', (scope, body) => {\n const files = texts(confirmOf(body), 'files') ?? [];\n return git.discard(scope, { ...changes(body), confirm: { files } });\n }));\n router.post('/branch', act('create branch', (scope, body) => {\n const from = optionalText(body, 'from');\n const switching = yes(body, 'switch');\n return git.createBranch(scope, { name: text(body, 'name'), ...(from !== undefined ? { from } : {}), ...(switching !== undefined ? { switch: switching } : {}) });\n }));\n router.post('/switch', act('switch branch', (scope, body) => git.switchBranch(scope, { branch: text(body, 'branch') })));\n router.post('/branch-delete', act('delete branch', (scope, body) => {\n const confirm = confirmOf(body);\n const shown = typeof confirm.branch === 'string' ? confirm.branch : '';\n if (typeof confirm.unmerged !== 'boolean') bad('\"confirm.unmerged\" must say whether the branch was shown as unmerged.');\n return git.deleteBranch(scope, { branch: text(body, 'branch'), confirm: { branch: shown, unmerged: confirm.unmerged } });\n }));\n router.post('/stash', act('stash', (scope, body) => {\n const paths = texts(body, 'paths');\n const message = optionalText(body, 'message');\n return git.stash(scope, { ...(paths !== undefined ? { paths } : {}), ...(message !== undefined ? { message } : {}) });\n }));\n router.post('/stash-pop', act('pop stash', (scope, body) => git.stashPop(scope, { stash: text(body, 'stash') })));\n router.post('/stash-drop', act('drop stash', (scope, body) => git.stashDrop(scope, { stash: text(body, 'stash') })));\n router.post('/fetch', act('fetch', (scope) => git.fetch(scope)));\n const remote = (body: Body) => {\n const confirm = confirmOf(body);\n return { remote: typeof confirm.remote === 'string' ? confirm.remote : '', branch: typeof confirm.branch === 'string' ? confirm.branch : '' };\n };\n router.post('/pull', act('pull', (scope, body) => git.pull(scope, { confirm: remote(body) })));\n router.post('/push', act('push', (scope, body) => git.push(scope, { confirm: remote(body) })));\n return router;\n}\n\n/**\n * `GET /api/plans/:sessionId/isolation/merge-preflight` (G8): per repository,\n * the user's uncommitted files Merge all would collide with. A read of the\n * saved run, so it needs neither the session open here nor its lease.\n */\nexport function mergePreflightRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/:sessionId/isolation/merge-preflight', async (c) => {\n try {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n return c.json(await reader.mergePreflight(workspace, c.req.param('sessionId') ?? '') satisfies MergePreflightResponse);\n } catch (err) {\n return failure(c, err, 'merge preflight', { message: 'Could not read the run' });\n }\n });\n return router;\n}\n","import { WebSocketServer, WebSocket } from 'ws';\nimport type { IncomingMessage } from 'http';\nimport type { Duplex } from 'stream';\nimport { DAEMON_SUBPROTOCOL, type RunSnapshotFrame, type SessionFrame } from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\n\nconst CHILD_PATH = /^\\/ws\\/session\\/([^/]+)\\/child\\/([^/]+)$/;\n\n/** Nothing is sent before the tree has named the child, so a stray id learns only that it was refused. */\nfunction joinChild(pool: OrchestratorPool, ws: WebSocket, rootId: string, childId: string): void {\n const leave = () => pool.unwatchChild(rootId, childId, ws);\n ws.on('close', leave);\n ws.on('error', leave);\n const refuse = () => ws.close(4404, 'No such child plan in this tree');\n void pool.watchChild(rootId, childId, ws).then((watching) => { if (!watching) refuse(); }, refuse);\n}\n\nexport function createWsHandler(pool: OrchestratorPool) {\n const wss = new WebSocketServer({\n noServer: true,\n // Select the plain subprotocol explicitly. Left to itself `ws` echoes back\n // whichever was offered first, which would put the token in the 101\n // response; selecting nothing makes the client fail the handshake.\n handleProtocols: (protocols) => (protocols.has(DAEMON_SUBPROTOCOL) ? DAEMON_SUBPROTOCOL : false),\n });\n\n wss.on('connection', (ws: WebSocket, request: IncomingMessage) => {\n const url = new URL(request.url ?? '', `http://${request.headers.host}`);\n const child = CHILD_PATH.exec(url.pathname);\n if (child) {\n joinChild(pool, ws, child[1], child[2]);\n return;\n }\n const sessionId = url.pathname.split('/').pop() || '';\n\n ws.on('close', () => {\n pool.unsubscribe(sessionId, ws);\n });\n\n ws.on('error', () => {\n pool.unsubscribe(sessionId, ws);\n });\n\n ws.send(JSON.stringify({ type: 'connected', sessionId }));\n // The stream reports changes only. Taken and subscribed in one turn, so no\n // broadcast can fall between the snapshot and the first message after it.\n const view = pool.runSnapshot(sessionId);\n if (view) {\n ws.send(JSON.stringify({\n type: 'run_snapshot', sessionId, view, approvals: pool.announcedApprovals(sessionId), ...pool.streamPosition(sessionId),\n } satisfies RunSnapshotFrame));\n }\n // A compaction has no turn id to adopt, so a client joining mid-way would\n // not know the planner is busy. Unstamped: the client's fold is idempotent\n // by the compaction's id, and a stamp would let it count this as the\n // broadcast it already holds.\n const compaction = pool.plannerCompaction(sessionId);\n if (compaction) ws.send(JSON.stringify(compaction satisfies SessionFrame));\n // Nor has a turn at the planner gate, which no planner has heard of yet.\n const detection = pool.plannerDetection(sessionId);\n if (detection?.waiting) ws.send(JSON.stringify(detection satisfies SessionFrame));\n // Subscribing also greets with host-owned account limits, independently\n // of the run snapshot above, even when the host knows none yet.\n pool.subscribe(sessionId, ws);\n });\n\n return (request: IncomingMessage, socket: Duplex, head: Buffer) => {\n wss.handleUpgrade(request, socket, head, (ws) => {\n wss.emit('connection', ws, request);\n });\n };\n}\n","/**\n * The single admission decision for the daemon.\n *\n * Both the HTTP middleware and the WebSocket upgrade handler call this. The\n * sharing is the point: the two paths drifting apart is how the upgrade ended\n * up validating nothing while the HTTP routes had a CORS allowlist.\n */\n\nimport { extractPresentedToken, tokensMatch } from '@ordewell/core';\n\n/** `localhost` is included because clients dial it by name; the daemon binds loopback only. */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nexport interface AdmissionHeaders {\n /** `null`/`undefined` mean absent. An empty string still counts as present. */\n origin?: string | null;\n host?: string | null;\n /** `Authorization: Bearer <token>` — how the token travels on HTTP routes. */\n authorization?: string | null;\n /** `Sec-WebSocket-Protocol` — how it travels on the upgrade, so it stays out of logs. */\n secWebSocketProtocol?: string | null;\n}\n\n/** What this daemon is: which port it bound, and which token it minted. */\nexport interface AdmissionContext {\n port: number;\n token: string;\n /** Named in a token rejection, so a stale token is diagnosable rather than a bare failure. */\n tokenFile: string;\n}\n\nexport type AdmissionDecision =\n | { admit: true }\n | { admit: false; status: number; reason: string };\n\nconst ADMIT: AdmissionDecision = { admit: true };\n\nexport function decideAdmission(\n headers: AdmissionHeaders,\n context: AdmissionContext,\n): AdmissionDecision {\n if (headers.origin !== undefined && headers.origin !== null) {\n return {\n admit: false,\n status: 403,\n reason: 'Refused: requests carrying an Origin header are not accepted. The Ordewell daemon has no browser client.',\n };\n }\n\n if (!isOwnLoopbackAuthority(headers.host, context.port)) {\n return {\n admit: false,\n status: 403,\n reason: `Refused: the Host header must name loopback (localhost, 127.0.0.1 or [::1]) at port ${context.port}.`,\n };\n }\n\n if (!tokensMatch(extractPresentedToken(headers), context.token)) {\n return {\n admit: false,\n status: 401,\n reason:\n 'Unauthenticated: this request did not present the daemon\\'s bearer token. '\n + `Ordewell clients read it from ${context.tokenFile}; if that file is stale, `\n + 'restart the daemon (`ordewell web --daemon`) to mint a fresh one.',\n };\n }\n\n return ADMIT;\n}\n\n/**\n * Rejecting anything but our own loopback authority is what closes DNS\n * rebinding: a page rebinding a hostname it controls to 127.0.0.1 still sends\n * that hostname in `Host`, and same-origin requests to it carry no `Origin`.\n */\nfunction isOwnLoopbackAuthority(host: string | null | undefined, port: number): boolean {\n if (!host) return false;\n const authority = splitAuthority(host);\n if (!authority) return false;\n if (!LOOPBACK_HOSTNAMES.has(authority.hostname.toLowerCase())) return false;\n return authority.port === port;\n}\n\n/** Absent port means the scheme default; the daemon only ever speaks http. */\nconst DEFAULT_HTTP_PORT = 80;\n\nfunction splitAuthority(host: string): { hostname: string; port: number } | undefined {\n const value = host.trim();\n if (value === '') return undefined;\n\n if (value.startsWith('[')) {\n const close = value.indexOf(']');\n if (close === -1) return undefined;\n const hostname = value.slice(1, close);\n const rest = value.slice(close + 1);\n if (rest === '') return { hostname, port: DEFAULT_HTTP_PORT };\n if (!rest.startsWith(':')) return undefined;\n return withPort(hostname, rest.slice(1));\n }\n\n const colon = value.indexOf(':');\n if (colon === -1) return { hostname: value, port: DEFAULT_HTTP_PORT };\n // An unbracketed second colon is a bare IPv6 literal, which is malformed in a\n // Host header — refuse rather than guess where the port starts.\n if (value.indexOf(':', colon + 1) !== -1) return undefined;\n return withPort(value.slice(0, colon), value.slice(colon + 1));\n}\n\nfunction withPort(hostname: string, port: string): { hostname: string; port: number } | undefined {\n if (!/^\\d+$/.test(port)) return undefined;\n return { hostname, port: Number(port) };\n}\n","import { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { seaVersion, type SeaDeps } from '@ordewell/core';\n\nlet cached: string | undefined;\n\n/**\n * This daemon's `@ordewell/web` version, for `GET /api/server` (ADR-0063 H3).\n * Found by walking up to the package's own manifest rather than a fixed\n * `..`: the tsup bundle runs from `dist/server/` and the tests from\n * `server/utils/`, and a fixed hop count breaks on whichever moves next.\n * Inside the standalone binary there is no manifest to walk to, and the daemon\n * is the binary itself, so its version is the one the build embedded\n * (ADR-0065 C2, C3).\n */\nexport function serverVersion(from: string = __dirname, sea: SeaDeps = {}): string {\n const embedded = embeddedVersion(sea);\n if (embedded) return embedded;\n if (cached !== undefined) return cached;\n cached = findVersion(from);\n return cached;\n}\n\nfunction embeddedVersion(sea: SeaDeps): string | undefined {\n try {\n return seaVersion(sea);\n } catch {\n // A binary whose manifest cannot be read still answers the API.\n return 'unknown';\n }\n}\n\nfunction findVersion(from: string): string {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n const pkg: unknown = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));\n const { name, version } = pkg as { name?: unknown; version?: unknown };\n if (name === '@ordewell/web' && typeof version === 'string' && version) return version;\n } catch {\n // No manifest here, or not one we can read: keep walking.\n }\n if (dirname(dir) === dir) return 'unknown';\n }\n}\n","import { Hono } from 'hono';\nimport type { Server } from 'http';\nimport type { Duplex } from 'stream';\nimport { childrenRoute } from './routes/children';\nimport { sessionsRoute } from './routes/sessions';\nimport { plansRoute } from './routes/plans';\nimport { runnersRoute } from './routes/runners';\nimport { modelsRoute } from './routes/models';\nimport { workspacesRoute } from './routes/workspaces';\nimport { approvalsRoute } from './routes/approvals';\nimport { settingsRoute } from './routes/settings';\nimport { commandsRoute } from './routes/commands';\nimport { filesRoute, gitRoute, taskDiffRoute } from './routes/workspaceRead';\nimport { fileWriteRoute, gitWriteRoute, mergePreflightRoute } from './routes/workspaceWrite';\nimport { WebConfig } from './adapters/WebConfig';\nimport { createWsHandler } from './ws/stream';\nimport {\n decideAdmission,\n type AdmissionContext,\n type AdmissionDecision,\n} from './security/admission';\nimport { OrchestratorPool } from './pool/orchestratorPool';\nimport {\n DAEMON_CONTRACT,\n createUserGit,\n createWorkspaceReader,\n landingRuns,\n type ServerInfoResponse,\n type UserGit,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { serverVersion } from './utils/serverVersion';\n\n/**\n * The user's git actions (ADR-0062). The pool answers only whether a run is\n * live and where its timeline is: an action never takes a session's lease.\n */\nexport function userGitFor(pool: OrchestratorPool, reader: WorkspaceReader): UserGit {\n return createUserGit({\n reader,\n landingRuns: (checkout) => landingRuns(checkout, (workspace, sessionId, plan) => pool.userRunIsLive(sessionId, workspace, plan)),\n record: (workspace, held, text) => pool.recordUserAction(held.sessionId, workspace, text),\n });\n}\n\nexport function createApp(\n pool: OrchestratorPool,\n admission: AdmissionContext,\n reader: WorkspaceReader = createWorkspaceReader({ config: new WebConfig() }),\n userGit: UserGit = userGitFor(pool, reader),\n) {\n const app = new Hono();\n\n // There is no CORS allowlist: the daemon ships no browser front end, so a\n // browser has no legitimate reason to reach it at all. The bearer token\n // supersedes it, and covers every local caller rather than only browsers.\n app.use('*', async (c, next) => {\n const decision = decideAdmission({\n origin: c.req.header('origin') ?? null,\n // The request URL's authority is built from the Host header upstream, so\n // it is the same value; the fallback only matters when the header is\n // absent entirely, which fails the check anyway.\n host: c.req.header('host') ?? new URL(c.req.url).host,\n authorization: c.req.header('authorization') ?? null,\n }, admission);\n if (!decision.admit) return c.json({ error: decision.reason }, decision.status as 401 | 403);\n await next();\n });\n\n // `ordewell stop --server` verifies a PID file against the process that\n // actually owns the port before signalling anything, so a stale file cannot\n // terminate an unrelated process. The desktop app reads the version and the\n // contract before it drives a daemon it did not start (ADR-0063 H3), and a\n // newer CLI whether it may replace one it cannot drive (ADR-0048). Behind\n // admission like every other route.\n app.get('/api/server', (c) => c.json({\n pid: process.pid,\n port: admission.port,\n version: serverVersion(),\n contract: DAEMON_CONTRACT,\n live: pool.workLive(),\n } satisfies ServerInfoResponse));\n\n app.route('/api/sessions', sessionsRoute(pool));\n app.route('/api/sessions', childrenRoute(pool));\n app.route('/api/plans', plansRoute(pool));\n app.route('/api/plans', taskDiffRoute(reader));\n app.route('/api/plans', mergePreflightRoute(reader));\n app.route('/api/runners', runnersRoute(pool));\n app.route('/api/models', modelsRoute(pool));\n app.route('/api/settings', settingsRoute(pool));\n app.route('/api/commands', commandsRoute());\n app.route('/api/workspaces', workspacesRoute(pool));\n app.route('/api/approvals', approvalsRoute(pool));\n // The user's reads of files and git (ADR-0064): the reader, never the pool.\n app.route('/api/files', filesRoute(reader));\n app.route('/api/git', gitRoute(reader));\n // The user's actions on their own checkout (ADR-0062), beside those reads.\n app.route('/api/files', fileWriteRoute(userGit));\n app.route('/api/git', gitWriteRoute(userGit));\n\n return app;\n}\n\nexport function attachWsHandler(server: Server, pool: OrchestratorPool, admission: AdmissionContext) {\n const handler = createWsHandler(pool);\n server.on('upgrade', (request, socket, head) => {\n const decision = decideAdmission({\n origin: request.headers.origin ?? null,\n host: request.headers.host ?? null,\n authorization: request.headers.authorization ?? null,\n secWebSocketProtocol: request.headers['sec-websocket-protocol'] ?? null,\n }, admission);\n if (!decision.admit) {\n refuseUpgrade(socket, decision);\n return;\n }\n\n const url = new URL(request.url ?? '', `http://${request.headers.host}`);\n if (url.pathname.startsWith('/ws/session/')) {\n handler(request, socket, head);\n } else {\n socket.destroy();\n }\n });\n}\n\nconst REASON_PHRASE: Record<number, string> = { 401: 'Unauthorized', 403: 'Forbidden' };\n\nfunction refuseUpgrade(socket: Duplex, decision: Extract<AdmissionDecision, { admit: false }>): void {\n const body = JSON.stringify({ error: decision.reason });\n socket.end(\n `HTTP/1.1 ${decision.status} ${REASON_PHRASE[decision.status] ?? 'Forbidden'}\\r\\n` +\n 'Connection: close\\r\\n' +\n 'Content-Type: application/json\\r\\n' +\n `Content-Length: ${Buffer.byteLength(body)}\\r\\n` +\n `\\r\\n${body}`,\n );\n socket.destroy();\n}\n","import type { IncomingMessage, ServerResponse } from 'http';\nimport type { Hono } from 'hono';\nimport { decideAdmission, type AdmissionContext } from './security/admission';\n\n/**\n * How much of a request body the daemon will hold in memory. Plans, task edits\n * and conversation messages are small; a body past this is not one of ours.\n * Without a cap, the admission check below could never run before a browser's\n * multi-gigabyte `text/plain` POST was already buffered.\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024;\n\nclass BodyTooLargeError extends Error {}\n\n/** A body over the cap, or a request the admission check refused, answered and closed. */\nfunction refuse(req: IncomingMessage, res: ServerResponse, status: number, message: string): void {\n const payload = JSON.stringify({ error: message });\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(payload),\n // Nothing more is read from this request, so its connection cannot be reused.\n Connection: 'close',\n });\n res.end(payload, () => req.destroy());\n}\n\n/**\n * Read at most `max` bytes, leaving the stream paused once it is over. The\n * caller answers 413 and destroys the request; draining it instead would let a\n * browser keep the daemon busy for as long as it liked.\n */\nfunction readBody(req: IncomingMessage, max: number): Promise<string | undefined> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const cleanup = () => {\n req.off('data', onData);\n req.off('end', onEnd);\n req.off('error', onError);\n };\n const onData = (chunk: Buffer) => {\n size += chunk.length;\n if (size > max) {\n cleanup();\n req.pause();\n reject(new BodyTooLargeError());\n return;\n }\n chunks.push(chunk);\n };\n const onEnd = () => {\n cleanup();\n resolve(chunks.length > 0 ? Buffer.concat(chunks).toString() : undefined);\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n req.on('data', onData);\n req.on('end', onEnd);\n req.on('error', onError);\n });\n}\n\n/**\n * Bridges node's http server onto the Hono app. Kept out of `main.ts` so the\n * real request path — including the Host header the admission check reads — is\n * testable against a listening server.\n *\n * Admission runs here as well as in the Hono middleware, and first: the\n * middleware only sees the request after the body has been read, which is too\n * late to keep a browser from making the daemon buffer it.\n */\nexport function createRequestListener(app: Hono, admission: AdmissionContext, maxBodyBytes = MAX_BODY_BYTES) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const decision = decideAdmission({\n origin: req.headers.origin ?? null,\n host: req.headers.host ?? null,\n authorization: req.headers.authorization ?? null,\n }, admission);\n if (!decision.admit) {\n refuse(req, res, decision.status, decision.reason);\n return;\n }\n\n const declared = Number(req.headers['content-length']);\n if (Number.isFinite(declared) && declared > maxBodyBytes) {\n refuse(req, res, 413, `Request body must be at most ${maxBodyBytes} bytes.`);\n return;\n }\n\n let body: string | undefined;\n try {\n body = await readBody(req, maxBodyBytes);\n } catch (err) {\n if (err instanceof BodyTooLargeError) {\n refuse(req, res, 413, `Request body must be at most ${maxBodyBytes} bytes.`);\n return;\n }\n throw err;\n }\n\n const url = `http://${req.headers.host || 'localhost'}${req.url}`;\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (v) {\n if (Array.isArray(v)) v.forEach(vv => headers.append(k, vv));\n else headers.set(k, v as string);\n }\n }\n if (body && !headers.has('content-type')) headers.set('content-type', 'application/json');\n\n const webReq = new Request(url, {\n method: req.method || 'GET',\n headers,\n body: req.method !== 'GET' && req.method !== 'HEAD' ? body : undefined,\n });\n\n try {\n const webRes = await app.fetch(webReq);\n res.writeHead(webRes.status, Object.fromEntries(webRes.headers.entries()));\n if (webRes.body) {\n const reader = webRes.body.getReader();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n }\n res.end();\n } catch (err) {\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: err instanceof Error ? (err as Error).message : 'Internal server error' }));\n }\n }\n };\n}\n","import { createApp, attachWsHandler } from './app';\nimport { createRequestListener } from './nodeAdapter';\nimport { OrchestratorPool } from './pool/orchestratorPool';\nimport { createServer } from 'http';\nimport { mkdirSync, unlinkSync, writeFileSync } from 'fs';\nimport { dirname } from 'path';\nimport { clearDaemonToken, mintDaemonToken, processLeaseHost, StructuredRunner } from '@ordewell/core';\n\n/**\n * The daemon: the API server the CLI, the TUI and the desktop app drive over\n * 127.0.0.1. `main.ts` runs it with its own argv; the standalone CLI binary\n * runs it in-process as `ordewell __daemon ...`, having no server file to\n * spawn (ADR-0065). It owns the process from here on: its signal handlers end it.\n */\nexport function runDaemon(args: string[]): void {\n let port = 3742;\n\n const portIdx = args.indexOf('--port');\n if (portIdx !== -1 && args[portIdx + 1]) {\n port = parseInt(args[portIdx + 1], 10) || 3742;\n }\n\n // Set only for a daemon owned by one CLI invocation (e.g. `ordewell tui`),\n // which spawns it non-detached expecting it to die with the caller. A\n // closed terminal delivers SIGHUP to both via the shared process group, but\n // that misses a caller killed by PID directly or a multiplexer that doesn't\n // relay the signal — this poll is the fallback so an owned daemon never\n // outlives its CLI and orphans don't accumulate.\n const watchParentIdx = args.indexOf('--watch-parent');\n const watchParentPid = watchParentIdx !== -1 ? parseInt(args[watchParentIdx + 1], 10) : undefined;\n\n // Written by the daemon itself only once it is listening, and removed on\n // shutdown, so `ordewell stop --server` never reads an entry belonging to a\n // process that failed to bind or a daemon that is already gone.\n const pidFileIdx = args.indexOf('--pid-file');\n const pidFile = pidFileIdx !== -1 ? args[pidFileIdx + 1] : undefined;\n let ownsPidFile = false;\n\n // What another host's refusal names this one as (ADR-0049). Only a TUI starts\n // a daemon it watches, as its private one.\n processLeaseHost().describe({ kind: 'daemon', port, ...(watchParentPid ? { ownerPid: watchParentPid } : {}) });\n\n // Tasks run on the structured transport (ADR-0018) as plain child processes,\n // so one runner serves every plan whatever the host has.\n const pool = new OrchestratorPool({ runner: new StructuredRunner() });\n // Before listening, so the first request already finds the probe in flight\n // and waits on it rather than reading the openrouter fallback (ADR-0009).\n void pool.detectInstalledPlanner();\n const server = createServer();\n let ownsToken = false;\n\n server.listen(port, '127.0.0.1', () => {\n // A losing startup must not replace the listening daemon's credential.\n // This callback installs admission before the event loop can serve a request.\n const { token, file: tokenFile } = mintDaemonToken(port);\n ownsToken = true;\n if (pidFile) {\n mkdirSync(dirname(pidFile), { recursive: true });\n writeFileSync(pidFile, String(process.pid), { mode: 0o600 });\n ownsPidFile = true;\n }\n const admission = { port, token, tokenFile };\n const app = createApp(pool, admission);\n app.get('/', (c) => c.json({ message: 'Ordewell API', docs: '/api/workspaces' }));\n server.on('request', createRequestListener(app, admission));\n attachWsHandler(server, pool, admission);\n pool.getProviderModels().catch((err) => {\n console.error(`[web] model discovery warmup failed: ${err?.message ?? err}`);\n });\n console.error(`[web] Ordewell API server: http://localhost:${port}`);\n });\n\n function shutdown(): void {\n if (ownsToken) clearDaemonToken(port);\n if (ownsPidFile && pidFile) {\n try { unlinkSync(pidFile); } catch { /* already gone */ }\n }\n pool.destroyAll();\n server.close();\n process.exit(0);\n }\n\n // A stray rejection in one session's background work must not take every\n // session's runners down with the daemon.\n process.on('unhandledRejection', (reason) => {\n console.error(`[web] unhandled rejection: ${reason instanceof Error ? reason.stack ?? reason.message : String(reason)}`);\n });\n\n // A daemon this CLI owns shares its foreground process group. Ctrl-C while a\n // login child holds the terminal is a SIGINT to that whole group, and the TUI\n // ignores it so the child alone is cancelled; shutting down here would take\n // every in-memory session with it. The owner stops us with SIGTERM, and the\n // parent watch below still catches an owner that dies.\n process.on('SIGINT', () => { if (!watchParentPid) shutdown(); });\n process.on('SIGTERM', () => { shutdown(); });\n process.on('SIGHUP', () => { shutdown(); });\n\n if (watchParentPid) {\n const parentCheck = setInterval(() => {\n try {\n process.kill(watchParentPid, 0);\n } catch {\n clearInterval(parentCheck);\n shutdown();\n }\n }, 5000);\n }\n}\n","#!/usr/bin/env node\nimport { runDaemon } from './daemon';\n\nrunDaemon(process.argv.slice(2));\n"]}
1
+ {"version":3,"sources":["../../server/pool/childStreams.ts","../../server/pool/streamSequence.ts","../../server/adapters/WebConfig.ts","../../server/utils/workspaceScanner.ts","../../server/adapters/run.ts","../../server/adapters/PoolFileSystem.ts","../../server/adapters/PoolAwareRunner.ts","../../server/pool/orchestratorPool.ts","../../server/routes/errors.ts","../../server/routes/liveSession.ts","../../server/routes/children.ts","../../server/routes/sessions.ts","../../server/routes/plans.ts","../../server/routes/runners.ts","../../server/routes/models.ts","../../server/routes/workspaces.ts","../../server/routes/approvals.ts","../../server/routes/settings.ts","../../server/routes/workspaceRead.ts","../../server/routes/workspaceWrite.ts","../../server/ws/stream.ts","../../server/security/admission.ts","../../server/utils/serverVersion.ts","../../server/app.ts","../../server/nodeAdapter.ts","../../server/daemon.ts","../../server/main.ts"],"names":["BaseConfig","isApiProvider","normalizeGeminiModel","defaultEnabledRunners","DEFAULT_RUNNERS","fs","path","os","isSea","resolve","execFile","BaseFileSystem","researchToolsPath","withPath","GREP_PCRE_PROBE_ARGS","grepRegexFromProbe","result","buildGlobArgs","capped","applyHeadLimit","formatSearchOutput","SEARCH_EXCLUSIONS","path2","buildGrepArgs","buildFallbackGrepArgs","filterFallbackByAnchoredInclude","listTree","STOPPED_TOOL_RESULT","headLines","text","randomUUID","RunnerRegistry","SettingsService","PlannerModelMemory","removedPluginNotice","StructuredRunner","RunnerInstallation","workspaceEnvOf","ModelResolver","CodexSandboxAvailability","nodeSpawn","createIsolationPreview","claudeAccountLimitCollector","codexAccountLimitCollector","openCodeGoAccountLimitCollector","detectInstalledPlanner","assertWorkspaceExists","PlannerNotReadyError","PlannerTurnStoppedError","PlannerTurnDiscardedError","AccountLimitMonitor","flattenTasks","task","assignedRunnerOf","processLeaseHost","savedRunLooksLive","appendUserAction","planProgressCount","sessionRuntimeSettings","assertWorkspaceIsProject","WorkspaceNotAProjectError","ensureStateDirIgnored","createSession","changes","containerStatus","changeContainers","runnerForProvider","selectPlanner","PROVIDER_CREDENTIAL_ENV","forgetSignedOutRunnerAuth","configuredProviders","runnerModesFrom","migratePlanState","recordedRunnerAuth","installedPlannerAnswered","loadSession","SessionNotFoundError","reclaimContainers","scanWorkspaces","listSessions","discardChildRuns","createWorktreeIsolation","deleteSession","admitSettingsEnv","SessionHeldError","NoPlanError","AlreadyExecutingError","WorkspaceNotFoundError","ConversationBusyError","WorkspaceReadError","UserGitError","ConversationEditError","PlanEditError","TaskControlError","sameWorkspace","Hono","listTaskLogAttempts","taskLogForSurface","readTaskLog","run","surfacePlan","surfacePlanState","resolveUserTaskRef","parseExecutionCommand","yes","isCardEdit","installedPlannerDetected","toApprovalDecision","isGranted","containersOffered","RunSettingsError","refuse","WebSocketServer","DAEMON_SUBPROTOCOL","tokensMatch","extractPresentedToken","seaVersion","dirname","readFileSync","join","createUserGit","landingRuns","createWorkspaceReader","DAEMON_CONTRACT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ket } from 'ws';\nimport type { ChildFrame, ChildPlanHandle, RunSnapshotFrame, SessionFrame, StreamStamp } from '@ordewell/core';\nimport type { StreamSequence } from './streamSequence';\n\ninterface Watched {\n sockets: Set<WebSocket>;\n stop(): void;\n}\n\n/**\n * The sockets on a child plan (ADR-0055 D20): a child's frames reach only those\n * watching it, numbered on a count of its own. The count outlives every watcher\n * and every Session of the root, so a socket that comes back never sees the\n * numbers go backward. The child's words stay on these sockets: no frame of\n * theirs enters the root's stream.\n */\nexport class ChildStreams {\n private readonly watched = new Map<string, Watched>();\n\n constructor(private readonly sequence: StreamSequence, private readonly hears: (ws: WebSocket, workspace: string | undefined) => boolean) {}\n\n /**\n * Snapshot and watching in one turn, as a root's socket has them: no frame can\n * fall between. `workspace` is the root's: its later frames reach only sockets allowed to hear it.\n */\n join(rootId: string, childId: string, child: ChildPlanHandle, ws: WebSocket, workspace: string | undefined): void {\n if (ws.readyState !== ws.OPEN) return;\n const key = keyOf(rootId, childId);\n const view = child.view();\n ws.send(JSON.stringify({ type: 'connected', sessionId: childId }));\n ws.send(JSON.stringify({\n type: 'run_snapshot', sessionId: childId, view: view.run, approvals: [], ...this.position(rootId, childId),\n } satisfies RunSnapshotFrame));\n if (view.plannerCompaction) ws.send(JSON.stringify(view.plannerCompaction satisfies SessionFrame));\n const watching = this.watched.get(key);\n if (watching) {\n watching.sockets.add(ws);\n return;\n }\n const sockets = new Set([ws]);\n this.watched.set(key, { sockets, stop: child.watch((frame) => this.send(key, sockets, workspace, frame)) });\n }\n\n leave(rootId: string, childId: string, ws: WebSocket): void {\n const key = keyOf(rootId, childId);\n const watching = this.watched.get(key);\n if (!watching) return;\n watching.sockets.delete(ws);\n if (watching.sockets.size === 0) this.drop(key, watching);\n }\n\n position(rootId: string, childId: string): StreamStamp {\n return this.sequence.position(keyOf(rootId, childId));\n }\n\n closeRoot(rootId: string, code: number): void {\n for (const [key, watching] of this.watched) {\n if (!key.startsWith(keyOf(rootId, ''))) continue;\n this.drop(key, watching);\n for (const ws of watching.sockets) {\n if (ws.readyState === ws.OPEN) ws.close(code, 'Child plan closed');\n }\n }\n }\n\n private send(key: string, sockets: Set<WebSocket>, workspace: string | undefined, frame: ChildFrame): void {\n const payload = JSON.stringify({ ...frame, ...this.sequence.next(key) } satisfies SessionFrame);\n for (const ws of sockets) {\n if (ws.readyState === ws.OPEN && this.hears(ws, workspace)) ws.send(payload);\n }\n }\n\n private drop(key: string, watching: Watched): void {\n watching.stop();\n this.watched.delete(key);\n }\n}\n\n// A root's own stream is keyed by its bare id, which never holds a NUL: the two never share a count.\nconst keyOf = (rootId: string, childId: string) => `${rootId}\\0${childId}`;\n","import type { StreamStamp } from '@ordewell/core';\n\n/**\n * This daemon's broadcast numbering (see `StreamStamp`), one count per stream\n * a socket follows: a root session's id, or a child plan's own key. A count\n * outlives every Session and every watcher that used it, so a client that\n * comes back never sees the numbers go backward.\n */\nexport class StreamSequence {\n private readonly counts = new Map<string, number>();\n\n constructor(private readonly stream: string) {}\n\n /** The stamp of the next frame on `key`'s stream. */\n next(key: string): StreamStamp {\n const seq = (this.counts.get(key) ?? 0) + 1;\n this.counts.set(key, seq);\n return { stream: this.stream, seq };\n }\n\n /** The last frame on `key`'s stream: a read taken now accounts for it and everything before. */\n position(key: string): StreamStamp {\n return { stream: this.stream, seq: this.counts.get(key) ?? 0 };\n }\n}\n","import { type PlannerBackendId, BaseConfig, DEFAULT_RUNNERS, defaultEnabledRunners, isApiProvider, normalizeGeminiModel } from '@ordewell/core';\nimport type { ConfiguredPlanner, ProviderModelLists, ResolvedPlanner } from '@ordewell/core';\n\nexport interface PlannerPick {\n model: string;\n provider: PlannerBackendId;\n}\n\ninterface WebConfigOpts {\n enabledRunners?: string[];\n /**\n * The lists that route a model id to its vendor. A function is read on every\n * resolution, so a long-lived config (a session's) never routes on lists its\n * owner has since dropped for a removed key.\n */\n providerModelLists?: ProviderModelLists | (() => ProviderModelLists | undefined);\n modelOverride?: string;\n /** The model a settings write picked in this daemon and the planner it was for, read live; absent when none has. */\n pickedModel?: () => PlannerPick | undefined;\n /** The model ids a coding agent's discovery last listed, read live; empty while it is cold. */\n agentCatalog?: (provider: PlannerBackendId) => readonly string[];\n}\n\nexport class WebConfig extends BaseConfig {\n private _enabledRunnersOverride: string[] | undefined;\n private _providerModelLists: () => ProviderModelLists | undefined;\n private _modelOverride: string | undefined;\n private _pickedModel: () => PlannerPick | undefined;\n private _agentCatalog: (provider: PlannerBackendId) => readonly string[];\n\n constructor(opts?: WebConfigOpts) {\n super();\n this._enabledRunnersOverride = opts?.enabledRunners;\n const lists = opts?.providerModelLists;\n this._providerModelLists = typeof lists === 'function' ? lists : () => lists;\n this._modelOverride = opts?.modelOverride;\n this._pickedModel = opts?.pickedModel ?? (() => undefined);\n this._agentCatalog = opts?.agentCatalog ?? (() => []);\n }\n\n protected agentCatalog(provider: PlannerBackendId): readonly string[] {\n return this._agentCatalog(provider);\n }\n\n setProviderModelLists(lists: ProviderModelLists): void {\n this._providerModelLists = () => lists;\n }\n\n /**\n * Read live, not fixed at construction: a session's WebConfig lives for the\n * whole session while /planner and /key (or the headless `ordewell model`)\n * mutate process.env under it. `routedProvider` keeps that cheap.\n */\n get planner(): ResolvedPlanner {\n return this.resolvePlanner({ ...this.configuredPlanner(), override: this._modelOverride }, this._providerModelLists());\n }\n\n /**\n * What the daemon inherited at startup, or what a settings write has set\n * since; the model counts as picked only while it is the one a write picked.\n */\n private configuredPlanner(): ConfiguredPlanner {\n const model = process.env.ORCHESTRATOR_MODEL || '';\n const pick = this._pickedModel();\n return { model, effort: process.env.ORDEWELL_PLANNER_EFFORT || '', pickedFor: pick?.model === model ? pick.provider : undefined };\n }\n\n get orchestratorModel(): string {\n return this.planner.model;\n }\n\n get aiProvider(): PlannerBackendId {\n return this.planner.provider;\n }\n\n get plannerThinkingEffort(): string | undefined {\n return this.planner.effort || undefined;\n }\n\n get apiKey(): string {\n const provider = this.aiProvider;\n return isApiProvider(provider) ? this.getProviderApiKey(provider) : '';\n }\n\n get planningModel(): string {\n const model = this.plannerChoiceFor(this.aiProvider, this.configuredPlanner()).model;\n return this.aiProvider === 'google' ? normalizeGeminiModel(process.env.GEMINI_MODEL || model) : model;\n }\n\n get enabledRunners(): string[] {\n if (this._enabledRunnersOverride) return this._enabledRunnersOverride;\n\n const envRunners = process.env.ORDEWELL_ENABLED_RUNNERS;\n if (envRunners) {\n const parsed = envRunners.split(',').map((s) => s.trim()).filter(Boolean);\n if (parsed.length > 0) return parsed;\n }\n\n // The per-runner toggles that predate ORDEWELL_ENABLED_RUNNERS: three fixed\n // variables, named by runner id on purpose; a newer runner is enabled\n // through the list above. Only a toggle that is set is a choice: with none,\n // claude-code's default-on toggle would hide a Codex- or OpenCode-only host.\n const toggles = ['ORDEWELL_CLAUDE_CODE_ENABLED', 'ORDEWELL_CODEX_ENABLED', 'ORDEWELL_OPENCODE_ENABLED'];\n if (toggles.every((name) => process.env[name] === undefined)) return defaultEnabledRunners();\n const out: string[] = [];\n if (process.env.ORDEWELL_CLAUDE_CODE_ENABLED !== 'false' && process.env.ORDEWELL_CLAUDE_CODE_ENABLED !== '0') {\n out.push('claude-code');\n }\n if (process.env.ORDEWELL_CODEX_ENABLED === 'true' || process.env.ORDEWELL_CODEX_ENABLED === '1') {\n out.push('codex');\n }\n if (process.env.ORDEWELL_OPENCODE_ENABLED === 'true' || process.env.ORDEWELL_OPENCODE_ENABLED === '1') {\n out.push('opencode');\n }\n return out.length > 0 ? out : [...DEFAULT_RUNNERS];\n }\n\n}\n","import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { isSea, type SeaDeps } from '@ordewell/core';\n\nexport interface WorkspaceScannerDeps {\n fsModule: typeof fs;\n pathModule: typeof path;\n cwd: string;\n home: string;\n /** A folder never to list; undefined lists every one found. */\n projectDir: string | undefined;\n}\n\nexport function scanWorkspacesImpl(deps: WorkspaceScannerDeps): string[] {\n const { fsModule, pathModule, cwd, home, projectDir } = deps;\n const paths = new Set<string>();\n const searchRoots = [\n cwd,\n home,\n pathModule.join(home, 'projects'),\n pathModule.join(home, 'dev'),\n pathModule.join(home, 'code'),\n pathModule.join(home, 'src'),\n pathModule.join(home, 'Desktop'),\n pathModule.join(home, 'Documents'),\n ];\n for (const root of searchRoots) {\n try {\n if (fsModule.existsSync(pathModule.join(root, '.ordewell'))) paths.add(root);\n const entries = fsModule.readdirSync(root, { withFileTypes: true }).filter(e => e.isDirectory());\n for (const e of entries.slice(0, 50)) {\n const sub = pathModule.join(root, e.name);\n if (fsModule.existsSync(pathModule.join(sub, '.ordewell'))) paths.add(sub);\n }\n } catch { /* empty */ }\n }\n const hidden = projectDir === undefined ? undefined : pathModule.resolve(projectDir);\n return [...paths].filter(p => p !== hidden).sort();\n}\n\nexport function scanWorkspaces(sea: SeaDeps = {}): string[] {\n return scanWorkspacesImpl({\n fsModule: fs,\n pathModule: path,\n cwd: process.cwd(),\n // Not HOME, which Windows does not set: os.homedir() reads USERPROFILE there.\n home: os.homedir(),\n // Four up from dist/server/ is the root of an Ordewell source checkout,\n // whose own `.ordewell/` (its committed skills) is no workspace of the\n // user's. The binary has no checkout: its `__dirname` is the executable's\n // folder, and four up from there could be the home or a projects folder\n // that does hold one, so nothing is hidden (ADR-0065 C2).\n projectDir: isSea(sea) ? undefined : path.resolve(__dirname, '..', '..', '..', '..'),\n });\n}\n","import { execFile } from 'child_process';\n\nexport interface ExecResult {\n stdout: string;\n stderr: string;\n code: number | null;\n /** The child was killed at the call's time limit, rather than exiting on its own. */\n timedOut: boolean;\n /** The signal that ended the child, if one did. */\n signal: NodeJS.Signals | null;\n}\n\n/**\n * Cap on a single child's buffered output. Above this, Node kills the child\n * and invokes the callback with `err.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'`\n * — a string, so the coercion below maps it to `1` (see `run`).\n */\nexport const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;\n\n/** How long a sealed run's output may trail its exit. */\nconst SEALED_OUTPUT_GRACE_MS = 1_000;\n\n/**\n * The single primitive every search/inspection adapter in this package is\n * built on: spawn a child, never reject. Kept in its own module so the\n * contract that the planner depends on — synchronous spawn failures degrade\n * to a failed tool call, never a rejected promise that aborts the whole\n * planner turn — can be pinned by a focused test rather than exercised only\n * incidentally through the public adapter API.\n *\n * Node hands only ENOENT/EAGAIN/EMFILE/ENFILE from spawn(2) to the\n * callback; every other errno — ENOTDIR for a `cwd` that is a file, EACCES\n * for one it cannot enter — is thrown synchronously. Thrown in here that\n * rejects the promise, and no caller of `run` catches, so a single bad\n * search argument aborted the entire planner turn as \"Plan generation\n * failed: spawn ENOTDIR\". A failed spawn is a failed tool call, never a\n * failed plan.\n */\nexport function run(\n file: string,\n args: string[],\n opts: { cwd?: string; timeout: number; shell?: boolean; env?: NodeJS.ProcessEnv; signal?: AbortSignal; sealed?: boolean },\n): Promise<ExecResult> {\n return new Promise((resolve) => {\n try {\n const child = execFile(file, args, {\n cwd: opts.cwd,\n timeout: opts.timeout,\n maxBuffer: MAX_OUTPUT_BYTES,\n encoding: 'utf8',\n shell: opts.shell,\n env: opts.env,\n // A sealed run's wall-time limit is a kill, not a request it may trap\n // (ADR-0036 S1); the sandbox takes the processes it started down with it.\n ...(opts.sealed ? { killSignal: 'SIGKILL' as const } : {}),\n // Node kills the child when this aborts, and calls back with an\n // ABORT_ERR — which lands on the `code: 1` branch below, i.e. a\n // failed tool call, exactly like any other command that did not\n // finish. Stopping the planner must not leave a research `bash`\n // running out its own timeout on the server.\n signal: opts.signal,\n }, (err, stdout, stderr) => {\n const code = err && typeof (err as { code?: unknown }).code === 'number' ? (err as { code: number }).code : err ? 1 : 0;\n // Only Node's own timeout sets `killed`; an abort and a stdout overflow do not, so this names the limit exactly.\n resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code, timedOut: err?.killed === true, signal: err?.signal ?? null });\n });\n // A process that left a sealed run's process group can hold its output\n // open after the run has ended: the result is what arrived by then.\n if (opts.sealed) child.once('exit', () => setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, SEALED_OUTPUT_GRACE_MS).unref());\n } catch (err) {\n // `code: null` rather than 1 on purpose: the search adapters read 0 and 1\n // as \"ran, possibly no matches\", so a 1 here would report a confident\n // \"No matches found.\" for a search that never executed.\n resolve({ stdout: '', stderr: (err as Error).message, code: null, timedOut: false, signal: null });\n }\n });\n}","import {\n BaseFileSystem,\n buildGrepArgs,\n buildGlobArgs,\n buildFallbackGrepArgs,\n GREP_PCRE_PROBE_ARGS,\n grepRegexFromProbe,\n listTree,\n type GrepRegex,\n filterFallbackByAnchoredInclude,\n applyHeadLimit,\n formatSearchOutput,\n headLines,\n researchToolsPath,\n withPath,\n SEARCH_EXCLUSIONS,\n STOPPED_TOOL_RESULT,\n type GrepOptions,\n type ReadFileOpts,\n type ShellLaunch,\n type ToolOutcome,\n} from '@ordewell/core';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { run } from './run';\n\n/**\n * Everything here is async. It used to be `execSync`/`readFileSync`, which on\n * the web server blocked the entire Node event loop: one session running\n * `tree -L 4` over a monorepo stalled every other session's WebSocket\n * streaming, HTTP API, and plan-token delivery. It also makes the parallel\n * tool-round pre-pass in BaseAiService pointless, since concurrent calls into\n * a synchronous adapter still serialize.\n */\n\nconst SEARCH_TIMEOUT_MS = 20_000;\n/** Generous, because an approved `bash` call may legitimately be a test suite. */\nconst BASH_TIMEOUT_MS = 120_000;\n\nexport class PoolFileSystem extends BaseFileSystem {\n constructor(private workspaceRoot: string) { super(); }\n getWorkspaceRoot(): string { return this.workspaceRoot; }\n rootedAt(workspace: string): PoolFileSystem { return new PoolFileSystem(workspace); }\n\n /**\n * PATH for the search subprocesses. `execFile` starts them with no shell, so\n * on a Windows box whose POSIX tools live in the Git tree (`grep.exe` beside\n * the research shell) they are only resolvable with that directory prepended.\n * Identity on POSIX, where `utilsDir` is null. Kept in step with\n * VsCodeFileSystem.searchEnv.\n */\n private searchEnv(): NodeJS.ProcessEnv | undefined {\n const resolved = researchToolsPath(this.researchShell, process.env.PATH);\n // `withPath`, not a `PATH:` spread: on Windows the spread of `process.env`\n // carries `Path`, so adding `PATH` hands the child two and lets the OS pick.\n return resolved === (process.env.PATH ?? '') ? undefined : withPath(process.env, resolved);\n }\n\n private grepRegex: Promise<GrepRegex> | null = null;\n private fallbackGrepRegex(): Promise<GrepRegex> {\n this.grepRegex ??= run('grep', GREP_PCRE_PROBE_ARGS, { timeout: 5_000, env: this.searchEnv() })\n .then((r) => grepRegexFromProbe(r.code))\n .catch(() => 'ere' as const);\n return this.grepRegex;\n }\n\n private rgAvailable: Promise<boolean> | null = null;\n private hasRg(): Promise<boolean> {\n this.rgAvailable ??= run('rg', ['--version'], { timeout: 5_000, env: this.searchEnv() }).then((r) => r.code === 0).catch(() => false);\n return this.rgAvailable;\n }\n\n protected async readFileImpl(absPath: string, opts?: ReadFileOpts): Promise<ToolOutcome> {\n try {\n const stat = await fs.stat(absPath);\n if (!stat.isFile()) return { success: false, output: `Not a file: ${absPath}`, truncated: false };\n\n // Hard file-size cap — return an actionable error so the model switches to grep\n const maxBytes = opts?.maxBytes ?? 1024;\n if (stat.size > maxBytes * 1024) {\n const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);\n return {\n success: true,\n output: `File too large (${sizeMB} MB). Maximum is ${maxBytes} KB. Use grep to search for specific patterns instead.`,\n truncated: false,\n };\n }\n\n const content = await fs.readFile(absPath, 'utf8');\n const allLines = content.split('\\n');\n // Discard the empty element from a trailing newline\n if (allLines.length > 0 && allLines[allLines.length - 1] === '') allLines.pop();\n const totalLines = allLines.length;\n\n const startLine = opts?.offset ?? 0;\n const maxLines = opts?.limit ?? 2000;\n\n if (startLine >= totalLines) return { success: true, output: '', truncated: false };\n\n const selectedLines = allLines.slice(startLine, startLine + maxLines);\n const truncated = (startLine + maxLines) < totalLines;\n\n // Right-align line numbers so columns stay aligned across calls\n const lineWidth = String(totalLines).length;\n let output = selectedLines.map((line, i) => {\n const lineNum = String(startLine + i + 1).padStart(lineWidth);\n return `${lineNum}|${line}`;\n }).join('\\n');\n\n // Actionable hint so the model knows how to continue\n if (truncated) {\n const nextOffset = startLine + maxLines;\n output += `\\n\\n(File has more lines — use offset=${nextOffset} to read beyond line ${nextOffset})\\n`;\n }\n\n return { success: true, output, truncated };\n } catch (err) {\n return { success: false, output: `Error reading ${absPath}: ${(err as Error).message}`, truncated: false };\n }\n }\n\n protected async globImpl(pattern: string, absRoot: string, headLimit: number): Promise<ToolOutcome> {\n if (await this.hasRg()) {\n // ripgrep resolves a `--glob` pattern that contains a `/` against its own\n // cwd, not the `--` search path — without this, a daemon started outside\n // the workspace silently drops every anchored pattern (\"src/**/*\") to a\n // false \"No files matched.\".\n const { root, anchor } = await this.searchTarget(absRoot);\n const result = await run('rg', buildGlobArgs(pattern, root), { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() });\n // rg exits 1 for \"no files matched\", which is a valid empty answer.\n if (result.code !== 0 && result.code !== 1 && !result.stdout) {\n return { success: false, output: `Glob failed: ${result.stderr.trim() || 'ripgrep error'}`, truncated: false };\n }\n const capped = applyHeadLimit(result.stdout, headLimit);\n return {\n success: true,\n output: formatSearchOutput(capped, anchor, { emptyMessage: 'No files matched.', hint: 'Narrow the pattern.' }),\n truncated: capped.truncated,\n };\n }\n\n // `find -path` treats `*` as crossing `/`, so `**` is not recursive there.\n // Translating to `-name` on the basename keeps the common cases honest\n // rather than silently returning a different result set than ripgrep would.\n const basename = pattern.split('/').pop() || pattern;\n const excludeArgs = SEARCH_EXCLUSIONS.flatMap((dir) => ['-not', '-path', `*/${dir}/*`]);\n const { root: findRoot } = await this.searchTarget(absRoot);\n const result = await run('find', [findRoot, '-type', 'f', '-name', basename, ...excludeArgs], { timeout: SEARCH_TIMEOUT_MS, env: this.searchEnv() });\n if (result.code !== 0 && !result.stdout) {\n return { success: false, output: `Glob failed: ${result.stderr.trim() || 'find error'}`, truncated: false };\n }\n const capped = applyHeadLimit(result.stdout, headLimit);\n return {\n success: true,\n output: formatSearchOutput(capped, findRoot, { emptyMessage: 'No files matched.' }),\n truncated: capped.truncated,\n };\n }\n\n /**\n * The search path and a directory to anchor it in. `cwd` exists only so\n * anchored `--glob`/`--include` patterns resolve against the search root, and\n * spawn(2) rejects a `cwd` that is a file with ENOTDIR.\n *\n * `grep`'s `path` is documented as a directory, but the tool description\n * tells the model to survey with output_mode=\"files\" and then re-run \"on a\n * narrower path\" — and what that survey hands back are files. rg and grep\n * both search a single file happily, so anchor at the parent rather than\n * failing a legitimately file-scoped search.\n *\n * The root is resolved through symlinks because the OS reports a child's cwd\n * as the resolved path (macOS tmpdir is `/var/...` -> `/private/var/...`),\n * and ripgrep matches an anchored glob against the search path as written: a\n * root that goes through a link never matches and yields a false empty\n * result. Result rows then carry the resolved prefix, which is why callers\n * strip `anchor` rather than the path they were handed.\n */\n private async searchTarget(absRoot: string): Promise<{ root: string; anchor: string }> {\n try {\n const root = await fs.realpath(absRoot);\n return { root, anchor: (await fs.stat(root)).isDirectory() ? root : path.dirname(root) };\n } catch {\n return { root: absRoot, anchor: absRoot };\n }\n }\n\n protected async grepImpl(pattern: string, absRoot: string, opts: GrepOptions): Promise<ToolOutcome> {\n const headLimit = opts.headLimit ?? 100;\n const useRg = await this.hasRg();\n // Same anchored-glob-vs-cwd hazard as globImpl: an `include` filter with a\n // `/` in it would otherwise resolve against the daemon's cwd, not absRoot.\n const { root, anchor } = await this.searchTarget(absRoot);\n // GNU grep's `--include` only matches a basename, so an anchored pattern\n // like `subdir/*.txt` never matches there — strip it from the grep call\n // and filter matches by relative path afterward instead.\n const anchoredInclude = !useRg && opts.include?.includes('/') ? opts.include : undefined;\n const result = useRg\n ? await run('rg', buildGrepArgs(pattern, opts, root).args, { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() })\n : await run('grep', buildFallbackGrepArgs(pattern, anchoredInclude ? { ...opts, include: undefined } : opts, root, await this.fallbackGrepRegex()), { timeout: SEARCH_TIMEOUT_MS, cwd: anchor, env: this.searchEnv() });\n\n // Exit 1 is \"no matches\" for both tools — a successful search with an empty\n // result, not a failure. Anything else with no stdout is a real error.\n if (result.code !== 0 && result.code !== 1 && !result.stdout) {\n return { success: false, output: `Search failed: ${result.stderr.trim() || 'search error'}`, truncated: false };\n }\n\n const filteredStdout = anchoredInclude\n ? filterFallbackByAnchoredInclude(result.stdout, anchoredInclude, anchor, opts.outputMode)\n : result.stdout;\n const capped = applyHeadLimit(filteredStdout, headLimit);\n const hint = opts.outputMode === 'content'\n ? 'Re-run with output_mode=\"files\" to see the full breadth, or narrow with include/path.'\n : 'Narrow with include/path.';\n return {\n success: true,\n output: formatSearchOutput(capped, anchor, { emptyMessage: 'No matches found.', hint }),\n truncated: capped.truncated,\n };\n }\n\n protected async listDirImpl(absPath: string, depth: number): Promise<ToolOutcome> {\n try {\n return await listTree(absPath, depth, async (abs) =>\n (await fs.readdir(abs, { withFileTypes: true })).map((e) => ({ name: e.name, directory: e.isDirectory() })));\n } catch (err) {\n return { success: false, output: `Error listing ${absPath}: ${(err as Error).message}`, truncated: false };\n }\n }\n\n protected async execBashImpl(command: string, shell: ShellLaunch, signal: AbortSignal | undefined, cwd: string): Promise<ToolOutcome> {\n // `shell: true` is required now that approved commands may legitimately\n // contain pipes; the tier classifier in core (not string filtering here)\n // is what decides whether this command was allowed to reach the shell.\n //\n // `file: null` is that host default, unchanged on POSIX where no sandbox\n // runs. A resolved file is the sandbox launcher around the POSIX shell, or\n // the POSIX shell found on a Windows box: either way the command goes last,\n // in the dialect `BaseFileSystem` classified it under.\n const { file, args, env, wallTimeMs } = shell;\n const result = file === null\n ? await run(command, [], { cwd, timeout: BASH_TIMEOUT_MS, shell: true, env, signal })\n : await run(file, [...args, command], { cwd, timeout: wallTimeMs ?? BASH_TIMEOUT_MS, env, signal, sealed: wallTimeMs !== undefined });\n const out = (result.stdout || '').trim();\n const err = (result.stderr || '').trim();\n\n // A stopped turn reports as a stop, not as a mysterious non-zero exit: the\n // child was killed on purpose and there is nothing here to diagnose.\n if (signal?.aborted) return { success: false, output: STOPPED_TOOL_RESULT, truncated: false };\n\n if (result.code !== 0) {\n const detail = err || out || `exited with code ${result.code}`;\n // A failing command is still research: the model asked to diagnose, and\n // the failure output is usually the answer. Report it, do not swallow it.\n // Whole lines only: executeTool redacts what this returns, and a cut inside\n // a line can leave a credential's value with no name to recognise it by.\n return { success: false, output: `Command exited ${result.code}:\\n${headLines(detail, 20_000)}`, truncated: detail.length > 20_000, ...(result.timedOut ? { timedOut: true } : {}), ...(result.signal ? { signal: result.signal } : {}) };\n }\n\n const combined = err ? `${out}\\n[stderr]\\n${err}` : out;\n return { success: true, output: combined || '(no output)', truncated: combined.length > 20_000 };\n }\n}\n","import type { IRunner, IRunnerSession, RunnerSpawnOptions } from '@ordewell/core';\nimport type { SessionBroadcaster } from '@ordewell/core';\n\nexport class PoolAwareRunner implements IRunner {\n /**\n * Sessions this plan spawned. The inner runner is shared by every plan in\n * the pool, so \"stop everything\" and \"how many are running\" must be\n * answered from this set, never delegated — delegating would let one plan's\n * /stop kill another plan's tasks.\n */\n private owned = new Set<string>();\n\n constructor(\n private sessionId: string,\n private broadcast: SessionBroadcaster,\n private inner: IRunner,\n ) {}\n\n get activeCount(): number { return this.owned.size; }\n\n async spawn(opts: RunnerSpawnOptions): Promise<IRunnerSession> {\n const session = await this.inner.spawn({ ...opts, planSessionId: this.sessionId });\n this.owned.add(session.id);\n session.onExit(() => this.owned.delete(session.id));\n this.broadcast({ type: 'task_started', taskId: opts.taskId, order: opts.order ?? 0, title: opts.title ?? '', runner: opts.runner, modelId: opts.modelId });\n session.onOutput((text) => {\n this.broadcast({ type: 'task_output', taskId: opts.taskId, text });\n });\n return session;\n }\n\n stop(sessionId: string): Promise<void> {\n this.owned.delete(sessionId);\n return this.inner.stop(sessionId);\n }\n\n stopAll(): void {\n for (const id of this.owned) void this.inner.stop(id);\n this.owned.clear();\n }\n}\n","import { spawn as nodeSpawn } from 'child_process';\nimport { randomUUID } from 'crypto';\nimport { resolve } from 'path';\nimport { WebSocket } from 'ws';\nimport {\n AccountLimitMonitor,\n claudeAccountLimitCollector,\n codexAccountLimitCollector,\n openCodeGoAccountLimitCollector,\n assignedRunnerOf,\n flattenTasks,\n type AccountLimitCollector,\n type AccountLimitsFrame,\n Session,\n createSession,\n type ConversationCompaction,\n type ChildTreeFrame,\n type ConversationFork,\n type RunView,\n type SessionMessage,\n type SessionNotice,\n type SessionRuntimeSettings,\n type SessionFrame,\n type ApprovalRequestMessage,\n type StreamStamp,\n ModelResolver,\n RunnerRegistry,\n removedPluginNotice,\n RunnerInstallation,\n listSessions,\n loadSession,\n appendUserAction,\n processLeaseHost,\n savedRunLooksLive,\n planProgressCount,\n type SessionRunActivity,\n deleteSession,\n reclaimContainers,\n changeContainers,\n containerStatus,\n type ContainerChange,\n type ContainerChangeResponse,\n type ContainerStatus,\n type DockerCli,\n SettingsService,\n sessionRuntimeSettings,\n type GlobalRunSettings,\n type PlanState,\n type LegacyPlanState,\n migratePlanState,\n type RunnerId,\n type DiscoveredModel,\n type ModelsResponse,\n type RunnersResponse,\n type SettingsResponse,\n type SettingsUpdateResponse,\n SessionNotFoundError,\n runnerModesFrom,\n configuredProviders,\n assertWorkspaceExists,\n assertWorkspaceIsProject,\n WorkspaceNotAProjectError,\n ensureStateDirIgnored,\n runnerForProvider,\n PlannerModelMemory,\n selectPlanner,\n admitSettingsEnv,\n PROVIDER_CREDENTIAL_ENV,\n forgetSignedOutRunnerAuth,\n type PlannerBackendId,\n type PlannerModelCandidate,\n type PlannerSelectionChange,\n type PlannerSelectionCurrent,\n StructuredRunner,\n CodexSandboxAvailability,\n detectInstalledPlanner,\n installedPlannerAnswered,\n PlannerNotReadyError,\n PlannerTurnDiscardedError,\n PlannerTurnStoppedError,\n type LeaseHost,\n workspaceEnvOf,\n recordedRunnerAuth,\n createIsolationPreview,\n createWorktreeIsolation,\n discardChildRuns,\n type IIsolationPreview,\n type IsolationPreview,\n} from '@ordewell/core';\nimport { ChildStreams } from './childStreams';\nimport { StreamSequence } from './streamSequence';\nimport { WebConfig, type PlannerPick } from '../adapters/WebConfig';\nimport { scanWorkspaces as scanWorkspacesImpl } from '../utils/workspaceScanner';\nimport { PoolFileSystem } from '../adapters/PoolFileSystem';\nimport { PoolAwareRunner } from '../adapters/PoolAwareRunner';\nimport type { RunnerRegistry as CoreRunnerRegistry, IRunner } from '@ordewell/core';\n\n/** A fork the pool has adopted: addressable at once, its plan read back from the file it was written to. */\nexport interface AdoptedFork {\n sessionId: string;\n goal: string;\n plan: LegacyPlanState;\n}\n\n/**\n * A load for a session id this daemon already holds open for another\n * workspace. The pool keeps one session per id, so adopting this one would\n * stop the other's run or planner turn and take its place.\n */\nexport class SessionOpenElsewhereError extends Error {\n constructor(sessionId: string, workspace: string) {\n super(`Session \"${sessionId}\" is open in this daemon for ${workspace}. Close it there before opening this workspace's copy.`);\n this.name = 'SessionOpenElsewhereError';\n }\n}\n\n/**\n * The installation checks a host supplies the pool. `refresh` is optional so a\n * test may hand in only the two probes; the real `RunnerInstallation` always\n * has it, and a refresh then re-probes a CLI installed since the last look.\n */\ntype RunnerInstall = Pick<RunnerInstallation, 'filterInstalled' | 'plannerUsability' | 'runnerUsability'> & Partial<Pick<RunnerInstallation, 'refresh'>>;\n\nexport interface OrchestratorPoolDeps {\n /** Inject acquisition boundaries without reading real accounts in host lifecycle tests. */\n accountLimitCollectors?: (workspace: string) => readonly AccountLimitCollector[];\n /**\n * Where every plan's tasks run (ADR-0018), shared across sessions behind\n * each plan's `PoolAwareRunner`. Defaulted to a real one; tests inject a fake.\n */\n runner?: IRunner;\n /**\n * Overrides the pool's own `ModelResolver`. Left undefined, behavior is\n * unchanged; tests inject one built with fake exec/fetch impls so a\n * planner-switch catalog lookup can be seeded without spawning real CLIs.\n */\n modelResolver?: ModelResolver;\n /** Overrides the docker CLI a containers status or change asks; tests inject one so no engine is needed. */\n dockerCli?: DockerCli;\n /** Overrides the pool's Codex sandbox probe; tests inject one so no real `codex` is started. */\n codexSandbox?: Pick<CodexSandboxAvailability, 'ensure' | 'refresh'>;\n /** Overrides the pool's installation checks; tests inject one so no real agent binary is asked. */\n runnerInstallation?: RunnerInstall;\n /**\n * The host whose leases the pool's sessions hold (ADR-0049); this process's\n * unless a test runs two pools as two hosts.\n */\n leaseHost?: LeaseHost;\n /**\n * The read-only repository look a surface shows before any run. Defaulted to\n * one built from the daemon's config; tests inject a fake so no real git runs.\n */\n isolationPreview?: IIsolationPreview;\n}\n\nexport class OrchestratorPool {\n // A daemon serves several workspaces; login selection must never follow\n // whichever session was opened most recently (ADR-0051).\n private readonly sessionWorkspaces = new Map<string, string>();\n private readonly accountLimits = new Map<string, AccountLimitMonitor>();\n private readonly accountLimitCollectors: (workspace: string) => readonly AccountLimitCollector[];\n private limitsRevision = 0;\n private sessions = new Map<string, Session>();\n private clients = new Map<string, Set<WebSocket>>();\n /** The workspace each socket named when it subscribed, judged again whenever a session takes its id. */\n private readonly socketWorkspaces = new WeakMap<WebSocket, string>();\n /**\n * This process's broadcast numbering, per session id rather than per\n * Session object: a session replaced under the same id keeps counting up,\n * so a client never mistakes its first broadcast for one of the old\n * session's it already showed. Child plans count on the same sequence,\n * each under its own key.\n */\n private readonly stream = randomUUID();\n private readonly sequence = new StreamSequence(this.stream);\n private readonly childStreams = new ChildStreams(this.sequence, (ws, workspace) => this.hears(ws, workspace));\n private registry: CoreRunnerRegistry = new RunnerRegistry();\n private modelResolver: ModelResolver;\n /** A host that supplied its own resolver answers for every workspace, as a supplied probe does. */\n private suppliedModelResolver: boolean;\n private runnerInstallation: RunnerInstall;\n /**\n * A host that supplied its own probe (a test, or a surface that owns one).\n * Everything else asks {@link installationFor}, which keys a real probe by\n * the workspace whose account it is judging (ADR-0016).\n */\n private suppliedRunnerInstallation: RunnerInstall | undefined;\n private workspaceInstallations = new Map<string, RunnerInstall>();\n private cachedProviderLists: Record<string, string[]> | undefined;\n private settingsService = new SettingsService();\n private plannerModelMemory = new PlannerModelMemory(this.settingsService);\n /**\n * The model a settings write picked in this daemon, and the workspace it was\n * picked in. The environment's model is otherwise inherited, and an agent\n * planning only because detection found it does not plan with an inherited\n * model it cannot be shown to run. The pick is that workspace's: another\n * may name another account, whose catalog judges the model afresh.\n */\n private pickedModel: (PlannerPick & { workspace: string }) | undefined;\n /**\n * The last planner write a route made, so each lands after the ones made\n * before it: a switch still waiting for its catalog must not write over a\n * pick made while it waited (ADR-0040).\n */\n private plannerWrites: Promise<unknown> = Promise.resolve();\n private runner: IRunner;\n /** One probe per daemon, asked again whenever the runner list is refreshed (ADR-0033). */\n private codexSandbox: Pick<CodexSandboxAvailability, 'ensure' | 'refresh'>;\n private readonly leaseHost: LeaseHost | undefined;\n private readonly isolationPreview: IIsolationPreview;\n private readonly suppliedDockerCli: DockerCli | undefined;\n\n constructor(deps: OrchestratorPoolDeps = {}) {\n const pluginNotice = removedPluginNotice();\n if (pluginNotice) console.warn(pluginNotice);\n this.suppliedDockerCli = deps.dockerCli;\n this.runner = deps.runner ?? new StructuredRunner();\n // The login probe must ask the account the planner will use (ADR-0016).\n // This installation is the daemon's own cwd for detection; a runner list\n // request naming a workspace is judged by that workspace's own probe.\n this.suppliedRunnerInstallation = deps.runnerInstallation;\n this.runnerInstallation = deps.runnerInstallation\n ?? new RunnerInstallation(this.registry, undefined, undefined, {\n env: () => workspaceEnvOf(process.cwd()),\n workspace: () => process.cwd(),\n });\n // Read from the account the runners use, as the login probe above is.\n this.suppliedModelResolver = deps.modelResolver !== undefined;\n this.modelResolver = deps.modelResolver ?? new ModelResolver(this.registry, new WebConfig(), {\n env: async () => ({ ...process.env, ...(await workspaceEnvOf(process.cwd())) }),\n });\n this.codexSandbox = deps.codexSandbox\n ?? new CodexSandboxAvailability(this.registry, { spawn: nodeSpawn, fetch: globalThis.fetch }, { cwd: process.cwd(), env: process.env });\n this.leaseHost = deps.leaseHost;\n // What worktreeIsolation and workspaceRepos mean here, which is the config\n // the sessions plan with: the daemon's own environment, not a guess from\n // the workspace a request happens to name.\n this.isolationPreview = deps.isolationPreview ?? createIsolationPreview({ config: new WebConfig() });\n this.accountLimitCollectors = deps.accountLimitCollectors ?? ((workspace) => {\n const workspaceRoot = () => workspace;\n const isInstalled = (runner: string) => async () => (await this.runnerInstallation.filterInstalled([runner])).includes(runner);\n const server = this.registry.getManifest('codex')?.modelDiscovery.appServer;\n return [\n claudeAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('claude-code') }),\n codexAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('codex'), command: server?.command, args: server?.args }),\n openCodeGoAccountLimitCollector({ workspaceRoot, isInstalled: isInstalled('opencode') }),\n ];\n });\n }\n\n /**\n * Not awaited: planning must start at once, and the daemon already warms the\n * probe at startup through the catalog. This only covers a daemon that was\n * asked to plan before that finished.\n */\n private warmCodexSandbox(): void {\n this.codexSandbox.ensure().catch((err) => console.error(`[web] codex sandbox probe failed: ${err instanceof Error ? err.message : err}`));\n }\n\n /**\n * Find the coding agent that plans when the user has chosen no planner and\n * set no vendor key (ADR-0009), for the daemon to start as it starts. Every\n * planner turn waits on it, so a goal typed the instant the TUI opens\n * does not plan with an openrouter key nobody set.\n */\n detectInstalledPlanner(): Promise<PlannerBackendId | null> {\n return detectInstalledPlanner(this.runnerInstallation);\n }\n\n /**\n * A read-only look at the repositories and branches a run would isolate in\n * `workspace`. Free of side effects on purpose: a first screen may ask before\n * any plan or run exists, and asking must not create one.\n */\n previewIsolation(workspace: string): Promise<IsolationPreview> {\n assertWorkspaceExists(workspace);\n return this.isolationPreview.preview(workspace);\n }\n\n /**\n * A new session's first planner turn. It waits for that probe at the\n * session's own planner gate, where a reply sent meanwhile queues behind\n * it, and a Stop or the session closing or being replaced ends the wait.\n */\n private async firstTurn<T>(sessionId: string, session: Session, turn: () => Promise<T>): Promise<T> {\n try {\n return await turn();\n } catch (err) {\n // Judged once the probe answered: a refused session is never left\n // addressable, as when it is judged before it is registered.\n if (err instanceof PlannerNotReadyError && this.sessions.get(sessionId) === session) this.destroy(sessionId);\n // Stopped before it opened, the session holds no conversation for a\n // reply to continue: for the client its goal was discarded.\n if (err instanceof PlannerTurnStoppedError && !session.planState) throw new PlannerTurnDiscardedError();\n throw err;\n }\n }\n\n /** A socket naming a workspace keeps hearing the id only while no other workspace holds it; one naming none hears whoever does. */\n subscribe(sessionId: string, ws: WebSocket, workspace?: string): void {\n if (workspace !== undefined) this.socketWorkspaces.set(ws, workspace);\n if (!this.clients.has(sessionId)) this.clients.set(sessionId, new Set());\n this.clients.get(sessionId)!.add(ws);\n this.connectAccountLimits(sessionId, ws);\n const session = this.sessions.get(sessionId);\n if (session) void this.tellTree(sessionId, session, [ws]);\n }\n\n unsubscribe(sessionId: string, ws: WebSocket): void {\n this.clients.get(sessionId)?.delete(ws);\n if (this.clients.get(sessionId)?.size === 0) this.clients.delete(sessionId);\n this.releaseUnusedAccountLimits();\n }\n\n private connectAccountLimits(sessionId: string, ws: WebSocket): void {\n const workspace = this.sessionWorkspaces.get(sessionId);\n if (!workspace) {\n this.sendAccountLimits(sessionId, ws, []);\n return;\n }\n let monitor = this.accountLimits.get(workspace);\n if (!monitor) {\n monitor = new AccountLimitMonitor({ collectors: this.accountLimitCollectors(workspace) });\n this.accountLimits.set(workspace, monitor);\n monitor.subscribe((limits) => {\n for (const [id, clients] of this.clients) {\n if (this.sessionWorkspaces.get(id) !== workspace) continue;\n for (const client of clients) this.sendAccountLimits(id, client, limits, workspace);\n }\n });\n }\n this.sendAccountLimits(sessionId, ws, monitor.snapshots(), workspace);\n monitor.setForeground(true);\n monitor.surfaceConnected();\n }\n\n /** `workspace` is the account the limits are read from; none for the empty greeting of an id nobody holds. */\n private sendAccountLimits(sessionId: string, ws: WebSocket, limits: AccountLimitsFrame['limits'], workspace?: string): void {\n this.send(sessionId, workspace, JSON.stringify({ type: 'account_limits', sessionId, limits, stream: this.stream, revision: ++this.limitsRevision } satisfies AccountLimitsFrame), [ws]);\n }\n\n private releaseUnusedAccountLimits(): void {\n for (const [workspace, monitor] of this.accountLimits) {\n if ([...this.clients.keys()].some((id) => this.sessionWorkspaces.get(id) === workspace)) continue;\n monitor.dispose();\n this.accountLimits.delete(workspace);\n }\n }\n\n private registerSession(sessionId: string, workspace: string, session: Session): void {\n this.sessions.set(sessionId, session);\n this.sessionWorkspaces.set(sessionId, workspace);\n // A socket subscribes to an id, which may be nobody's when it connects (a\n // surface opens it before adopting): the workspace taking the id now must\n // not reach a socket another one opened, through its limits or a broadcast.\n const clients = this.clients.get(sessionId);\n for (const ws of clients ?? []) {\n if (this.hears(ws, workspace)) continue;\n clients?.delete(ws);\n ws.close(4409, 'Session open for another workspace');\n }\n if (clients?.size === 0) this.clients.delete(sessionId);\n for (const ws of this.clients.get(sessionId) ?? []) this.connectAccountLimits(sessionId, ws);\n session.children.onChange(() => void this.tellTree(sessionId, session));\n }\n\n /** The tree as it stands. A failed read tells nothing: the list route is where a surface hears why. */\n private async tellTree(sessionId: string, session: Session, sockets?: WebSocket[]): Promise<void> {\n const children = await session.children.list().catch(() => []);\n if (children.length === 0 || this.sessions.get(sessionId) !== session) return;\n this.send(sessionId, this.sessionWorkspaces.get(sessionId), JSON.stringify({ type: 'child_tree', sessionId, children } satisfies ChildTreeFrame), sockets);\n }\n\n /**\n * The one way a frame of a session reaches its sockets: one that named\n * another workspace than `workspace`, the one the frame speaks for, hears\n * none of it. Registering a session closes such sockets, but frames are\n * sent outside that window too: a load announces its usage before the\n * session takes the id, and a replaced session's work may still be\n * settling once another workspace's holds it.\n */\n private send(sessionId: string, workspace: string | undefined, payload: string, sockets?: Iterable<WebSocket>): void {\n for (const ws of sockets ?? this.clients.get(sessionId) ?? []) {\n if (ws.readyState === ws.OPEN && this.hears(ws, workspace)) ws.send(payload);\n }\n }\n\n /** Whether a socket may hear what `workspace`'s session says: always, unless both name a workspace and they differ. */\n private hears(ws: WebSocket, workspace: string | undefined): boolean {\n const named = this.socketWorkspaces.get(ws);\n return named === undefined || workspace === undefined || sameWorkspace(named, workspace);\n }\n\n /** False for a child this root does not hold, or a root no longer loaded (ADR-0055 D20). */\n async watchChild(rootId: string, childId: string, ws: WebSocket, workspace?: string): Promise<boolean> {\n if (workspace !== undefined) this.socketWorkspaces.set(ws, workspace);\n const session = this.sessions.get(rootId);\n const child = await session?.children.find(childId);\n const held = this.sessionWorkspaces.get(rootId);\n if (!child || this.sessions.get(rootId) !== session || !this.hears(ws, held)) return false;\n this.childStreams.join(rootId, childId, child, ws, held);\n return true;\n }\n\n unwatchChild(rootId: string, childId: string, ws: WebSocket): void { this.childStreams.leave(rootId, childId, ws); }\n /** What a read of the child taken now accounts for on its socket; refused, as {@link live} is, once another workspace holds the root. */\n childPosition(rootId: string, childId: string, workspace: string | undefined): StreamStamp {\n this.live(rootId, workspace);\n return this.childStreams.position(rootId, childId);\n }\n\n /** `workspace` is the one of the Session that speaks, which need not be the one holding the id by the time it does. */\n private broadcast(sessionId: string, workspace: string | undefined, msg: SessionMessage | SessionNotice): void {\n const monitor = workspace ? this.accountLimits.get(workspace) : undefined;\n if (msg.type === 'planner_usage') monitor?.invalidate();\n else if (msg.type === 'task_log' && msg.events.some((event) => event.type === 'turn_end')) {\n const task = flattenTasks(this.sessions.get(sessionId)?.planTasks ?? []).find((task) => task.id === msg.taskId);\n const runner = task && assignedRunnerOf(task);\n if (runner) monitor?.invalidate(runner);\n }\n this.send(sessionId, workspace, JSON.stringify({ ...msg, ...this.sequence.next(sessionId) } satisfies SessionFrame));\n }\n\n hasSession(sessionId: string): boolean { return this.sessions.has(sessionId); }\n\n /** Whether the session open under this id is this workspace's: only then do the id's live accessors speak for it. */\n holds(sessionId: string, workspace: string): boolean { return this.heldHere(sessionId, workspace) !== undefined; }\n\n /** Whether the session open under this id is another workspace's: what the id's live accessors say is not this workspace's to read or act on. */\n heldElsewhere(sessionId: string, workspace: string): boolean { return this.sessions.has(sessionId) && !this.holds(sessionId, workspace); }\n\n /**\n * The session open under this id, as a client in `workspace` reaches it: the\n * one lookup a route goes through to reach a live session by id. The pool\n * keeps one session per id, so while another workspace holds it the id names\n * that project's session, not the caller's, and the call is refused rather\n * than served or acted on there. Undefined when none is open; a caller that\n * names no workspace reaches it by the id alone.\n */\n live(sessionId: string, workspace: string | undefined): Session | undefined {\n const held = this.sessionWorkspaces.get(sessionId);\n if (held !== undefined && workspace !== undefined && !this.heldHere(sessionId, workspace)) throw new SessionOpenElsewhereError(sessionId, held);\n return this.sessions.get(sessionId);\n }\n\n /** The session open here under this id for this workspace, if any: an id names a session only within its workspace. */\n private heldHere(sessionId: string, workspace: string): Session | undefined {\n const held = this.sessionWorkspaces.get(sessionId);\n return held !== undefined && sameWorkspace(held, workspace) ? this.sessions.get(sessionId) : undefined;\n }\n\n /**\n * Whether a session's run holds its landing branch (ADR-0062 G7): this\n * host's own word for a session open here; for one another live host holds,\n * that host's word in its lease record, or the saved record where the holder\n * says nothing; and for one nobody holds, nothing is at work.\n */\n userRunIsLive(sessionId: string, workspace: string, plan: LegacyPlanState): boolean {\n const session = this.heldHere(sessionId, workspace);\n if (session) return session.runIsLive;\n const held = (this.leaseHost ?? processLeaseHost()).peek(sessionId, workspace);\n return held !== null && (held.holder.runLive === true || savedRunLooksLive(plan));\n }\n\n /**\n * A user git action into the session's timeline (ADR-0062 G6): straight in\n * for a session open here, else left in its directory for whichever host\n * holds it, or next opens it, to fold (ADR-0049 L5).\n */\n recordUserAction(sessionId: string, workspace: string, text: string): void {\n const session = this.heldHere(sessionId, workspace);\n if (session?.planState) session.recordUserAction(text);\n else appendUserAction(sessionId, workspace, { text, at: new Date().toISOString() });\n }\n\n isExecuting(sessionId: string): boolean { return this.sessions.get(sessionId)?.isExecuting ?? false; }\n /** Work under way in any session held here, which stopping this daemon would cut off: a run not settled, or a planner turn answering. */\n workLive(): boolean {\n for (const session of this.sessions.values()) {\n if (session.runIsLive || session.plannerTurnId !== undefined) return true;\n }\n return false;\n }\n getPlan(sessionId: string): LegacyPlanState | null { return this.sessions.get(sessionId)?.planState ?? null; }\n /**\n * The plan of a session this process is holding, straight from its store —\n * null for an id the pool never adopted. Reading it through the saved file\n * instead answers as if nothing were running.\n */\n getPlanState(sessionId: string): PlanState | null {\n return this.sessions.get(sessionId)?.currentPlanState ?? null;\n }\n getGoal(sessionId: string): string { return this.sessions.get(sessionId)?.currentGoal ?? ''; }\n /**\n * A session's run as the session list says it (`SessionRunActivity`): for\n * one held here for this workspace, this daemon's own word, by the test and\n * the count the open session's header uses, so its row reads the same open\n * or not; for one another host holds, that host's lease's `runLive`, read\n * without taking it and only while its holder lives (ADR-0049); otherwise\n * nothing. An id held here for another workspace says nothing of this one's.\n */\n runActivity(sessionId: string, workspace: string): SessionRunActivity | undefined {\n const session = this.heldHere(sessionId, workspace);\n if (session) {\n if (!session.isExecuting && !session.activity.advancesOnItsOwn) return undefined;\n return { live: true, ...planProgressCount(session.runSnapshot().tasks) };\n }\n let held: ReturnType<LeaseHost['peek']>;\n try {\n held = (this.leaseHost ?? processLeaseHost()).peek(sessionId, workspace);\n } catch {\n // An unreadable lease is no word that a run is live, and must not cost the whole list.\n return undefined;\n }\n // A holder that died with runners still going is no run: nothing drives it on.\n return held && !held.orphanedRunners && held.holder.runLive === true ? { live: true } : undefined;\n }\n /** Null for a session this process is not holding: there is no run to describe. */\n runSnapshot(sessionId: string): RunView | null { return this.sessions.get(sessionId)?.runSnapshot() ?? null; }\n /** The planner turn answering in a session this process holds, if one is. */\n plannerTurnId(sessionId: string): string | undefined { return this.sessions.get(sessionId)?.plannerTurnId; }\n /** The planner compaction running in a session this process holds, as its start was announced; it has no turn to name. */\n plannerCompaction(sessionId: string): ReturnType<Session['plannerCompaction']> { return this.sessions.get(sessionId)?.plannerCompaction(); }\n plannerDetection(sessionId: string): ReturnType<Session['plannerDetection']> | undefined { return this.sessions.get(sessionId)?.plannerDetection(); }\n /** The planner's approval requests still waiting, as they were announced. */\n announcedApprovals(sessionId: string): ApprovalRequestMessage[] { return this.sessions.get(sessionId)?.announcedApprovals() ?? []; }\n /** The last broadcast of the session so far: a snapshot taken now accounts for it and everything before. */\n streamPosition(sessionId: string): StreamStamp { return this.sequence.position(sessionId); }\n\n private runtimeSettings(): SessionRuntimeSettings {\n return sessionRuntimeSettings(this.settingsService.getAll());\n }\n\n private createSessionFor(sessionId: string, workspace: string, modelOverride?: string, options: { allowInit?: boolean } = {}): Session {\n // Rejected here rather than left to the planner: a non-existent workspace\n // otherwise reaches the harness adapter's `spawn` as an ENOENT that reads\n // as a missing agent binary, not a missing directory.\n assertWorkspaceExists(workspace);\n // Rejected here too: without a project marker, the filesystem root or an\n // arbitrary system directory becomes the confinement boundary for every\n // read, search and permitted command the planner runs. `allowInit` only\n // ever arrives here on the retry of a call the user already saw and\n // explicitly confirmed (the TUI's \"initialize this as a new workspace?\"\n // prompt) — never as a default, so an unmarked directory is still never\n // admitted silently.\n try {\n assertWorkspaceIsProject(workspace);\n } catch (err) {\n if (!(err instanceof WorkspaceNotAProjectError) || !options.allowInit) throw err;\n ensureStateDirIgnored(workspace);\n assertWorkspaceIsProject(workspace);\n }\n const config = this.plannerConfig(modelOverride, workspace);\n const fsAdapter = new PoolFileSystem(workspace);\n const broadcast = (msg: SessionMessage) => this.broadcast(sessionId, workspace, msg);\n const runner = new PoolAwareRunner(sessionId, broadcast, this.runner);\n return createSession({\n config,\n notifications: { info() {}, warn() {}, error() {}, async confirm() { return undefined; } },\n runner,\n registry: this.registry,\n workspaceRoot: () => workspace,\n fsAdapter,\n broadcast,\n // The notification channel above is silent here; this is how a client hears how the run isolates.\n onNotice: (notice) => this.broadcast(sessionId, workspace, notice),\n modelResolver: this.resolverFor(workspace),\n settings: () => this.runtimeSettings(),\n sessionId,\n ...(this.leaseHost ? { leaseHost: this.leaseHost } : {}),\n });\n }\n\n /**\n * The one way the pool builds a config that answers \"who plans\": sessions,\n * the settings response and the switch judgement all route through it, so\n * what the settings route reports is what the next turn plans with. The\n * lists are handed over as a reader, not a snapshot, so a credential change\n * reaches a session that is already open.\n */\n private plannerConfig(\n modelOverride?: string,\n workspace?: string,\n catalog: (provider: PlannerBackendId) => PlannerModelCandidate[] = (provider) => this.plannerCatalogFor(provider, workspace),\n ): WebConfig {\n return new WebConfig({\n enabledRunners: this.enabledRunnerOverride(),\n modelOverride,\n providerModelLists: () => this.cachedProviderLists,\n pickedModel: () => (this.pickedModel?.workspace === workspaceKey(workspace) ? this.pickedModel : undefined),\n agentCatalog: (provider) => catalog(provider).map((model) => model.id),\n });\n }\n\n /**\n * The user's runner choice, or undefined when they have never made one —\n * which is what lets `WebConfig` fall back to the environment's defaults.\n * Read per call rather than cached: the settings file is shared with the\n * VS Code extension host, and `getAll()` already invalidates on mtime.\n */\n private enabledRunnerOverride(): string[] | undefined {\n return this.settingsService.getEnabledRunners();\n }\n\n /**\n * Persisted, not held in memory: the daemon dies with the TUI, and a\n * process-local override meant every reopen silently reinstated the\n * environment's defaults over what the user had chosen.\n */\n setRunnerEnabled(id: string, enabled: boolean): void {\n // Worked out from the file as it is when written, not from an earlier read.\n this.settingsService.updateEnabledRunners((saved) => {\n const current = saved ?? new WebConfig().enabledRunners;\n return enabled\n ? (current.includes(id) ? current : [...current, id])\n : current.filter((r) => r !== id);\n });\n }\n\n /**\n * What `sessionId`, or a client in `workspace`, plans with: the planner's\n * model is judged against that workspace's runner catalog (see\n * {@link settingsWorkspace}).\n */\n getSettings(sessionId?: string, workspace?: string): SettingsResponse {\n const config = this.plannerConfig(undefined, this.settingsWorkspace(sessionId, workspace));\n const userSettings = this.settingsService.getAll();\n const live = sessionId ? this.live(sessionId, workspace) : undefined;\n return {\n orchestratorModel: config.orchestratorModel,\n // Who plans (ADR-0009) — a vendor id, or one of the three harness\n // planners. Surfaces need it to render the planner picker and to know\n // whether the planner model comes from a runner catalog or a vendor one.\n aiProvider: config.aiProvider,\n // A harness planner's thinking effort (ADR-0009). Surfaces need it back\n // to render the current level; without it the picker shows \"default\"\n // for a planner that is running at \"high\".\n plannerThinkingEffort: config.plannerThinkingEffort ?? '',\n // The saved level, read through the service so an environment override\n // is reported the way the next plan will read it (ADR-0001, ADR-0030).\n autonomousMode: this.settingsService.autonomousMode(),\n maxParallel: config.maxParallelSessions,\n modelAllowlist: userSettings.modelAllowlist,\n // The model remembered per planner backend (this task), so a surface can\n // render what's remembered without a second round-trip.\n plannerModels: userSettings.plannerModels,\n // An open session shows what it was opened with; a closed or unknown id\n // falls back to the file, which is what a new session starts from (ADR-0030).\n run: live?.runSettings() ?? this.settingsService.getRunSettings(),\n };\n }\n\n /**\n * Save the user's run settings, and apply them at once to `sessionId`'s run\n * when that session is open here (ADR-0030). Other sessions keep the values\n * they were opened with. Throws a {@link RunSettingsError}, saving nothing,\n * for a value out of range.\n */\n updateRunSettings(changes: Partial<GlobalRunSettings>, sessionId?: string, workspace?: string): SettingsResponse {\n // Looked up first, so a change refused for another workspace's session saves nothing either.\n const live = sessionId ? this.live(sessionId, workspace) : undefined;\n this.settingsService.updateRunSettings(changes);\n live?.applyRunSettings(changes);\n return this.getSettings(sessionId, workspace);\n }\n\n /** The `containers` setting as a surface shows it: `prove` starts a throwaway container to measure (ADR-0059 L3). */\n containerStatus(prove: boolean, workspace?: string): Promise<ContainerStatus> {\n const { worktreeSetupCommand: setupCommand } = this.plannerConfig(undefined, workspace);\n return containerStatus(this.settingsService.getAll().containers, { prove, ...this.docker(), ...(setupCommand ? { setupCommand } : {}) });\n }\n\n /** The way a surface changes that setting, and where it then stands; a running Session keeps what it opened with. */\n async changeContainers(change: ContainerChange, workspace?: string): Promise<ContainerChangeResponse> {\n const refused = await changeContainers(change, { settings: this.settingsService, ...this.docker() });\n return { refused, status: await this.containerStatus(false, workspace) };\n }\n\n private docker(): { cli?: DockerCli } {\n return this.suppliedDockerCli ? { cli: this.suppliedDockerCli } : {};\n }\n\n /**\n * The workspace whose runner catalog a settings read or write is judged\n * against: an open session's own, else the one the client says it is in,\n * refused for a session another workspace holds under the id. Without either\n * the daemon's cwd stands in. One daemon serves several\n * workspaces, and each may name another Claude account in its environment.\n */\n private settingsWorkspace(sessionId: string | undefined, workspace: string | undefined): string | undefined {\n return (sessionId ? this.live(sessionId, workspace)?.workspaceRoot : undefined) ?? workspace;\n }\n\n /**\n * The catalog `selectPlanner` should judge `provider`'s\n * remembered model against — a harness planner's own runner catalog, or the\n * cross-provider picker list for a vendor (ADR-0009), same split as\n * `plannerModelItems` in the TUI reducer. Read from whatever the resolver\n * has already cached so this stays synchronous; the routes discover it\n * first where it decides the answer ({@link discoverPlannerCatalogs},\n * {@link writeSettings}), and a catalog still cold degrades to an empty one\n * rather than kicking off discovery mid-settings-write.\n */\n private plannerCatalogFor(provider: PlannerBackendId, workspace?: string): PlannerModelCandidate[] {\n return this.resolverFor(workspace).cachedPlannerCatalog(provider);\n }\n\n /**\n * Discover the runner catalog a settings read for `workspace` is judged\n * against, when the read consults one not yet held. Most reads consult\n * none — a vendor planner, a model picked in that workspace, an agent's\n * alias or remembered pick — and answer at once, however slow the runner\n * is to list its models (ADR-0040). Only a configured model whose owner\n * only the catalog can tell waits: a cold one would report the wrong model.\n * Never throws: a catalog that cannot be discovered stays empty.\n */\n async discoverPlannerCatalogs(sessionId: string | undefined, requestWorkspace: string | undefined): Promise<void> {\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n const consulted: PlannerBackendId[] = [];\n void this.plannerConfig(undefined, workspace, (provider) => {\n consulted.push(provider);\n return this.plannerCatalogFor(provider, workspace);\n }).planner;\n await this.discoverUnheld(workspace, consulted);\n }\n\n /**\n * {@link updateSettings} as a route makes it. A write that changes who plans\n * lands after the planner writes made before it and, where its judgement\n * reads a catalog not yet held, waits for that one; every other write — a\n * key, an allowlist, a limit — lands at once (ADR-0040).\n */\n async writeSettings(changes: Record<string, unknown>, sessionId?: string, requestWorkspace?: string): Promise<SettingsUpdateResponse> {\n const change = plannerChangeOf(changes, admittedEnv(changes)?.accepted);\n if (!changesPlanner(change)) return this.updateSettings(changes, sessionId, requestWorkspace);\n const turn = this.plannerWrites.then(async () => {\n // Judged once the writes before it have landed: one may have switched.\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n const judging = this.catalogJudging(change, workspace);\n await this.discoverUnheld(workspace, judging ? [judging] : []);\n return this.updateSettings(changes, sessionId, requestWorkspace);\n });\n this.plannerWrites = turn.catch(() => undefined);\n return turn;\n }\n\n /**\n * The provider whose catalog `selectPlanner` reads to judge `change`: a\n * switch with no model of its own restores the remembered pick only from\n * the incoming catalog, and an agent's effort alone survives only where its\n * model in effect offers it. An explicit model is the user's word whatever\n * the catalog lists, and a cold catalog refuses no effort, so it reads none.\n */\n private catalogJudging(change: PlannerSelectionChange, workspace: string | undefined): PlannerBackendId | undefined {\n const current = this.plannerProviderInEffect(workspace);\n const provider = change.provider ?? current;\n const model = change.model?.trim();\n if (provider !== current) return model ? undefined : provider;\n return model === undefined && change.effort !== undefined && runnerForProvider(provider) ? provider : undefined;\n }\n\n /**\n * Discover the catalogs of `providers` that `workspace`'s resolver does not\n * hold yet; a held one, or a degraded one discovery still remembers,\n * answers at once. Never throws.\n */\n private async discoverUnheld(workspace: string | undefined, providers: PlannerBackendId[]): Promise<void> {\n const resolver = this.resolverFor(workspace);\n await Promise.all([...new Set(providers)].map((provider) => resolver.plannerCatalog(provider)));\n }\n\n /**\n * The provider planning right now. A vendor planner is resolved from its\n * model id, so this is read again after a write rather than carried over.\n */\n private plannerProviderInEffect(workspace: string | undefined): PlannerBackendId {\n return this.plannerConfig(undefined, workspace).aiProvider;\n }\n\n updateSettings(changes: Record<string, unknown>, sessionId?: string, requestWorkspace?: string): SettingsUpdateResponse {\n const workspace = this.settingsWorkspace(sessionId, requestWorkspace);\n // Read before any of this call's changes land, so a switch is judged\n // against what was actually in effect a moment ago. The model and effort\n // too, with where they came from: a detected agent does not plan with a\n // vendor model left in the environment, and judging against it would\n // remember that model as the agent's own pick.\n const current: PlannerSelectionCurrent = this.plannerConfig(undefined, workspace).planner;\n\n // Only allowlisted keys reach `process.env`, and everything else comes back\n // to the caller by name — the daemon's environment is inherited by every\n // runner it spawns, so this write is the whole of `admitSettingsEnv`'s\n // reason to exist. All downstream reads below use `envChanges`, which is\n // the admitted subset, never the raw body.\n const admission = admittedEnv(changes);\n const envChanges = admission ? admission.accepted : undefined;\n\n const plannerChange = plannerChangeOf(changes, envChanges);\n // Judged against the incoming provider's catalog as already discovered —\n // before the credential refresh below clears the resolver's cache — so\n // the write itself never waits on (async) discovery.\n const selection = changesPlanner(plannerChange)\n ? selectPlanner(current, plannerChange, this.plannerModelMemory, this.plannerCatalogFor(plannerChange.provider ?? current.provider, workspace))\n : undefined;\n\n if (envChanges) {\n let touched = false;\n for (const [key, value] of Object.entries(envChanges)) {\n process.env[key] = value;\n // Only a credential or endpoint change touches what a catalog\n // contains. A planner, model or effort pick does not, and invalidating\n // on one would wipe the very cache `plannerCatalogFor` reads\n // synchronously, right before the next call's switch needs it.\n if (PROVIDER_CREDENTIAL_ENV.has(key)) touched = true;\n }\n // The scheduler reads the limit on every tick, but a raised one would\n // only be seen at the next verdict; the runs waiting for a slot start now.\n if (envChanges.ORDEWELL_MAX_PARALLEL !== undefined) {\n for (const [id, session] of this.sessions) {\n session.reschedule().catch((err) => {\n console.error(`[web] reschedule failed for session ${id}: ${err instanceof Error ? err.message : err}`);\n });\n }\n }\n // A new/changed provider key or base URL must re-probe the catalog, every\n // workspace's included; without this the picker keeps serving the\n // pre-key cache until restart.\n if (touched) {\n this.modelResolver.invalidate();\n this.dropUnkeyedProviderLists();\n // A saved key can sign an agent in with no login of its own (ADR-0060,\n // R9): a signed-out verdict taken before it, recorded or cached, is no\n // longer evidence, and the next start must not be refused on it.\n forgetSignedOutRunnerAuth();\n for (const installation of new Set([this.runnerInstallation, ...this.workspaceInstallations.values()])) installation.refresh?.();\n }\n }\n\n if (selection) {\n // An effort on its own leaves the configured model as it was: a\n // detected agent's model in effect can be its remembered one, which a\n // key added later must not find written over the configured model.\n if (plannerChange.provider !== undefined || plannerChange.model !== undefined) process.env.ORCHESTRATOR_MODEL = selection.next.model;\n process.env.ORDEWELL_PLANNER_EFFORT = selection.next.effort;\n // Read once the env above is written: the pick is for whoever that\n // routes to, which a switch or the model's own catalog may have changed.\n if (plannerChange.model !== undefined) {\n this.pickedModel = { model: selection.next.model, provider: this.plannerProviderInEffect(workspace), workspace: workspaceKey(workspace) };\n }\n }\n\n if (changes.modelAllowlist && typeof changes.modelAllowlist === 'object') {\n const allowlist = changes.modelAllowlist as Record<string, unknown>;\n for (const [runner, ids] of Object.entries(allowlist)) {\n if (Array.isArray(ids)) {\n this.settingsService.setModelAllowlist(runner, ids.map(String));\n } else if (ids === null) {\n this.settingsService.setModelAllowlist(runner, undefined);\n }\n }\n }\n\n // Full/Guarded is a saved user setting (ADR-0030), not an environment\n // write: ORDEWELL_AUTONOMOUS_MODE is refused below on purpose.\n if (typeof changes.autonomousMode === 'boolean') {\n this.settingsService.setAutonomousMode(changes.autonomousMode);\n }\n\n if (envChanges) for (const monitor of this.accountLimits.values()) monitor.refresh();\n\n if (selection?.remember) {\n const { provider, model, effort } = selection.remember;\n // Without a switch a vendor pick is keyed by the provider its model id\n // resolves to now, which the env written above already reflects.\n const switched = provider !== current.provider;\n this.plannerModelMemory.remember(switched ? provider : this.plannerProviderInEffect(workspace), model, effort);\n }\n\n // Refused keys are named back rather than dropped: a client that sent one\n // wrote it to `.env` on the strength of this response, and would otherwise\n // reinstate the refusal as the next daemon's startup environment.\n const rejectedEnvKeys = admission?.rejected ?? [];\n const settings: SettingsUpdateResponse = this.getSettings(sessionId, workspace);\n if (rejectedEnvKeys.length > 0) settings.rejectedEnvKeys = rejectedEnvKeys;\n if (selection?.recall) settings.switchRecall = selection.recall;\n return settings;\n }\n\n /**\n * A vendor whose credential is gone keeps no list to route a model to it,\n * or the next turn would be sent to a planner the settings response no\n * longer names. Pruned rather than cleared: the vendors that still hold a\n * key keep routing their models until the catalog is discovered again, so\n * adding a second key does not move the planner off the first.\n */\n private dropUnkeyedProviderLists(): void {\n if (!this.cachedProviderLists) return;\n const keyed = new Set<string>(configuredProviders(new WebConfig()));\n this.cachedProviderLists = Object.fromEntries(\n Object.entries(this.cachedProviderLists).filter(([provider]) => keyed.has(provider)),\n );\n }\n\n setOrchestratorModel(model: string): string {\n process.env.ORCHESTRATOR_MODEL = model;\n return model;\n }\n\n /**\n * The catalog as `workspace`'s runners see it: Claude Code's picker lineup\n * follows the `CLAUDE_CONFIG_DIR` that workspace's environment sets.\n * Without a workspace the daemon's cwd stands in.\n */\n async getProviderModels(workspace?: string): Promise<ModelsResponse> {\n const config = new WebConfig();\n const resolver = this.resolverFor(workspace);\n\n const runnerIds = this.registry.list().map((p) => p.manifest.name);\n const sandbox = this.codexSandbox.ensure();\n // Awaited below; marked handled now, so a failed catalog load before then\n // does not leave its rejection unhandled.\n sandbox.catch(() => {});\n // The vendor catalogs first: a runner started on a key Ordewell holds can\n // be handed the model that key's catalog says its account is served\n // (Qwen's, ADR-0060 R9), and a discovery begun before the catalog is held\n // would list a model the account may be refused, until the next refresh.\n const providerLists = await resolver.refresh();\n const [runnerModels] = await Promise.all([resolver.modelsForRunners(runnerIds), sandbox]);\n\n // `refresh()` populates the picker cache, so this is the same fetch — no\n // second network round-trip. Errors are whatever that fetch recorded.\n const orchestratorModels = await resolver.pickerOptions();\n const providerErrors = resolver.getDiscoveryErrors();\n const runnerErrors = resolver.getRunnerDiscoveryErrors();\n\n this.cachedProviderLists = providerLists;\n\n const allModels: DiscoveredModel[] = [];\n const seen = new Set<string>();\n const modelsByRunner: Record<string, DiscoveredModel[]> = {};\n\n for (const id of runnerIds) {\n modelsByRunner[id] = runnerModels[id] ?? [];\n for (const m of modelsByRunner[id]) {\n if (!seen.has(m.modelId)) {\n seen.add(m.modelId);\n allModels.push(m);\n }\n }\n }\n\n const providers = configuredProviders(config);\n\n return {\n models: allModels,\n modelsByRunner,\n modesByRunner: runnerModesFrom(this.registry, runnerIds),\n orchestratorModel: this.plannerConfig(undefined, workspace).orchestratorModel,\n providers,\n orchestratorModels,\n providerErrors,\n runnerErrors,\n };\n }\n\n getRunnerState(workspace?: string): { enabledRunners: RunnerId[]; orchestratorModel: string } {\n const config = this.plannerConfig(undefined, workspace);\n return { enabledRunners: config.enabledRunners, orchestratorModel: config.orchestratorModel };\n }\n\n /**\n * The resolver whose runner catalogs are discovered under `workspace`'s\n * environment, the one its tasks are launched with. Kept per workspace,\n * since one daemon serves several and a catalog is cached until refreshed;\n * the vendor catalogs are shared by all of them.\n */\n private resolverFor(workspace: string | undefined): ModelResolver {\n if (this.suppliedModelResolver || !workspace) return this.modelResolver;\n const key = workspaceKey(workspace);\n if (key === workspaceKey(undefined)) return this.modelResolver;\n return this.modelResolver.withRunnerEnv(key, async () => ({ ...process.env, ...(await workspaceEnvOf(key)) }));\n }\n\n /**\n * The probe that judges a login for `workspace`, cached so its install and\n * auth verdicts survive between runner-list refreshes. Without a workspace\n * the daemon's cwd is what the request would plan with anyway.\n */\n private installationFor(workspace: string | undefined): RunnerInstall {\n if (this.suppliedRunnerInstallation) return this.suppliedRunnerInstallation;\n if (!workspace) return this.runnerInstallation;\n const key = resolve(workspace);\n let installation = this.workspaceInstallations.get(key);\n if (!installation) {\n installation = new RunnerInstallation(this.registry, undefined, undefined, {\n env: () => workspaceEnvOf(key),\n workspace: () => key,\n });\n this.workspaceInstallations.set(key, installation);\n }\n return installation;\n }\n\n /**\n * Runners whose CLI is actually installed on the host, with display name and\n * enabled state. Only these should be offered for selection — an uninstalled\n * runner can't be spawned. `workspace` names whose account the auth verdict\n * is about; without it the daemon's cwd stands in.\n */\n async getInstalledRunners(workspace?: string): Promise<RunnersResponse['runners']> {\n // The runner list is the one place a user who just fixed their host looks\n // again, so every cached answer is asked afresh: the Codex sandbox, the\n // install verdicts, and the agent detection behind the no-choice defaults.\n await this.codexSandbox.refresh();\n const installation = this.installationFor(workspace);\n installation.refresh?.();\n await this.detectInstalledPlanner();\n\n const config = new WebConfig({ enabledRunners: this.enabledRunnerOverride() });\n const enabled = new Set(config.enabledRunners);\n const runners = this.registry.list();\n const installedIds = new Set(\n await installation.filterInstalled(runners.map((p) => p.manifest.name)),\n );\n // The auth verdict rides along, never gating the list: a signed-out agent\n // is installed and offered, and a surface flags it. The probe was just\n // asked above and its answer is cached, so this costs no second spawn.\n // An installed CLI that cannot be started — a Windows `.cmd` shim, or an\n // ACP agent below its minimum version — stays in the list as unavailable\n // with its reason, so a surface can say why instead of hiding it (ADR-0009,\n // ADR-0060).\n return Promise.all(\n runners\n .filter((p) => installedIds.has(p.manifest.name))\n .map(async (p): Promise<RunnersResponse['runners'][number]> => {\n const { usable, reason, auth, version } = await installation.runnerUsability(p.manifest.name);\n return {\n id: p.manifest.name,\n name: p.manifest.displayName,\n enabled: enabled.has(p.manifest.name),\n ...(usable ? {} : { usable: false, ...(reason ? { reason } : {}) }),\n ...(auth ? { auth } : {}),\n ...(version ? { version } : {}),\n };\n }),\n );\n }\n\n async generatePlan(sessionId: string, goal: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Promise<PlanState> {\n const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride, workspace).aiProvider);\n if (recheck) await recheck;\n const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);\n return migratePlanState(await this.firstTurn(sessionId, session, () => session.generatePlan(goal, runners)));\n }\n\n /**\n * Judge the planner as the workspace's account is now, not as it was when the\n * list was last read: the signed-out refusal itself offers the runner's own\n * `auth login` as a way back, and that happens in another process. Only a\n * recorded signed-out verdict is asked again — unknown never blocks, and a\n * signed-in one is the runner's own failure to report. Null when there is\n * nothing to ask, so the turn registers at once as it always did.\n */\n private recheckSignedOutPlanner(workspace: string, provider: PlannerBackendId): Promise<void> | null {\n const runner = runnerForProvider(provider);\n if (!runner || recordedRunnerAuth(runner, workspace)?.state !== 'signed-out') return null;\n const installation = this.installationFor(workspace);\n installation.refresh?.();\n return installation.plannerUsability(runner).then(() => undefined);\n }\n\n /**\n * Build the session a new planning conversation runs in and register it in\n * place of any live one, for {@link firstTurn} to run its first turn on.\n */\n private openPlanningSession(sessionId: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Session {\n // The one it replaces must be this workspace's: another's is not this conversation to end.\n this.live(sessionId, workspace);\n const session = this.createSessionFor(sessionId, workspace, modelOverride, options);\n // Judged on the new session's config (which carries the request's model)\n // and before the old session is destroyed, so a refusal leaves it alone.\n // Not while the installed-planner probe is out: its answer can be the\n // planner, and judging the openrouter fallback now would refuse the very\n // keyless first run the probe exists for, so that judgement is the first\n // turn's own gate. The runners are judged on the same terms: before the\n // probe answers, the enabled set is a guess a refusal must not rest on.\n if (installedPlannerAnswered()) {\n session.assertPlannerReady();\n session.assertRunnersEnabled(runners);\n }\n // After the new session is built, so a refusal above leaves the live one\n // alone; before the set, so its runners and planner turn stop broadcasting.\n this.destroy(sessionId);\n // Registered before the blocking call, not after: research inside\n // the first planner turn can raise an approval and await the answer, and\n // that answer arrives over POST /api/approvals/:sessionId — which 404s\n // until the session is in this map. Registering only on return made the\n // first approval of every session unanswerable until its 5-minute timeout.\n this.registerSession(sessionId, workspace, session);\n this.warmCodexSandbox();\n return session;\n }\n\n /**\n * Conversational planning (ADR-0002): start the planner dialogue for a\n * session. Returns the current plan state — a committed plan when the\n * planner had enough context, otherwise the dialogue so far (last\n * assistant message lives in conversationHistory).\n */\n async startPlanning(sessionId: string, goal: string, runners: RunnerId[] | undefined, workspace: string, modelOverride?: string, options?: { allowInit?: boolean }): Promise<LegacyPlanState> {\n const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride, workspace).aiProvider);\n if (recheck) await recheck;\n const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);\n return this.firstTurn(sessionId, session, () => session.startPlanning(goal, runners));\n }\n\n /**\n * Continue the planner dialogue with the user's reply: queued behind the\n * first turn, even while it waits for the installed-planner probe, and\n * refused only while a turn of another kind holds the conversation. The\n * session's own planner gate waits for the probe and judges the planner, as\n * it does for every turn.\n */\n async continuePlanning(sessionId: string, message: string, workspace: string | undefined): Promise<LegacyPlanState> {\n const session = this.session(sessionId, workspace);\n // A reply is a planner turn like any other: the signed-out refusal offers\n // the runner's own login, which runs outside this process, so ask the\n // workspace's account again before the session's synchronous gate judges.\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.continueConversation(message);\n }\n\n /** Condense a session's conversation. The summary turn is a planner turn, so `cancelPlanning` stops it. */\n async compactConversation(sessionId: string, workspace: string | undefined): Promise<ConversationCompaction & { plan: LegacyPlanState }> {\n const session = this.session(sessionId, workspace);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n const compaction = await session.compactConversation();\n return { ...compaction, plan: session.planState! };\n }\n\n /**\n * Send now (ADR-0023): the Session stops the planner turn in flight and\n * answers this message in the turn that replaces it, ahead of anything\n * waiting. The recheck is the one a reply does before the gate: a login done\n * with the runner's own command is seen here too.\n */\n async forceSendPrompt(sessionId: string, message: string, workspace: string | undefined): Promise<LegacyPlanState> {\n const session = this.session(sessionId, workspace);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.forceSendPrompt(message);\n }\n\n /** Retry a compaction paused on the planner's context: a planner turn, and gated as one. */\n async retryPlannerCompaction(sessionId: string, workspace: string | undefined): Promise<LegacyPlanState> {\n const session = this.session(sessionId, workspace);\n const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);\n if (recheck) await recheck;\n return session.retryPlannerCompaction();\n }\n\n /**\n * Abort the planner turn in flight for a session, if any. Answers whether\n * there was one to cancel — the route reports that rather than 404ing a\n * session that simply is not planning right now.\n */\n cancelPlanning(sessionId: string, workspace: string | undefined): boolean {\n // A first turn still waiting for the probe is the session's to stop too.\n return this.live(sessionId, workspace)?.abortPlannerTurn() ?? false;\n }\n\n /**\n * Register a session persisted on disk so its plan becomes executable and\n * editable. Only sessions planned in this process are otherwise addressable,\n * which left a restored plan readable but inert — every task endpoint\n * answered \"Session not found\".\n *\n * No LLM call happens here: the plan is adopted as saved, and the planner is\n * only contacted when the user next sends a message.\n */\n adoptSavedSession(sessionId: string, workspace: string): LegacyPlanState {\n // Re-adopting would clear the execution log and drop a running plan back to\n // its saved state, so a live session wins over the file. Only one held for\n // this workspace: an id names a session within its workspace, and another\n // project's session under the same id is not an answer for this one.\n const live = this.heldHere(sessionId, workspace);\n if (live?.planState) return live.planState;\n\n const saved = loadSession(sessionId, workspace);\n if (!saved) throw new SessionNotFoundError();\n const elsewhere = this.sessionWorkspaces.get(sessionId);\n if (!live && elsewhere !== undefined) throw new SessionOpenElsewhereError(sessionId, elsewhere);\n\n const session = this.createSessionFor(sessionId, workspace);\n // The saved id is adopted too, so later persists rewrite the same file\n // instead of forking the session under a fresh identity. Refused while\n // another live host runs the session (ADR-0049); the session built for\n // it is let go, and the one live here, if any, keeps running.\n try {\n session.loadPlan(saved.plan, saved.meta.goal, workspace, { sessionId: saved.meta.id });\n } catch (err) {\n session.destroy();\n throw err;\n }\n // A live session with no plan yet is mid-planning; replacing it must stop that turn.\n this.destroy(sessionId);\n this.registerSession(sessionId, workspace, session);\n // What another host recorded while it held the session, before this one took it (ADR-0062 G6).\n session.foldUserActions();\n\n return session.planState ?? saved.plan;\n }\n\n /**\n * Fork a session's conversation into a new session and adopt it, so the\n * fork is addressable at once — through the same path a saved session is\n * adopted by, reading back the file the fork was written to. The original\n * keeps running, or planning, untouched.\n */\n forkConversation(sessionId: string, workspace: string | undefined): AdoptedFork {\n return this.adoptFork(this.session(sessionId, workspace).forkConversation());\n }\n\n /** A rewind is a fork from an earlier point, so it is adopted the same way. */\n rewindConversation(sessionId: string, index: number, workspace: string | undefined): AdoptedFork & { rewoundMessage: string } {\n const fork = this.session(sessionId, workspace).rewindConversation(index);\n return { ...this.adoptFork(fork), rewoundMessage: fork.rewoundMessage };\n }\n\n private adoptFork(fork: ConversationFork): AdoptedFork {\n return { sessionId: fork.sessionId, goal: fork.goal, plan: this.adoptSavedSession(fork.sessionId, fork.workspace) };\n }\n\n /**\n * Direct access to a session's interface — routes call the Session; the\n * pool only registers sessions and fans broadcasts out to WS clients. A\n * caller naming a workspace is refused another's, as {@link live} is. The\n * workspace is required, if only as undefined, so that no caller reaches a\n * session by its id without saying whose it asks for; and a route calls it\n * where it acts, after whatever it awaited, since the id may name another\n * project's session by then.\n */\n session(sessionId: string, workspace: string | undefined): Session {\n const session = this.live(sessionId, workspace);\n if (!session) throw new SessionNotFoundError();\n return session;\n }\n\n /**\n * Stop a session and drop it. A replacement under the same id (re-planning,\n * adopting) keeps its subscribers: they are watching the id, and the new\n * session's broadcasts continue on the same socket. An explicit delete or\n * close is different — the surface must stop drawing a session that no\n * longer exists — so those pass `notifyClients`.\n */\n destroy(sessionId: string, options?: { notifyClients?: boolean }): void {\n const workspace = this.sessionWorkspaces.get(sessionId);\n this.sessions.get(sessionId)?.destroy();\n this.sessions.delete(sessionId);\n this.sessionWorkspaces.delete(sessionId);\n this.releaseUnusedAccountLimits();\n // A root's socket outlives a replacement, its broadcasts arriving on it. A\n // child's cannot: it reads a directory that went with the old Session.\n this.childStreams.closeRoot(sessionId, options?.notifyClients ? 1001 : 1012);\n if (!options?.notifyClients) return;\n const clients = this.clients.get(sessionId);\n if (!clients) return;\n this.broadcast(sessionId, workspace, { type: 'notice', level: 'info', message: 'Session closed.' });\n for (const ws of clients) {\n if (ws.readyState === ws.OPEN) ws.close(1001, 'Session closed');\n }\n this.clients.delete(sessionId);\n }\n\n /**\n * Close `workspace`'s session for a surface that is done with it: it is\n * dropped now, and this resolves once all it started has gone. Another\n * workspace's open under the id is left alone. Judged when called, not when\n * the request began: a delete calls this after its tree stop, by when the\n * id may name a session another project opened meanwhile.\n */\n async close(sessionId: string, workspace: string): Promise<void> {\n const session = this.heldHere(sessionId, workspace);\n if (!session) return;\n this.destroy(sessionId, { notifyClients: true });\n await session.gone;\n }\n\n /** Stop the whole tree of `workspace`'s session, if it holds the id, and wait until it has gone; the session stays open (ADR-0055 D16). */\n async stopTree(sessionId: string, workspace: string): Promise<void> {\n await this.heldHere(sessionId, workspace)?.stopSubtree();\n }\n\n /**\n * What `workspace`'s session's tree left in the engine, which only the\n * `containers` setting says to look for (ADR-0059 L6). Nothing while another\n * workspace holds the id: its tree runs in containers under the same id.\n */\n reclaim(sessionId: string, workspace: string): Promise<void> {\n if (this.heldElsewhere(sessionId, workspace)) return Promise.resolve();\n return reclaimContainers(sessionId, this.settingsService.getAll().containers);\n }\n\n destroyAll(): void { for (const id of this.sessions.keys()) this.destroy(id); }\n}\n\nexport const scanWorkspaces = scanWorkspacesImpl;\n\nexport function getSessionList(workspace: string) { return listSessions(workspace); }\nexport function getSession(sessionId: string, workspace: string) { return loadSession(sessionId, workspace); }\n\n/**\n * A session and the children saved under it. Its tree stops first, since a\n * child at work cannot have its worktrees taken from under it (ADR-0055 D16).\n * Their runs go next: the files that follow are the only record that names\n * their worktrees and branches (D11). What git could not let go stops the\n * delete, with the records still in place and `close` not called, and is named\n * in the error. What the tree left in an engine goes last: its volumes are\n * nothing a person could go back to once its records have gone. That waits for\n * the session to have gone, not only stopped: a closing attempt still brings its\n * work back, and a helper that names a volume already taken makes it again, with\n * no label for anything to find it by.\n */\nexport async function removeSession(sessionId: string, workspace: string, stop: () => Promise<void>, close: () => Promise<void>, reclaim: () => Promise<void>): Promise<boolean> {\n await stop();\n const { refused } = await discardChildRuns(sessionId, workspace, createWorktreeIsolation({ config: new WebConfig() }));\n if (refused.length > 0) throw new Error(`The session was kept: ${refused.map(({ worktree, reason }) => `${worktree} (${reason})`).join(', ')}`);\n await close();\n await reclaim();\n return deleteSession(sessionId, workspace);\n}\n\n/** A write's `env`, split into what may reach `process.env` and what may not. */\nfunction admittedEnv(changes: Record<string, unknown>): ReturnType<typeof admitSettingsEnv> | undefined {\n const raw = changes.env;\n return raw && typeof raw === 'object' && !Array.isArray(raw) ? admitSettingsEnv(raw as Record<string, unknown>) : undefined;\n}\n\n/**\n * What a settings write asks of who plans. A pick arrives either as a\n * top-level field (a vendor model, `ordewell model set`) or through env\n * (`ordewell planner-effort`, the TUI's pickers); env wins, as it did when\n * both were written in that order. The provider is the name the client sent,\n * never re-derived from the model: a switch may have just cleared that model.\n * An `inherited` write is no pick at all: it is the environment a client was\n * started under, which the daemon would have inherited had the client spawned\n * it, so it is written as it stands and nothing in it is remembered.\n */\nfunction plannerChangeOf(changes: Record<string, unknown>, envChanges: Record<string, string> | undefined): PlannerSelectionChange {\n return changes.inherited === true ? {} : {\n provider: envChanges?.AI_PROVIDER,\n model: envChanges?.ORCHESTRATOR_MODEL ?? stringField(changes.orchestratorModel),\n effort: envChanges?.ORDEWELL_PLANNER_EFFORT ?? stringField(changes.plannerThinkingEffort),\n };\n}\n\nfunction changesPlanner(change: PlannerSelectionChange): boolean {\n return Object.values(change).some((v) => v !== undefined);\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Whether two workspaces are one project, as every judgement of whose an id is compares them. */\nfunction sameWorkspace(a: string, b: string): boolean {\n return resolve(a) === resolve(b);\n}\n\n/** One spelling per workspace; a request that names none is the daemon's cwd's. */\nfunction workspaceKey(workspace: string | undefined): string {\n return resolve(workspace ?? process.cwd());\n}\n","import type { Context } from 'hono';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport {\n AlreadyExecutingError,\n ConversationBusyError,\n ConversationEditError,\n NoPlanError,\n PlanEditError,\n PlannerNotReadyError,\n PlannerTurnDiscardedError,\n PlannerTurnStoppedError,\n SessionHeldError,\n SessionNotFoundError,\n TaskControlError,\n UserGitError,\n WorkspaceNotAProjectError,\n WorkspaceNotFoundError,\n WorkspaceReadError,\n type DaemonErrorCode,\n type ErrorBody,\n} from '@ordewell/core';\nimport { SessionOpenElsewhereError } from '../pool/orchestratorPool';\n\ninterface Classified {\n status: ContentfulStatusCode;\n code: DaemonErrorCode;\n}\n\n/** A request body that is missing, not JSON, or not an object: the request's fault, never a fault of the daemon. */\nexport class InvalidBodyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidBodyError';\n }\n}\n\n/** An id the tree does not hold, whatever else it might name. */\nexport class ChildNotFoundError extends Error {\n constructor() {\n super('This tree has no such child plan.');\n this.name = 'ChildNotFoundError';\n }\n}\n\n/**\n * The body of a route that needs one object. Every route that read\n * `c.req.json()` directly turned a client's typo into a 500 with the parser's\n * message and a logged stack, while its neighbours answered 400.\n */\nexport async function jsonObject<T extends object = Record<string, unknown>>(c: Context): Promise<T> {\n let parsed: unknown;\n try {\n parsed = await c.req.json();\n } catch {\n throw new InvalidBodyError('The request body must be valid JSON.');\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new InvalidBodyError('The request body must be a JSON object.');\n }\n return parsed as T;\n}\n\n/**\n * The one table from a thrown class to a status and a stable code. A refusal is\n * the request being wrong (400) or arriving at a bad moment (409), a missing\n * session is 404, and only what falls through is a fault — collapsing these\n * into 404/500 gave the TUI and VS Code nothing to show but \"Internal error\",\n * which reads as the edit having silently done nothing.\n *\n * Order matters: `ConversationBusyError` extends `ConversationEditError`.\n */\nfunction classify(err: unknown): Classified | undefined {\n if (err instanceof InvalidBodyError) return { status: 400, code: 'refused' };\n if (err instanceof SessionNotFoundError) return { status: 404, code: 'session_not_found' };\n if (err instanceof ChildNotFoundError) return { status: 404, code: 'child_not_found' };\n // 409: the session exists; another host has it open right now (ADR-0049).\n if (err instanceof SessionHeldError) return { status: 409, code: 'session_held' };\n // 409: this workspace's session exists; the id is taken here by another workspace's, open now.\n if (err instanceof SessionOpenElsewhereError) return { status: 409, code: 'refused' };\n if (err instanceof NoPlanError) return { status: 400, code: 'no_plan' };\n if (err instanceof AlreadyExecutingError) return { status: 409, code: 'already_executing' };\n if (err instanceof WorkspaceNotAProjectError) return { status: 400, code: 'workspace_not_a_project' };\n if (err instanceof WorkspaceNotFoundError) return { status: 400, code: 'workspace_not_found' };\n // 409: the request is fine; the machine is not set up to serve it yet.\n if (err instanceof PlannerNotReadyError) return { status: 409, code: 'planner_not_ready' };\n // 409, not 5xx: the turn ending is what the user asked for (or a plan they\n // dropped), and a 5xx would log a stack for every Stop.\n if (err instanceof PlannerTurnStoppedError) return { status: 409, code: 'planner_turn_stopped' };\n if (err instanceof PlannerTurnDiscardedError) return { status: 409, code: 'planner_turn_discarded' };\n if (err instanceof ConversationBusyError) return { status: 409, code: 'conversation_busy' };\n // A user read (ADR-0064): a scope that no longer exists is gone (410), never\n // answered from another; a path outside the scope is forbidden, not missing.\n if (err instanceof WorkspaceReadError) {\n if (err.code === 'gone') return { status: 410, code: 'gone' };\n if (err.code === 'path_refused') return { status: 403, code: 'path_refused' };\n if (err.code === 'path_not_found') return { status: 404, code: 'path_not_found' };\n return { status: 400, code: 'refused' };\n }\n // A user git action (ADR-0062): what changed under the person, or a run\n // holding the branch, is a bad moment (409); git's own refusal (a hook, a\n // rejected push) is the person's repository answering, not a daemon fault.\n if (err instanceof UserGitError) {\n if (err.code === 'landing_branch_held' || err.code === 'confirm_stale' || err.code === 'stale') return { status: 409, code: err.code };\n return { status: 400, code: err.code };\n }\n if (err instanceof ConversationEditError || err instanceof PlanEditError || err instanceof TaskControlError) {\n return { status: 400, code: 'refused' };\n }\n return undefined;\n}\n\n/** A refusal the route itself decided on, in the body shape every client reads. */\nexport function refuse(c: Context, status: ContentfulStatusCode, message: string, code?: DaemonErrorCode) {\n const body: ErrorBody = code ? { error: message, code } : { error: message };\n return c.json(body, status);\n}\n\n/**\n * A JSON error response from a thrown call. What `classify` does not know is a\n * fault and takes the route's `fallback` status; only a 5xx is logged, since a\n * refusal is the request being wrong and travels to the client as-is.\n */\nexport function failure(\n c: Context,\n err: unknown,\n label: string,\n { fallback = 500, message = 'Internal error' }: { fallback?: ContentfulStatusCode; message?: string } = {},\n) {\n const classified = classify(err);\n const status = classified?.status ?? fallback;\n // Log before returning: the message alone travels to the client, so an\n // unexpected throw (a research tool crashing the whole turn, say) left no\n // stack anywhere — server.log showed nothing and the CLI showed one line.\n if (status >= 500) console.error(`[web] ${label} failed:`, err);\n const body: ErrorBody = {\n error: (err instanceof Error && err.message) || message,\n ...(classified ? { code: classified.code } : {}),\n ...(err instanceof WorkspaceNotAProjectError ? { workspace: err.workspace } : {}),\n ...(err instanceof PlannerNotReadyError ? { plannerNotReady: err.reason } : {}),\n ...(err instanceof SessionHeldError ? { sessionHeld: err.held } : {}),\n ...(err instanceof UserGitError && err.detail.held ? { landingBranchHeld: err.detail.held } : {}),\n ...(err instanceof UserGitError && err.detail.difference ? { confirmStale: err.detail.difference } : {}),\n };\n return c.json(body, status);\n}\n","import type { Context, MiddlewareHandler } from 'hono';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure } from './errors';\n\n/**\n * The workspace a request names, for every pool lookup its handler makes. A\n * caller naming none reaches a session by its id alone, as before workspaces\n * were checked.\n */\nexport function callerWorkspace(c: Context): string | undefined {\n return c.req.query('workspace') || undefined;\n}\n\n/**\n * Every route under a session id reaches the live session through\n * `pool.live` with the workspace the client names, before its handler runs.\n * The pool keeps one session per id, so a request from another project's copy\n * of the id would otherwise read, drive or replace the project holding it; one\n * guard on the whole router also covers a route added after this one.\n *\n * It is judged once, before the handler reads a body or awaits anything, so it\n * is the early answer and not the safeguard: a handler passes\n * {@link callerWorkspace} to the lookup it acts through, at the point it acts.\n */\nexport function sameWorkspace(pool: OrchestratorPool, param: 'id' | 'sessionId'): MiddlewareHandler {\n return async (c, next) => {\n const workspace = callerWorkspace(c);\n if (workspace) {\n try {\n pool.live(c.req.param(param) ?? '', workspace);\n } catch (err) {\n return failure(c, err, 'reach session');\n }\n }\n await next();\n };\n}\n","import { Hono, type Context } from 'hono';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport {\n listTaskLogAttempts,\n readTaskLog,\n taskLogForSurface,\n type ChildListResponse,\n type ChildMessageResponse,\n type ChildPlanHandle,\n type ChildPlanResponse,\n type ChildControlOutcome,\n type ChildTaskControlResponse,\n type DaemonErrorCode,\n type TaskLogAttemptsResponse,\n type TaskLogResponse,\n} from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { ChildNotFoundError, failure, jsonObject, refuse } from './errors';\nimport { callerWorkspace, sameWorkspace } from './liveSession';\n\nconst ABOVE_THIS_PLAN = 'A raise or a force is the plan above this one to give: this request sets neither.';\n\nconst CONTROL_REFUSALS: Record<Extract<ChildControlOutcome, { ok: false }>['code'], { status: ContentfulStatusCode; code: DaemonErrorCode }> = {\n view_only: { status: 409, code: 'child_view_only' },\n refused: { status: 409, code: 'child_refused' },\n no_task: { status: 404, code: 'child_task_not_found' },\n not_waiting: { status: 409, code: 'checkpoint_not_waiting' },\n};\n\n/**\n * Selecting, reading and speaking to the plans below a root (ADR-0055 D20).\n * Each goes through the root a surface holds, and its directory, so an id this\n * tree does not name reads nothing. A person's message is the words and nothing\n * else: no field here raises a budget, adds a grant or approves an effect. A\n * checkpoint is answered on the plan that holds it, under what that plan's own\n * subplanner may do, and a task id is the plan's exactly: nothing here resolves\n * a reference or falls back to the root. An unloaded root answers\n * `session_not_found`, and `POST /:id/load` loads it, starting nothing.\n */\nexport function childrenRoute(pool: OrchestratorPool) {\n const router = new Hono();\n router.use('/:id/children', sameWorkspace(pool, 'id'));\n router.use('/:id/children/*', sameWorkspace(pool, 'id'));\n\n // A handler that reads a body finds the child after it: while the body\n // arrived, the root's id may have come to name another workspace's session.\n const childOf = async (c: Context): Promise<ChildPlanHandle> => {\n const child = await pool.session(c.req.param('id')!, callerWorkspace(c)).children.find(c.req.param('childId')!);\n if (!child) throw new ChildNotFoundError();\n return child;\n };\n const position = (c: Context) => pool.childPosition(c.req.param('id')!, c.req.param('childId')!, callerWorkspace(c));\n const controlled = (c: Context, outcome: ChildControlOutcome) => {\n if (!outcome.ok) return refuse(c, CONTROL_REFUSALS[outcome.code].status, outcome.message, CONTROL_REFUSALS[outcome.code].code);\n return c.json({ message: outcome.message, ...(outcome.id ? { id: outcome.id } : {}) } satisfies ChildTaskControlResponse);\n };\n // The root's routes take these. Dropped here, a person would believe a raise\n // or a force went through; the plan above holds both (ADR-0056 M8).\n const asksAboveItsPlan = (body: object) => 'raiseTokens' in body || 'force' in body;\n\n router.get('/:id/children', async (c) => {\n try {\n return c.json({ children: await pool.session(c.req.param('id'), callerWorkspace(c)).children.list() } satisfies ChildListResponse);\n } catch (err) {\n return failure(c, err, 'list child plans');\n }\n });\n\n router.get('/:id/children/:childId', async (c) => {\n try {\n const child = await childOf(c);\n return c.json({ ...child.view(), position: position(c) } satisfies ChildPlanResponse);\n } catch (err) {\n return failure(c, err, 'read child plan');\n }\n });\n\n router.get('/:id/children/:childId/tasks/:taskId/log', async (c) => {\n try {\n const child = await childOf(c);\n return c.json({ attempts: listTaskLogAttempts(child.logLocation(), c.req.param('taskId')), position: position(c) } satisfies TaskLogAttemptsResponse);\n } catch (err) {\n return failure(c, err, 'list child task log');\n }\n });\n\n router.get('/:id/children/:childId/tasks/:taskId/log/:attempt', async (c) => {\n try {\n const child = await childOf(c);\n const attempt = Number(c.req.param('attempt'));\n if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, 'attempt must be a positive integer');\n return c.json({ attempt, events: taskLogForSurface(readTaskLog(child.logLocation(), c.req.param('taskId'), attempt)), position: position(c) } satisfies TaskLogResponse);\n } catch (err) {\n return failure(c, err, 'read child task log');\n }\n });\n\n router.post('/:id/children/:childId/message', async (c) => {\n try {\n const body = await jsonObject<{ message?: unknown }>(c);\n const child = await childOf(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n const { message } = body;\n if (typeof message !== 'string' || !message.trim()) return refuse(c, 400, 'message must be a non-empty string');\n const outcome = child.message(message);\n if (!outcome.ok) return refuse(c, 409, outcome.message, outcome.code === 'view_only' ? 'child_view_only' : 'child_refused');\n return c.json({ status: outcome.status } satisfies ChildMessageResponse);\n } catch (err) {\n return failure(c, err, 'message child plan');\n }\n });\n\n router.post('/:id/children/:childId/tasks/:taskId/message', async (c) => {\n try {\n const body = await jsonObject<{ message?: unknown }>(c);\n const child = await childOf(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n if (typeof body.message !== 'string' || !body.message.trim()) return refuse(c, 400, 'message must be a non-empty string', 'refused');\n return controlled(c, await child.control(c.req.param('taskId'), { kind: 'message', text: body.message }));\n } catch (err) {\n return failure(c, err, 'message child task');\n }\n });\n\n for (const answer of ['approve', 'reject'] as const) {\n router.post(`/:id/children/:childId/tasks/:taskId/checkpoint/${answer}`, async (c) => {\n try {\n const body = await jsonObject<{ question?: unknown; reason?: unknown }>(c);\n const child = await childOf(c);\n if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, 'refused');\n const { question } = body;\n if (typeof question !== 'string' || !question.trim()) return refuse(c, 400, 'question must be the words the task is waiting on', 'refused');\n if (body.reason !== undefined && typeof body.reason !== 'string') return refuse(c, 400, 'reason must be a string', 'refused');\n const reason = body.reason?.trim();\n if (answer === 'reject' && !reason) return refuse(c, 400, 'A rejection needs a reason: it is all the runner has to go on.', 'refused');\n return controlled(c, await child.control(c.req.param('taskId'), { kind: 'checkpoint', answer, question, ...(reason ? { reason } : {}) }));\n } catch (err) {\n return failure(c, err, 'answer child checkpoint');\n }\n });\n }\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { OrchestratorPool, getSessionList, removeSession } from '../pool/orchestratorPool';\nimport {\n listTaskLogAttempts,\n loadSession,\n migratePlanState,\n readTaskLog,\n surfacePlan,\n surfacePlanState,\n taskLogForSurface,\n type AdoptSessionResponse,\n type OkResponse,\n type SessionListResponse,\n type SessionResponse,\n type TaskLogAttemptsResponse,\n type TaskLogResponse,\n} from '@ordewell/core';\nimport { failure, refuse } from './errors';\n\nexport function sessionsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', (c) => {\n try {\n const ws = c.req.query('workspace') || process.cwd();\n // The saved status reads approved for as long as a run lasts: whether one is at work is the pool's word, or its holder's.\n const sessions: SessionListResponse = getSessionList(ws).map((meta) => {\n const run = pool.runActivity(meta.id, ws);\n return run ? { ...meta, run } : meta;\n });\n return c.json(sessions);\n } catch (err) {\n return failure(c, err, 'list sessions');\n }\n });\n\n /**\n * The saved file answers for a session nobody is holding. While the pool has\n * one, its store is the only honest source of task status: the file is\n * normalized as if nothing were running (`in_progress` → `pending`), so\n * serving it mid-run told every surface that the tasks it is watching had\n * never started.\n */\n router.get('/:id', (c) => {\n try {\n const ws = c.req.query('workspace') || process.cwd();\n const id = c.req.param('id');\n const saved = loadSession(id, ws);\n if (!saved) return refuse(c, 404, 'Session not found', 'session_not_found');\n // The pool keeps one session per id: one open for another workspace is not this file's session.\n const live = pool.holds(id, ws);\n const run = live ? pool.runSnapshot(id) : null;\n const plannerTurnId = live ? pool.plannerTurnId(id) : undefined;\n const plannerCompaction = live ? pool.plannerCompaction(id) : undefined;\n // The phase-tagged plan keeps no transcript: a client that joins or only reads the session redraws its chat from this.\n const { conversationHistory, researchLog, plannerUsage, pendingTurns } = surfacePlan((live ? pool.getPlan(id) : null) ?? saved.plan);\n return c.json({\n meta: saved.meta,\n plan: surfacePlanState((live ? pool.getPlanState(id) : null) ?? migratePlanState(saved.plan)),\n conversation: { conversationHistory, researchLog, plannerUsage, pendingTurns },\n ...(run ? { run } : {}),\n ...(plannerTurnId ? { plannerTurnId } : {}),\n ...(plannerCompaction ? { plannerCompaction } : {}),\n // Taken in the same turn as the read, so a client drops exactly the held frames it already holds.\n ...(live ? { position: pool.streamPosition(id) } : {}),\n } satisfies SessionResponse);\n } catch (err) {\n return failure(c, err, 'read session');\n }\n });\n\n /**\n * Adopt a saved session into the running server. `GET /:id` only reads the\n * file; until a session is registered with the pool there is no orchestrator\n * behind it, so execution and task control answer \"Session not found\".\n */\n router.post('/:id/load', (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n try {\n const id = c.req.param('id');\n const plan = pool.adoptSavedSession(id, ws);\n const run = pool.runSnapshot(id);\n const plannerTurnId = pool.plannerTurnId(id);\n const plannerCompaction = pool.plannerCompaction(id);\n return c.json({\n ok: true,\n plan: surfacePlan(plan),\n goal: pool.getGoal(id),\n ...(run ? { run } : {}),\n ...(plannerTurnId ? { plannerTurnId } : {}),\n ...(plannerCompaction ? { plannerCompaction } : {}),\n position: pool.streamPosition(id),\n } satisfies AdoptSessionResponse);\n } catch (err: unknown) {\n return failure(c, err, 'load session', { message: 'Failed to load session' });\n }\n });\n\n /**\n * A structured task's saved log (ADR-0018, P1), read off disk whether or\n * not the pool holds the session: every attempt is written as it happens,\n * so the file is as current as the stream a reopened view catches up with.\n */\n // Another workspace's session under this id streams nothing this log is part of.\n const position = (id: string, ws: string) => (pool.heldElsewhere(id, ws) ? {} : { position: pool.streamPosition(id) });\n\n router.get('/:id/tasks/:taskId/log', (c) => {\n try {\n const ws = c.req.query('workspace') || process.cwd();\n return c.json({ attempts: listTaskLogAttempts({ baseDir: ws, sessionId: c.req.param('id') }, c.req.param('taskId')), ...position(c.req.param('id'), ws) } satisfies TaskLogAttemptsResponse);\n } catch (err) {\n return failure(c, err, 'list task log');\n }\n });\n\n router.get('/:id/tasks/:taskId/log/:attempt', (c) => {\n try {\n const ws = c.req.query('workspace') || process.cwd();\n const attempt = Number(c.req.param('attempt'));\n if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, 'attempt must be a positive integer');\n return c.json({ attempt, events: taskLogForSurface(readTaskLog({ baseDir: ws, sessionId: c.req.param('id') }, c.req.param('taskId'), attempt)), ...position(c.req.param('id'), ws) } satisfies TaskLogResponse);\n } catch (err) {\n return failure(c, err, 'read task log');\n }\n });\n\n // The live session goes before its files: it persists as it changes, so one\n // left running would write its file back and reappear in the list. A delete\n // refused before that point leaves it open, its tree stopped. Only this\n // workspace's: another's open under the same id is not the one deleted, and\n // the containers its tree runs in carry the same id. The pool judges whose\n // session the id names at each step, not here: the tree stop can take long\n // enough for another workspace to open its own session of the id.\n router.delete('/:id', async (c) => {\n const ws = c.req.query('workspace') || process.cwd();\n const id = c.req.param('id');\n const held = pool.holds(id, ws);\n let removed: boolean;\n try {\n removed = await removeSession(id, ws, () => pool.stopTree(id, ws), () => pool.close(id, ws), () => pool.reclaim(id, ws));\n } catch (err) {\n return c.json({ ok: false, message: err instanceof Error ? err.message : String(err) } satisfies OkResponse);\n }\n const ok = held || removed;\n return c.json({\n ok,\n ...(ok ? {} : { message: `No session \"${id}\" was found in ${ws}.` }),\n } satisfies OkResponse);\n });\n\n // Stops the orchestrator (killing every runner it spawned, and every container\n // with what serves it) and drops the in-memory planner conversation, answering\n // once they have gone. No-op if already closed/unregistered, or open for\n // another workspace: that is another project's session under the same id.\n router.post('/:id/close', async (c) => {\n try {\n const id = c.req.param('id');\n await pool.close(id, c.req.query('workspace') || process.cwd());\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'close session');\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport {\n flattenTasks,\n isCardEdit,\n NoPlanError,\n parseExecutionCommand,\n resolveUserTaskRef,\n surfacePlan,\n surfacePlanState,\n TaskControlError,\n type CommandOutcome,\n type ConversationCompactResponse,\n type ConversationForkResponse,\n type ConversationRewindResponse,\n type ApproveReviewResponse,\n type AnswerEscalationRequest,\n type ErrorBody,\n type EscalationsResponse,\n type ExecuteCommandResponse,\n type ExecuteResponse,\n type ExecutionCommand,\n type GeneratePlanResponse,\n type IsolationDiffResponse,\n type IsolationMergeResponse,\n type MergeGateResponse,\n type TaskRevertPreviewResponse,\n type OkResponse,\n type PlanResponse,\n type PrdResponse,\n type ResolveConflictResponse,\n type RewindTargetsResponse,\n type StopResponse,\n type TaskMessageResponse,\n type Task,\n type CancelPlanningResponse,\n type CancelResumeResponse,\n} from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\nimport { callerWorkspace, sameWorkspace } from './liveSession';\n\nconst NO_CHECKPOINT = 'The task is not waiting at a checkpoint: it was answered already, withdrawn, or has no runner left to hear it.';\n\n/** The id of the task a reference names, as the seam resolves it — the user's unique id prefix included; the reference itself when the plan holds no such task, for the seam to refuse. */\nfunction idOfRef(session: ReturnType<OrchestratorPool['session']>, ref: string): string {\n return resolveUserTaskRef(session.planState?.tasks ?? [], ref)?.id ?? ref;\n}\n\n/** One execution button's command, run as the user (ADR-0029): a refusal becomes the 400 the surface already shows. */\nasync function runUserCommand(session: ReturnType<OrchestratorPool['session']>, command: ExecutionCommand): Promise<Extract<CommandOutcome, { ok: true }>> {\n const outcome = await session.execute(command, { kind: 'user' });\n if (!outcome.ok) throw new TaskControlError(outcome.message);\n return outcome;\n}\n\nexport function plansRoute(pool: OrchestratorPool) {\n const router = new Hono();\n router.use('/:sessionId', sameWorkspace(pool, 'sessionId'));\n router.use('/:sessionId/*', sameWorkspace(pool, 'sessionId'));\n\n router.post('/:sessionId/generate', async (c) => {\n try {\n const { goal, runners, workspace, model, allowInit } = await jsonObject<{\n goal?: string; runners?: string[]; workspace?: string; model?: string; allowInit?: boolean;\n }>(c);\n if (!goal) return c.json({ error: 'goal is required' }, 400);\n const ws = workspace || c.req.query('workspace') || process.cwd();\n const queryRunners = c.req.query('runners');\n // No runners in the request means \"whatever is enabled\", not claude-code:\n // a hard-coded default here contradicts the /runners toggle state and\n // fails planning for anyone who disabled claude-code. Left undefined for\n // the session to read after its planner gate, since before the installed\n // agents are detected the enabled default is not known yet.\n const runnerList: string[] | undefined = Array.isArray(runners) ? runners : (runners ? [runners] : (queryRunners ? queryRunners.split(',').map(s => s.trim()).filter(Boolean) : undefined));\n const plan = await pool.generatePlan(c.req.param('sessionId'), goal, runnerList, ws, model, { allowInit });\n const { models, modelsByRunner } = await pool.getProviderModels(ws);\n const notes = (pool.session(c.req.param('sessionId'), ws).planState?.conversationHistory ?? [])\n .filter((e) => e.kind === 'system')\n .map((e) => e.content);\n return c.json({ plan: surfacePlanState(plan), models, modelsByRunner, ...(notes.length > 0 ? { notes } : {}) } satisfies GeneratePlanResponse);\n } catch (err) {\n return failure(c, err, 'generate', { message: 'Plan generation failed' });\n }\n });\n\n router.post('/:sessionId/execute', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'), callerWorkspace(c));\n // The daemon contract keeps `no_plan` distinct from a plain refusal; the\n // seam refuses either way, so the code it cannot carry is kept here. A\n // run under way is no refusal: executing then approves what waits (#95).\n if (!session.planState || session.planTasks.length === 0) throw new NoPlanError('execute');\n const { message } = await runUserCommand(session, { command: 'run_plan' });\n return c.json({ status: 'running', message } satisfies ExecuteResponse);\n } catch (err) {\n return failure(c, err, 'execute');\n }\n });\n\n router.post('/:sessionId/stop', async (c) => {\n try {\n const session = pool.live(c.req.param('sessionId'), callerWorkspace(c));\n if (session) {\n const outcome = await session.execute({ command: 'stop_run' }, { kind: 'user' });\n // A refused stop is no failure while nothing can start: \"stopped\" is still true (ADR-0029).\n if (!outcome.ok && (session.isExecuting || session.startsPending)) throw new TaskControlError(outcome.message);\n return c.json({ status: 'stopped', message: outcome.message } satisfies StopResponse);\n }\n return c.json({ status: 'stopped' } satisfies StopResponse);\n } catch (err) {\n return failure(c, err, 'stop');\n }\n });\n\n // Distinct from the stop route above, which halts *execution* (running\n // tasks). This aborts a planning turn in flight — a harmless no-op, not a\n // 404, when the session simply isn't planning right now.\n router.post('/:sessionId/planning/stop', (c) => {\n try {\n const cancelled = pool.cancelPlanning(c.req.param('sessionId'), callerWorkspace(c));\n return c.json({ cancelled } satisfies CancelPlanningResponse);\n } catch (err) {\n return failure(c, err, 'stop planning');\n }\n });\n\n // Every execution button that is no more than \"this command, as the user\"\n // (ADR-0029, ADR-0006): the body is an ExecutionCommand, the answer is the\n // seam's own line and payload, and a refusal is the one 400 every route gives.\n // The routes beside it stay because they answer more than the seam does: a\n // `no_plan` code, the 409 for a checkpoint nobody waits at, the Merge all card.\n router.post('/:sessionId/execute-command', async (c) => {\n try {\n const parsed = parseExecutionCommand(await jsonObject(c));\n if (!parsed.ok) return refuse(c, 400, parsed.message, 'refused');\n const outcome = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).execute(parsed.command, { kind: 'user' });\n if (!outcome.ok) {\n // Not through TaskControlError: a Merge all that git stopped keeps the result it stopped with.\n return c.json({ error: outcome.message, code: 'refused', ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ErrorBody, 400);\n }\n return c.json({ ok: true, message: outcome.message, ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ExecuteCommandResponse);\n } catch (err) {\n return failure(c, err, 'execute-command');\n }\n });\n\n router.get('/:sessionId/escalations', (c) => {\n try {\n return c.json({ escalations: pool.session(c.req.param('sessionId'), callerWorkspace(c)).escalations() } satisfies EscalationsResponse);\n } catch (err) {\n return failure(c, err, 'escalations');\n }\n });\n\n // Always the user's: a planner or a supervisor has no route here (ADR-0053).\n router.post('/:sessionId/escalations/answer', async (c) => {\n try {\n const { id, option, note, confirmed } = await jsonObject<Partial<AnswerEscalationRequest>>(c);\n if (typeof id !== 'string' || typeof option !== 'string') return refuse(c, 400, 'id and option are required', 'refused');\n const outcome = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).answerEscalation(id, option, typeof note === 'string' ? note : undefined, confirmed === true);\n if (!outcome.ok) return c.json({ error: outcome.message, code: 'refused', ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ErrorBody, 400);\n return c.json({ ok: true, message: outcome.message, ...(outcome.payload ? { payload: outcome.payload } : {}) } satisfies ExecuteCommandResponse);\n } catch (err) {\n return failure(c, err, 'escalations');\n }\n });\n\n // The task runner's own slash command (#66): carried to the runner, never\n // one of Ordewell's. A task that cannot take one is refused with the reason.\n router.post('/:sessionId/tasks/:taskId/commands', async (c) => {\n try {\n const body: unknown = await c.req.json().catch(() => ({}));\n const fields = typeof body === 'object' && body !== null ? body as { name?: unknown; args?: unknown } : {};\n if (typeof fields.name !== 'string' || !fields.name.trim()) return c.json({ error: 'name is required' }, 400);\n const args = typeof fields.args === 'string' ? fields.args : '';\n const id = pool.session(c.req.param('sessionId'), callerWorkspace(c)).invokeTaskCommand(c.req.param('taskId'), fields.name.trim(), args);\n return c.json({ id } satisfies TaskMessageResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // Answer the checkpoint a task waits at: approve lets it go on, a delegated\n // task's child with its words and a raise, reject sends it the reason. Nothing\n // waiting — settled elsewhere, withdrawn, or no runner left to hear it — is a\n // 409, so a surface says so instead of claiming success.\n // The seam refuses a checkpoint nobody waits at too; this route keeps that\n // case apart as its own 409 and code.\n for (const answer of ['approve', 'reject'] as const) {\n router.post(`/:sessionId/tasks/:taskId/checkpoint/${answer}`, async (c) => {\n try {\n const body: unknown = await c.req.json().catch(() => ({}));\n const reason = typeof body === 'object' && body !== null && 'reason' in body && typeof body.reason === 'string' ? body.reason.trim() : '';\n const raiseTokens = typeof body === 'object' && body !== null && 'raiseTokens' in body ? body.raiseTokens : undefined;\n const raise = typeof raiseTokens === 'number' && Number.isSafeInteger(raiseTokens) && raiseTokens > 0 ? raiseTokens : undefined;\n if (raiseTokens !== undefined && raise === undefined) return refuse(c, 400, 'A raise is a whole number of tokens, 1 or more.', 'refused');\n const session = pool.session(c.req.param('sessionId'), callerWorkspace(c));\n const taskId = idOfRef(session, c.req.param('taskId'));\n // Resolved once: the pre-check and the seam judge the same task, the\n // user's unique id prefix included (ADR-0029).\n if (!session.awaitsCheckpoint(taskId)) return refuse(c, 409, NO_CHECKPOINT, 'checkpoint_not_waiting');\n const { message } = await runUserCommand(session, { command: 'answer_checkpoint', task: taskId, answer, ...(reason ? { reason } : {}), ...(raise !== undefined ? { raiseTokens: raise } : {}) });\n return c.json({ ok: true, message } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n }\n\n // What a task waits on at its merge gate (ADR-0020), for a surface that asks\n // before a force start passes it. Empty when nothing gates the task.\n router.get('/:sessionId/tasks/:taskId/merge-gate', (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'), callerWorkspace(c));\n const tasks = flattenTasks(session.planState?.tasks ?? []);\n // Named as the seam names a task, so a surface asks about the reference the user typed.\n const mergeGate = session.mergeGate(idOfRef(session, c.req.param('taskId'))).map((id) => {\n const dep = tasks.find((t) => t.id === id);\n return { id, order: dep?.order ?? 0, title: dep?.title ?? id };\n });\n return c.json({ mergeGate } satisfies MergeGateResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // What reverting a task would do now (ADR-0054), for a surface that confirms\n // before it sends `revert_task`. A refusal is the answer here, not an error.\n router.get('/:sessionId/tasks/:taskId/revert-preview', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'), callerWorkspace(c));\n return c.json((await session.revertPreview(idOfRef(session, c.req.param('taskId')))) satisfies TaskRevertPreviewResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // Isolated-run handoff (ADR-0013). A merge that conflicts or fails is an\n // outcome the surface reports, not a malformed request, so it answers 200.\n router.get('/:sessionId/isolation/diff', async (c) => {\n try {\n return c.json({ diff: await pool.session(c.req.param('sessionId'), callerWorkspace(c)).reviewRunDiff() } satisfies IsolationDiffResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/isolation/merge', async (c) => {\n try {\n // A merge git stopped is still an outcome the Merge all card shows: the seam refuses it, with the result.\n const body: unknown = await c.req.json().catch(() => ({}));\n const yes = (name: string) => typeof body === 'object' && body !== null && Reflect.get(body, name) === true;\n const outcome = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).execute({\n command: 'merge_all',\n ...(yes('pastChecks') ? { pastChecks: true } : {}),\n ...(yes('besideOps') ? { besideOps: true } : {}),\n }, { kind: 'user' });\n if (outcome.payload?.kind === 'merge') return c.json(outcome.payload.result satisfies IsolationMergeResponse);\n // Not a refusal of the request: the user is asked, the checks or ops tasks named, and the yes comes in the body.\n if (outcome.payload?.kind === 'merge_hold') return refuse(c, 409, outcome.message, 'merge_past_check');\n if (outcome.payload?.kind === 'merge_beside_ops') return refuse(c, 409, outcome.message, 'merge_beside_ops');\n if (!outcome.ok) throw new TaskControlError(outcome.message);\n throw new Error('Merge all answered without its result.');\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n for (const [segment, run] of [\n ['discard', (s: ReturnType<typeof pool.session>) => s.discardRun()],\n ['cleanup', (s: ReturnType<typeof pool.session>) => s.cleanupRun()],\n ['stash-and-continue', (s: ReturnType<typeof pool.session>) => s.continueWithStash()],\n ['run-without', (s: ReturnType<typeof pool.session>) => s.continueWithoutIsolation()],\n ] as const) {\n router.post(`/:sessionId/isolation/${segment}`, async (c) => {\n try {\n await run(pool.session(c.req.param('sessionId'), callerWorkspace(c)));\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n }\n\n router.post('/:sessionId/tasks/:taskId/resolve-conflict', async (c) => {\n try {\n const plan = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).resolveConflictAsTask(c.req.param('taskId'));\n return c.json({ plan: plan && surfacePlan(plan) } satisfies ResolveConflictResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.put('/:sessionId/tasks/:taskId', async (c) => {\n try {\n const changes = await jsonObject<Partial<Task>>(c);\n // JSON cannot carry undefined, so a null is a client clearing the model.\n if (changes.assignedModel === null) changes.assignedModel = undefined;\n // One edit, whatever it holds: the session takes the fields a direct\n // edit may set, moves the runner with what it scopes, checks the\n // dependency list against the whole plan, and lands it as one save. An\n // empty patch still asks whether the task exists at all.\n const result = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).updateTask(c.req.param('taskId'), changes);\n if (!result) return refuse(c, 404, 'Task not found', 'task_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n // The card's edit, whose not-started precondition the session derives from\n // its own run facts: a PUT of the same fields is the wider direct edit.\n router.post('/:sessionId/tasks/:taskId/card-edit', async (c) => {\n try {\n const edit = await jsonObject(c);\n if (!isCardEdit(edit)) return refuse(c, 400, 'Unknown card edit');\n const result = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).cardEdit(c.req.param('taskId'), edit);\n if (!result) return refuse(c, 404, 'Task not found', 'task_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.delete('/:sessionId/tasks/:taskId', async (c) => {\n try {\n const result = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).removeTask(c.req.param('taskId'));\n if (!result) return refuse(c, 404, 'Task not found', 'task_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/tasks', async (c) => {\n try {\n const body = await jsonObject<Partial<Task>>(c);\n const result = await pool.session(c.req.param('sessionId'), callerWorkspace(c)).addTask(body);\n if (!result) return refuse(c, 404, 'Session not found', 'session_not_found');\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'task edit');\n }\n });\n\n router.post('/:sessionId/review/approve', async (c) => {\n try {\n const session = pool.session(c.req.param('sessionId'), callerWorkspace(c));\n const plan = session.planState;\n if (!plan) throw new NoPlanError('review');\n const { message } = await runUserCommand(session, { command: 'approve_review' });\n return c.json({ plan: surfacePlan(plan), message } satisfies ApproveReviewResponse);\n } catch (err) {\n return failure(c, err, 'review approve');\n }\n });\n\n // Conversational planning (ADR-0002): start the planner dialogue. The\n // response's plan carries conversationHistory; when tasks are non-empty the\n // planner committed the plan.\n router.post('/:sessionId/converse/start', async (c) => {\n try {\n const { goal, runners, workspace, model, allowInit } = await jsonObject<{\n goal?: string; runners?: string[]; workspace?: string; model?: string; allowInit?: boolean;\n }>(c);\n if (!goal) return c.json({ error: 'goal is required' }, 400);\n const ws = workspace || c.req.query('workspace') || process.cwd();\n // As in generate: none requested is read by the session, after its gate.\n const runnerList: string[] | undefined = Array.isArray(runners) ? runners : (runners ? [runners] : undefined);\n const plan = await pool.startPlanning(c.req.param('sessionId'), goal, runnerList, ws, model, { allowInit });\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'converse start', { message: 'Planning failed' });\n }\n });\n\n // One branch for every user reply — clarifying answers, outline confirm.\n // The planner decides what happens next.\n router.post('/:sessionId/converse/message', async (c) => {\n try {\n const { message } = await jsonObject<{ message?: string }>(c);\n if (!message) return c.json({ error: 'message is required' }, 400);\n const plan = await pool.continuePlanning(c.req.param('sessionId'), message, callerWorkspace(c));\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'conversation message');\n }\n });\n\n // Send now (ADR-0023): stops the planner turn in flight — never the run's\n // tasks — and answers this message in the turn that replaces it, ahead of\n // anything waiting. With no turn in flight it is the plain send above.\n router.post('/:sessionId/converse/message/now', async (c) => {\n try {\n const { message } = await jsonObject<{ message?: string }>(c);\n if (!message) return c.json({ error: 'message is required' }, 400);\n const plan = await pool.forceSendPrompt(c.req.param('sessionId'), message, callerWorkspace(c));\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'conversation message');\n }\n });\n\n // What waits on the planner's usage limit then goes with the user's next\n // message instead of at the reset; `cancelled` is false when nothing waited.\n router.post('/:sessionId/converse/resend/cancel', (c) => {\n try {\n const cancelled = pool.session(c.req.param('sessionId'), callerWorkspace(c)).cancelPlannerResend();\n return c.json({ cancelled } satisfies CancelResumeResponse);\n } catch (err) {\n return failure(c, err, 'cancel resend', { fallback: 404, message: 'Not found' });\n }\n });\n\n // Fork and rewind act on the conversation, never on the plan: the task list\n // rides along as-is (ADR-0002, update of 2026-09-25). A rewind is a fork from\n // just before a user message; the original session is left as it was.\n router.post('/:sessionId/conversation/fork', (c) => {\n try {\n const fork = pool.forkConversation(c.req.param('sessionId'), callerWorkspace(c));\n return c.json({ ...fork, plan: surfacePlan(fork.plan) } satisfies ConversationForkResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n router.get('/:sessionId/conversation/rewind-targets', (c) => {\n try {\n return c.json({ targets: pool.session(c.req.param('sessionId'), callerWorkspace(c)).rewindTargets() } satisfies RewindTargetsResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n router.post('/:sessionId/conversation/rewind', async (c) => {\n try {\n const { index } = await jsonObject<{ index?: number }>(c);\n if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) return c.json({ error: 'index must be a non-negative integer' }, 400);\n const rewound = pool.rewindConversation(c.req.param('sessionId'), index, callerWorkspace(c));\n return c.json({ ...rewound, plan: surfacePlan(rewound.plan) } satisfies ConversationRewindResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n // The summary is one planner call, so this can take as long as a reply and\n // fail like one — a failure leaves the conversation exactly as it was.\n router.post('/:sessionId/conversation/compact', async (c) => {\n try {\n const compacted = await pool.compactConversation(c.req.param('sessionId'), callerWorkspace(c));\n return c.json({ ...compacted, plan: surfacePlan(compacted.plan) } satisfies ConversationCompactResponse);\n } catch (err) {\n return failure(c, err, 'conversation edit');\n }\n });\n\n // Retry compaction of a planner paused on its context (ADR-0002): the\n // paused turn opens again on the inputs it kept, and this answers once it\n // has landed — or paused again, which the plan's pause says. A stop of the\n // planner ends it, as it ends any turn.\n router.post('/:sessionId/conversation/compact/retry', async (c) => {\n try {\n const plan = await pool.retryPlannerCompaction(c.req.param('sessionId'), callerWorkspace(c));\n return c.json({ plan: surfacePlan(plan) } satisfies PlanResponse);\n } catch (err) {\n return failure(c, err, 'retry compaction');\n }\n });\n\n router.get('/:sessionId/prd', (c) => {\n try {\n const plan = pool.live(c.req.param('sessionId'), callerWorkspace(c))?.planState;\n if (!plan?.prdMarkdown) return refuse(c, 404, 'No PRD found');\n return c.json({ prdMarkdown: plan.prdMarkdown } satisfies PrdResponse);\n } catch (err) {\n return failure(c, err, 'prd');\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { installedPlannerDetected, type OkResponse, type RunnersResponse } from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\n\nexport function runnersRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', async (c) => {\n // getInstalledRunners re-probes the host first, so the state read after it\n // reflects the fresh answer rather than the stale default. A workspace's\n // own `.envrc` can choose the account, so the probe and the planner's\n // model are judged for the one that will plan rather than the daemon's cwd.\n try {\n const workspace = c.req.query('workspace');\n const runners = await pool.getInstalledRunners(workspace);\n await pool.discoverPlannerCatalogs(undefined, workspace);\n const state = pool.getRunnerState(workspace);\n return c.json({\n runners,\n orchestratorModel: state.orchestratorModel,\n } satisfies RunnersResponse);\n } catch (err) {\n return failure(c, err, 'list runners');\n }\n });\n\n router.put('/:id', async (c) => {\n try {\n // A toggle saves the enabled set it changes; built on the stale default,\n // it would save claude-code over the installed agents the probe finds.\n await installedPlannerDetected();\n const id = c.req.param('id');\n const { enabled } = await jsonObject<{ enabled?: unknown }>(c);\n // A missing value is not `false`: before this, `{}` disabled the runner\n // while answering 200.\n if (typeof enabled !== 'boolean') return refuse(c, 400, 'enabled must be true or false');\n pool.setRunnerEnabled(id, enabled);\n return c.json({ ok: true } satisfies OkResponse);\n } catch (err) {\n return failure(c, err, 'runner toggle', { fallback: 400 });\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport type { ModelsResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure } from './errors';\n\nexport function modelsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n router.get('/', async (c) => {\n // The catalog of the workspace's own runner environment, as its login verdict is.\n try {\n const result: ModelsResponse = await pool.getProviderModels(c.req.query('workspace'));\n return c.json(result);\n } catch (err) {\n return failure(c, err, 'list models');\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { assertWorkspaceExists, type IsolationPreviewResponse, type WorkspacesResponse } from '@ordewell/core';\nimport { OrchestratorPool, scanWorkspaces } from '../pool/orchestratorPool';\nimport { failure } from './errors';\n\nexport function workspacesRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n // A read-only sibling of the list: it names the repositories behind one\n // workspace, while `/` keeps listing the workspaces sessions are saved under.\n router.get('/isolation-preview', async (c) => {\n try {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n const preview = await pool.previewIsolation(workspace);\n return c.json({ preview } satisfies IsolationPreviewResponse);\n } catch (err) {\n return failure(c, err, 'read isolation preview', { message: 'Could not read the repositories' });\n }\n });\n\n router.get('/', (c) => {\n try {\n const workspaces = scanWorkspaces();\n return c.json({ workspaces } satisfies WorkspacesResponse);\n } catch (err) {\n return failure(c, err, 'list workspaces');\n }\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { isGranted, toApprovalDecision, type ApprovalAnswer, type ApprovalAnswerResponse, type ApprovalsResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, refuse } from './errors';\nimport { callerWorkspace, sameWorkspace } from './liveSession';\n\n/**\n * A body's answer. `{ decision, note? }` carries a runner request's whole\n * answer (ADR-0018, A1); `{ granted }` is the planner prompt's yes/no.\n * Anything else — absent, malformed, an unknown decision — is a denial,\n * never consent.\n */\nfunction answerOf(body: unknown): ApprovalAnswer {\n if (typeof body !== 'object' || body === null) return false;\n const { decision, note, granted } = body as { decision?: unknown; note?: unknown; granted?: unknown };\n if (decision === undefined) return granted === true;\n if (decision === 'allow' || decision === 'allowForTask') return { decision };\n if (decision === 'deny' && typeof note === 'string' && note.trim()) return { decision, note: note.trim() };\n return { decision: 'deny' };\n}\n\n/**\n * The answer channel for approval prompts — the planner's, and a task\n * runner's tool requests.\n *\n * Requests go out over the session WebSocket (they are ordinary\n * SessionMessages), but answers come back here rather than over the socket:\n * the CLI and TUI already speak HTTP to this server, a prompt can outlive the\n * socket that announced it, and a plain POST is answerable from any surface —\n * including `curl` in a pinch.\n */\nexport function approvalsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n router.use('/:sessionId', sameWorkspace(pool, 'sessionId'));\n router.use('/:sessionId/*', sameWorkspace(pool, 'sessionId'));\n\n router.get('/:sessionId', (c) => {\n const sessionId = c.req.param('sessionId');\n try {\n const session = pool.session(sessionId, callerWorkspace(c));\n return c.json({ pending: session.outstandingApprovals(), approvedScopes: session.approvedScopes() } satisfies ApprovalsResponse);\n } catch (err) {\n return failure(c, err, 'read approvals');\n }\n });\n\n router.post('/:sessionId/:approvalId', async (c) => {\n const sessionId = c.req.param('sessionId');\n const approvalId = c.req.param('approvalId');\n if (!pool.hasSession(sessionId)) return refuse(c, 404, `Unknown session: ${sessionId}`, 'session_not_found');\n\n const answer = answerOf(await c.req.json().catch(() => null));\n const decided = toApprovalDecision(answer);\n try {\n // Found after the body: while it arrived, the id may have come to name\n // another workspace's session, whose prompt this caller never saw.\n const session = pool.session(sessionId, callerWorkspace(c));\n // A runner request goes through the command seam as the user's answer, so\n // their action is kept in the timeline (ADR-0029). The planner's own\n // prompt is no execution action and is answered directly.\n const request = session.outstandingApprovals().find((pending) => pending.id === approvalId)?.request;\n if (request?.taskId) {\n const outcome = await session.execute(\n { command: 'answer_approval', task: request.taskId, approval: approvalId, answer: decided.decision, ...(decided.decision === 'deny' && decided.note ? { note: decided.note } : {}) },\n { kind: 'user' },\n );\n if (!outcome.ok) return refuse(c, 400, outcome.message, 'refused');\n } else if (!session.resolveApproval(approvalId, answer)) {\n return refuse(c, 409, 'Approval is no longer outstanding: it timed out or was already answered.', 'approval_not_outstanding');\n }\n } catch (err) {\n return failure(c, err, 'answer approval');\n }\n return c.json({ ok: true, granted: isGranted(decided), decision: decided.decision } satisfies ApprovalAnswerResponse);\n });\n\n return router;\n}\n","import { Hono } from 'hono';\nimport { RunSettingsError, containersOffered, installedPlannerDetected, type ContainerChange, type ContainerChangeResponse, type ContainerStatus, type GlobalRunSettings, type SettingsResponse, type SettingsUpdateResponse } from '@ordewell/core';\nimport type { OrchestratorPool } from '../pool/orchestratorPool';\nimport { failure, jsonObject, refuse } from './errors';\n\n/** One change, so a surface cannot half-apply two; `changeContainers` judges what it holds. */\nfunction containerChange(body: Record<string, unknown>): ContainerChange | null {\n const change = Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'workspace'));\n if (Object.keys(change).length !== 1) return null;\n if (typeof change.on === 'boolean') return { on: change.on };\n if (typeof change.image === 'string') return { image: change.image };\n return 'login' in change ? { login: change.login } : null;\n}\n\nexport function settingsRoute(pool: OrchestratorPool) {\n const router = new Hono();\n\n // Not there at all in a build that does not offer containers (ADR-0059 L5):\n // the same answer as any other route it does not have.\n router.use('/containers', async (c, next) => {\n if (!containersOffered()) return refuse(c, 404, 'This build does not offer containers');\n return next();\n });\n\n router.get('/containers', async (c) => {\n try {\n const status: ContainerStatus = await pool.containerStatus(c.req.query('prove') === '1', c.req.query('workspace') || undefined);\n return c.json(status);\n } catch (err) {\n return failure(c, err, 'containers status');\n }\n });\n\n router.patch('/containers', async (c) => {\n try {\n const body = await jsonObject(c);\n const change = containerChange(body);\n if (!change) return refuse(c, 400, 'One of on, image or login is required');\n const { workspace } = body;\n const result: ContainerChangeResponse = await pool.changeContainers(change, typeof workspace === 'string' ? workspace || undefined : undefined);\n return c.json(result);\n } catch (err) {\n return failure(c, err, 'containers change', { fallback: 400 });\n }\n });\n\n // Both wait for the startup probe (ADR-0009): the TUI reads the planner from\n // here the moment it opens, and a /planner switch is judged against the\n // planner in effect, which the probe may be about to change.\n router.get('/', async (c) => {\n try {\n await installedPlannerDetected();\n // An open session answers with its own run settings; no id or an id it no\n // longer holds answers with the file's, which a new session starts from\n // (ADR-0030). The planner's model is judged against the runner catalog of\n // the session's workspace, else of the one the client is in, waited for\n // only where it decides that model (ADR-0040).\n const sessionId = c.req.query('sessionId') || undefined;\n const workspace = c.req.query('workspace') || undefined;\n await pool.discoverPlannerCatalogs(sessionId, workspace);\n const settings: SettingsResponse = pool.getSettings(sessionId, workspace);\n return c.json(settings);\n } catch (err) {\n return failure(c, err, 'read settings');\n }\n });\n\n router.patch('/', async (c) => {\n try {\n await installedPlannerDetected();\n const body = await jsonObject(c);\n // Every client names its workspace, which is not itself a change.\n if (Object.keys(body).every((key) => key === 'workspace')) {\n return refuse(c, 400, 'At least one setting field is required');\n }\n // Run settings (ADR-0030) are named fields under `run`, never environment\n // variables; `sessionId` is the session the change was made in, and\n // `workspace` the one the client is in, whose catalog a pick is judged by.\n const { run, sessionId: namedSession, workspace: namedWorkspace, ...rest } = body;\n if (namedSession !== undefined && typeof namedSession !== 'string') return refuse(c, 400, 'sessionId must be a string');\n if (namedWorkspace !== undefined && typeof namedWorkspace !== 'string') return refuse(c, 400, 'workspace must be a string');\n const sessionId = namedSession || undefined;\n const workspace = namedWorkspace || undefined;\n if (run !== undefined) {\n if (!run || typeof run !== 'object' || Array.isArray(run)) return refuse(c, 400, 'run must be an object of run settings');\n try {\n pool.updateRunSettings(run as Partial<GlobalRunSettings>, sessionId, workspace);\n } catch (err) {\n if (err instanceof RunSettingsError) return refuse(c, 400, err.message);\n throw err;\n }\n }\n // Only a planner switch waits for a catalog, the one it is judged\n // against, which no client has asked for yet when it switches (ADR-0040).\n const result: SettingsUpdateResponse = Object.keys(rest).length > 0\n ? await pool.writeSettings(rest, sessionId, workspace)\n : pool.getSettings(sessionId, workspace);\n return c.json(result);\n } catch (err) {\n return failure(c, err, 'settings update', { fallback: 400 });\n }\n });\n\n return router;\n}\n","import { Hono, type Context } from 'hono';\nimport {\n assertWorkspaceExists,\n WorkspaceReadError,\n type FileContentResponse,\n type FileFindResponse,\n type FileTreeResponse,\n type GitBranchesResponse,\n type GitCommitResponse,\n type GitDiffResponse,\n type GitLogResponse,\n type GitReposResponse,\n type GitStatusResponse,\n type ReadTarget,\n type TaskDiffResponse,\n type ViewScopeKind,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { failure } from './errors';\n\n/*\n * The user principal's reads of a workspace's files and git (ADR-0064): every\n * route is a GET, takes its workspace per request, and answers from the\n * reader alone. None touches the pool, so none takes or waits on a session's\n * lease (R4), and a session another host holds is read all the same.\n */\n\nconst SCOPES: readonly ViewScopeKind[] = ['checkout', 'integration', 'task'];\n\nfunction workspaceOf(c: Context): string {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n return workspace;\n}\n\nfunction targetOf(c: Context): ReadTarget {\n const scope = c.req.query('scope');\n if (scope !== undefined && !(SCOPES as readonly string[]).includes(scope)) {\n throw new WorkspaceReadError('refused', `Unknown scope \"${scope}\": name ${SCOPES.join(', ')}.`);\n }\n const target: ReadTarget = { workspace: workspaceOf(c) };\n const repo = c.req.query('repo');\n const sessionId = c.req.query('sessionId');\n const taskId = c.req.query('taskId');\n if (repo) target.repo = repo;\n if (scope) target.scope = scope as ViewScopeKind;\n if (sessionId) target.sessionId = sessionId;\n if (taskId) target.taskId = taskId;\n return target;\n}\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name);\n if (!value) throw new WorkspaceReadError('refused', `Name the ${name} to read.`);\n return value;\n}\n\nfunction flag(c: Context, name: string): boolean {\n const value = c.req.query(name);\n return value === '1' || value === 'true';\n}\n\nfunction count(c: Context, name: string): number | undefined {\n const value = c.req.query(name);\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isInteger(n) || n < 1) throw new WorkspaceReadError('refused', `\"${name}\" must be a positive whole number.`);\n return n;\n}\n\nfunction optional(c: Context, name: string): string | undefined {\n return c.req.query(name) || undefined;\n}\n\n/** A route body that answers what the reader read, or the classified refusal. */\nfunction read<T>(label: string, answer: (c: Context) => Promise<T>) {\n return async (c: Context) => {\n try {\n return c.json(await answer(c));\n } catch (err) {\n return failure(c, err, label, { message: 'Could not read the workspace' });\n }\n };\n}\n\n/** `/api/files`: a scope's tree, one file's content, and search by name or text. */\nexport function filesRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/tree', read('read tree', (c) => reader.tree(targetOf(c), c.req.query('dir') ?? '') satisfies Promise<FileTreeResponse>));\n router.get('/content', read('read file', async (c) => {\n const target = targetOf(c);\n return reader.content(target, required(c, 'path')) satisfies Promise<FileContentResponse>;\n }));\n router.get('/find', read('find files', async (c) => {\n const target = targetOf(c);\n return reader.find(target, { query: required(c, 'query'), text: flag(c, 'text'), limit: count(c, 'limit') }) satisfies Promise<FileFindResponse>;\n }));\n return router;\n}\n\n/** `/api/git`: the workspace's repositories, and per repository its status, diffs, history and branches. */\nexport function gitRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/repos', read('read repositories', (c) => reader.repos(workspaceOf(c)) satisfies Promise<GitReposResponse>));\n router.get('/status', read('read status', (c) => reader.status(targetOf(c)) satisfies Promise<GitStatusResponse>));\n router.get('/diff', read('read diff', async (c) => {\n const target = targetOf(c);\n const kind = c.req.query('kind');\n if (kind !== undefined && kind !== 'staged' && kind !== 'unstaged') throw new WorkspaceReadError('refused', `Unknown diff kind \"${kind}\": name staged or unstaged.`);\n return reader.diff(target, { kind, from: optional(c, 'from'), to: optional(c, 'to'), path: optional(c, 'path') }) satisfies Promise<GitDiffResponse>;\n }));\n router.get('/log', read('read log', async (c) => {\n const target = targetOf(c);\n return reader.log(target, { ref: optional(c, 'ref'), cursor: optional(c, 'cursor'), limit: count(c, 'limit') }) satisfies Promise<GitLogResponse>;\n }));\n router.get('/commit', read('read commit', async (c) => {\n const target = targetOf(c);\n return reader.commit(target, required(c, 'sha'), optional(c, 'path')) satisfies Promise<GitCommitResponse>;\n }));\n router.get('/branches', read('read branches', (c) => reader.branches(targetOf(c)) satisfies Promise<GitBranchesResponse>));\n return router;\n}\n\n/**\n * `GET /api/plans/:sessionId/tasks/:taskId/diff`: one task's diff from the\n * saved run, as `readTaskDiff` reads it for a verdict. Mounted beside\n * `plansRoute` rather than in it, since it reads the saved session and never\n * the pool's live one.\n */\nexport function taskDiffRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/:sessionId/tasks/:taskId/diff', read('read task diff', (c) => reader.taskDiff(workspaceOf(c), c.req.param('sessionId') ?? '', c.req.param('taskId') ?? '', {\n repo: optional(c, 'repo'), path: optional(c, 'path'), names: flag(c, 'names'),\n }) satisfies Promise<TaskDiffResponse>));\n return router;\n}\n","import { Hono, type Context } from 'hono';\nimport {\n assertWorkspaceExists,\n type GitActionResponse,\n type MergePreflightResponse,\n type UserGit,\n type UserGitScope,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { failure, InvalidBodyError, jsonObject } from './errors';\n\n/*\n * The user's git actions on their own checkout (ADR-0062). Each takes its\n * workspace and repository in the body and acts through the user's git. None\n * touches a session's lease: an action asks the pool only whether a run is\n * live and where its timeline is, so a session another host holds is no bar.\n */\n\ntype Body = Record<string, unknown>;\n\n/** The service trusts its types, so every body field is checked here: a wrong one is the request's fault, never a fault of git. */\nfunction bad(message: string): never {\n throw new InvalidBodyError(message);\n}\n\nfunction text(body: Body, name: string): string {\n const value = body[name];\n if (typeof value !== 'string') bad(`\"${name}\" must be a string.`);\n return value;\n}\n\nfunction optionalText(body: Body, name: string): string | undefined {\n return body[name] === undefined ? undefined : text(body, name);\n}\n\nfunction texts(body: Body, name: string): string[] | undefined {\n const value = body[name];\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || !value.every((v): v is string => typeof v === 'string')) bad(`\"${name}\" must be a list of strings.`);\n return value;\n}\n\nfunction yes(body: Body, name: string): boolean | undefined {\n const value = body[name];\n if (value === undefined) return undefined;\n if (typeof value !== 'boolean') bad(`\"${name}\" must be true or false.`);\n return value;\n}\n\n/** The `confirm` the surface echoes back: what it showed the person (G3). Absent reads as an empty one, so every field it lacks is stale. */\nfunction confirmOf(body: Body): Body {\n const value = body.confirm;\n if (value === undefined) return {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) bad('\"confirm\" must be an object.');\n return value as Body;\n}\n\nfunction scopeOf(body: Body): UserGitScope {\n const workspace = optionalText(body, 'workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n const repo = optionalText(body, 'repo');\n return repo ? { workspace, repo } : { workspace };\n}\n\nfunction changes(body: Body) {\n const paths = texts(body, 'paths');\n const hunks = optionalText(body, 'hunks');\n if ((paths === undefined) === (hunks === undefined)) bad('Name either \"paths\" or \"hunks\".');\n return hunks !== undefined ? { hunks } : { paths };\n}\n\n/** A route body that answers the repository's state after the action, or the classified refusal. */\nfunction act(label: string, action: (scope: UserGitScope, body: Body) => Promise<GitActionResponse>) {\n return async (c: Context) => {\n try {\n const body = await jsonObject(c);\n return c.json(await action(scopeOf(body), body) satisfies GitActionResponse);\n } catch (err) {\n return failure(c, err, label, { message: 'Could not act on the repository' });\n }\n };\n}\n\n/** `PUT /api/files/content`: a save of a file read at `baseHash` (G10). */\nexport function fileWriteRoute(git: UserGit) {\n const router = new Hono();\n router.put('/content', act('save file', (scope, body) => {\n const baseHash = body.baseHash === null ? null : text(body, 'baseHash');\n return git.save(scope, { path: text(body, 'path'), text: text(body, 'text'), baseHash });\n }));\n return router;\n}\n\n/** `POST /api/git/*`: the v1 action set, each on the user's checkout of one repository. */\nexport function gitWriteRoute(git: UserGit) {\n const router = new Hono();\n router.post('/stage', act('stage', (scope, body) => git.stage(scope, changes(body))));\n router.post('/unstage', act('unstage', (scope, body) => git.unstage(scope, changes(body))));\n router.post('/commit', act('commit', (scope, body) => {\n const amend = yes(body, 'amend');\n const head = confirmOf(body).head;\n return git.commit(scope, {\n message: text(body, 'message'),\n ...(amend !== undefined ? { amend } : {}),\n ...(typeof head === 'string' ? { confirm: { head } } : {}),\n });\n }));\n router.post('/discard', act('discard', (scope, body) => {\n const files = texts(confirmOf(body), 'files') ?? [];\n return git.discard(scope, { ...changes(body), confirm: { files } });\n }));\n router.post('/branch', act('create branch', (scope, body) => {\n const from = optionalText(body, 'from');\n const switching = yes(body, 'switch');\n return git.createBranch(scope, { name: text(body, 'name'), ...(from !== undefined ? { from } : {}), ...(switching !== undefined ? { switch: switching } : {}) });\n }));\n router.post('/switch', act('switch branch', (scope, body) => git.switchBranch(scope, { branch: text(body, 'branch') })));\n router.post('/branch-delete', act('delete branch', (scope, body) => {\n const confirm = confirmOf(body);\n const shown = typeof confirm.branch === 'string' ? confirm.branch : '';\n if (typeof confirm.unmerged !== 'boolean') bad('\"confirm.unmerged\" must say whether the branch was shown as unmerged.');\n return git.deleteBranch(scope, { branch: text(body, 'branch'), confirm: { branch: shown, unmerged: confirm.unmerged } });\n }));\n router.post('/stash', act('stash', (scope, body) => {\n const paths = texts(body, 'paths');\n const message = optionalText(body, 'message');\n return git.stash(scope, { ...(paths !== undefined ? { paths } : {}), ...(message !== undefined ? { message } : {}) });\n }));\n router.post('/stash-pop', act('pop stash', (scope, body) => git.stashPop(scope, { stash: text(body, 'stash') })));\n router.post('/stash-drop', act('drop stash', (scope, body) => git.stashDrop(scope, { stash: text(body, 'stash') })));\n router.post('/fetch', act('fetch', (scope) => git.fetch(scope)));\n const remote = (body: Body) => {\n const confirm = confirmOf(body);\n return { remote: typeof confirm.remote === 'string' ? confirm.remote : '', branch: typeof confirm.branch === 'string' ? confirm.branch : '' };\n };\n router.post('/pull', act('pull', (scope, body) => git.pull(scope, { confirm: remote(body) })));\n router.post('/push', act('push', (scope, body) => git.push(scope, { confirm: remote(body) })));\n return router;\n}\n\n/**\n * `GET /api/plans/:sessionId/isolation/merge-preflight` (G8): per repository,\n * the user's uncommitted files Merge all would collide with. A read of the\n * saved run, so it needs neither the session open here nor its lease.\n */\nexport function mergePreflightRoute(reader: WorkspaceReader) {\n const router = new Hono();\n router.get('/:sessionId/isolation/merge-preflight', async (c) => {\n try {\n const workspace = c.req.query('workspace') || process.cwd();\n assertWorkspaceExists(workspace);\n return c.json(await reader.mergePreflight(workspace, c.req.param('sessionId') ?? '') satisfies MergePreflightResponse);\n } catch (err) {\n return failure(c, err, 'merge preflight', { message: 'Could not read the run' });\n }\n });\n return router;\n}\n","import { WebSocketServer, WebSocket } from 'ws';\nimport type { IncomingMessage } from 'http';\nimport type { Duplex } from 'stream';\nimport { DAEMON_SUBPROTOCOL, type RunSnapshotFrame, type SessionFrame } from '@ordewell/core';\nimport { OrchestratorPool } from '../pool/orchestratorPool';\n\nconst CHILD_PATH = /^\\/ws\\/session\\/([^/]+)\\/child\\/([^/]+)$/;\n\n/** One id from the path, as a client encodes it (`/`, `?` and `#` cannot travel raw); undefined for a malformed escape. */\nfunction idOf(segment: string): string | undefined {\n try {\n return decodeURIComponent(segment);\n } catch {\n return undefined;\n }\n}\n\n/** Nothing is sent before the tree has named the child, so a stray id learns only that it was refused. */\nfunction joinChild(pool: OrchestratorPool, ws: WebSocket, rootId: string, childId: string, workspace: string | undefined): void {\n const leave = () => pool.unwatchChild(rootId, childId, ws);\n ws.on('close', leave);\n ws.on('error', leave);\n const refuse = () => ws.close(4404, 'No such child plan in this tree');\n void pool.watchChild(rootId, childId, ws, workspace).then((watching) => { if (!watching) refuse(); }, refuse);\n}\n\nexport function createWsHandler(pool: OrchestratorPool) {\n const wss = new WebSocketServer({\n noServer: true,\n // Select the plain subprotocol explicitly. Left to itself `ws` echoes back\n // whichever was offered first, which would put the token in the 101\n // response; selecting nothing makes the client fail the handshake.\n handleProtocols: (protocols) => (protocols.has(DAEMON_SUBPROTOCOL) ? DAEMON_SUBPROTOCOL : false),\n });\n\n wss.on('connection', (ws: WebSocket, request: IncomingMessage) => {\n const url = new URL(request.url ?? '', `http://${request.headers.host}`);\n const malformed = () => ws.close(4400, 'Malformed id in the socket path');\n // A socket naming its workspace hears only that workspace's session: the\n // pool keeps one per id, so another project's copy of the id would hear\n // this one's run. Refused here while another holds the id, and by the pool\n // when another takes it later.\n const workspace = url.searchParams.get('workspace') || undefined;\n const elsewhere = (id: string) => {\n if (workspace === undefined) return false;\n try {\n pool.live(id, workspace);\n return false;\n } catch {\n ws.close(4409, 'Session open for another workspace');\n return true;\n }\n };\n const child = CHILD_PATH.exec(url.pathname);\n if (child) {\n const rootId = idOf(child[1]);\n const childId = idOf(child[2]);\n if (rootId === undefined || childId === undefined) return malformed();\n if (elsewhere(rootId)) return;\n joinChild(pool, ws, rootId, childId, workspace);\n return;\n }\n const sessionId = idOf(url.pathname.split('/').pop() || '');\n if (sessionId === undefined) return malformed();\n if (elsewhere(sessionId)) return;\n\n ws.on('close', () => {\n pool.unsubscribe(sessionId, ws);\n });\n\n ws.on('error', () => {\n pool.unsubscribe(sessionId, ws);\n });\n\n ws.send(JSON.stringify({ type: 'connected', sessionId }));\n // The stream reports changes only. Taken and subscribed in one turn, so no\n // broadcast can fall between the snapshot and the first message after it.\n const view = pool.runSnapshot(sessionId);\n if (view) {\n ws.send(JSON.stringify({\n type: 'run_snapshot', sessionId, view, approvals: pool.announcedApprovals(sessionId), ...pool.streamPosition(sessionId),\n } satisfies RunSnapshotFrame));\n }\n // A compaction has no turn id to adopt, so a client joining mid-way would\n // not know the planner is busy. Unstamped: the client's fold is idempotent\n // by the compaction's id, and a stamp would let it count this as the\n // broadcast it already holds.\n const compaction = pool.plannerCompaction(sessionId);\n if (compaction) ws.send(JSON.stringify(compaction satisfies SessionFrame));\n // Nor has a turn at the planner gate, which no planner has heard of yet.\n const detection = pool.plannerDetection(sessionId);\n if (detection?.waiting) ws.send(JSON.stringify(detection satisfies SessionFrame));\n // Subscribing also greets with host-owned account limits, independently\n // of the run snapshot above, even when the host knows none yet.\n pool.subscribe(sessionId, ws, workspace);\n });\n\n return (request: IncomingMessage, socket: Duplex, head: Buffer) => {\n wss.handleUpgrade(request, socket, head, (ws) => {\n wss.emit('connection', ws, request);\n });\n };\n}\n","/**\n * The single admission decision for the daemon.\n *\n * Both the HTTP middleware and the WebSocket upgrade handler call this. The\n * sharing is the point: the two paths drifting apart is how the upgrade ended\n * up validating nothing while the HTTP routes had a CORS allowlist.\n */\n\nimport { extractPresentedToken, tokensMatch } from '@ordewell/core';\n\n/** `localhost` is included because clients dial it by name; the daemon binds loopback only. */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nexport interface AdmissionHeaders {\n /** `null`/`undefined` mean absent. An empty string still counts as present. */\n origin?: string | null;\n host?: string | null;\n /** `Authorization: Bearer <token>` — how the token travels on HTTP routes. */\n authorization?: string | null;\n /** `Sec-WebSocket-Protocol` — how it travels on the upgrade, so it stays out of logs. */\n secWebSocketProtocol?: string | null;\n}\n\n/** What this daemon is: which port it bound, and which token it minted. */\nexport interface AdmissionContext {\n port: number;\n token: string;\n /** Named in a token rejection, so a stale token is diagnosable rather than a bare failure. */\n tokenFile: string;\n}\n\nexport type AdmissionDecision =\n | { admit: true }\n | { admit: false; status: number; reason: string };\n\nconst ADMIT: AdmissionDecision = { admit: true };\n\nexport function decideAdmission(\n headers: AdmissionHeaders,\n context: AdmissionContext,\n): AdmissionDecision {\n if (headers.origin !== undefined && headers.origin !== null) {\n return {\n admit: false,\n status: 403,\n reason: 'Refused: requests carrying an Origin header are not accepted. The Ordewell daemon has no browser client.',\n };\n }\n\n if (!isOwnLoopbackAuthority(headers.host, context.port)) {\n return {\n admit: false,\n status: 403,\n reason: `Refused: the Host header must name loopback (localhost, 127.0.0.1 or [::1]) at port ${context.port}.`,\n };\n }\n\n if (!tokensMatch(extractPresentedToken(headers), context.token)) {\n return {\n admit: false,\n status: 401,\n reason:\n 'Unauthenticated: this request did not present the daemon\\'s bearer token. '\n + `Ordewell clients read it from ${context.tokenFile}; if that file is stale, `\n + 'restart the daemon (`ordewell web --daemon`) to mint a fresh one.',\n };\n }\n\n return ADMIT;\n}\n\n/**\n * Rejecting anything but our own loopback authority is what closes DNS\n * rebinding: a page rebinding a hostname it controls to 127.0.0.1 still sends\n * that hostname in `Host`, and same-origin requests to it carry no `Origin`.\n */\nfunction isOwnLoopbackAuthority(host: string | null | undefined, port: number): boolean {\n if (!host) return false;\n const authority = splitAuthority(host);\n if (!authority) return false;\n if (!LOOPBACK_HOSTNAMES.has(authority.hostname.toLowerCase())) return false;\n return authority.port === port;\n}\n\n/** Absent port means the scheme default; the daemon only ever speaks http. */\nconst DEFAULT_HTTP_PORT = 80;\n\nfunction splitAuthority(host: string): { hostname: string; port: number } | undefined {\n const value = host.trim();\n if (value === '') return undefined;\n\n if (value.startsWith('[')) {\n const close = value.indexOf(']');\n if (close === -1) return undefined;\n const hostname = value.slice(1, close);\n const rest = value.slice(close + 1);\n if (rest === '') return { hostname, port: DEFAULT_HTTP_PORT };\n if (!rest.startsWith(':')) return undefined;\n return withPort(hostname, rest.slice(1));\n }\n\n const colon = value.indexOf(':');\n if (colon === -1) return { hostname: value, port: DEFAULT_HTTP_PORT };\n // An unbracketed second colon is a bare IPv6 literal, which is malformed in a\n // Host header — refuse rather than guess where the port starts.\n if (value.indexOf(':', colon + 1) !== -1) return undefined;\n return withPort(value.slice(0, colon), value.slice(colon + 1));\n}\n\nfunction withPort(hostname: string, port: string): { hostname: string; port: number } | undefined {\n if (!/^\\d+$/.test(port)) return undefined;\n return { hostname, port: Number(port) };\n}\n","import { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { seaVersion, type SeaDeps } from '@ordewell/core';\n\nlet cached: string | undefined;\n\n/**\n * This daemon's `@ordewell/web` version, for `GET /api/server` (ADR-0063 H3).\n * Found by walking up to the package's own manifest rather than a fixed\n * `..`: the tsup bundle runs from `dist/server/` and the tests from\n * `server/utils/`, and a fixed hop count breaks on whichever moves next.\n * Inside the standalone binary there is no manifest to walk to, and the daemon\n * is the binary itself, so its version is the one the build embedded\n * (ADR-0065 C2, C3).\n */\nexport function serverVersion(from: string = __dirname, sea: SeaDeps = {}): string {\n const embedded = embeddedVersion(sea);\n if (embedded) return embedded;\n if (cached !== undefined) return cached;\n cached = findVersion(from);\n return cached;\n}\n\nfunction embeddedVersion(sea: SeaDeps): string | undefined {\n try {\n return seaVersion(sea);\n } catch {\n // A binary whose manifest cannot be read still answers the API.\n return 'unknown';\n }\n}\n\nfunction findVersion(from: string): string {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n const pkg: unknown = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));\n const { name, version } = pkg as { name?: unknown; version?: unknown };\n if (name === '@ordewell/web' && typeof version === 'string' && version) return version;\n } catch {\n // No manifest here, or not one we can read: keep walking.\n }\n if (dirname(dir) === dir) return 'unknown';\n }\n}\n","import { Hono } from 'hono';\nimport type { Server } from 'http';\nimport type { Duplex } from 'stream';\nimport { childrenRoute } from './routes/children';\nimport { sessionsRoute } from './routes/sessions';\nimport { plansRoute } from './routes/plans';\nimport { runnersRoute } from './routes/runners';\nimport { modelsRoute } from './routes/models';\nimport { workspacesRoute } from './routes/workspaces';\nimport { approvalsRoute } from './routes/approvals';\nimport { settingsRoute } from './routes/settings';\nimport { filesRoute, gitRoute, taskDiffRoute } from './routes/workspaceRead';\nimport { fileWriteRoute, gitWriteRoute, mergePreflightRoute } from './routes/workspaceWrite';\nimport { WebConfig } from './adapters/WebConfig';\nimport { createWsHandler } from './ws/stream';\nimport {\n decideAdmission,\n type AdmissionContext,\n type AdmissionDecision,\n} from './security/admission';\nimport { OrchestratorPool } from './pool/orchestratorPool';\nimport {\n DAEMON_CONTRACT,\n createUserGit,\n createWorkspaceReader,\n landingRuns,\n type ServerInfoResponse,\n type UserGit,\n type WorkspaceReader,\n} from '@ordewell/core';\nimport { serverVersion } from './utils/serverVersion';\n\n/**\n * The user's git actions (ADR-0062). The pool answers only whether a run is\n * live and where its timeline is: an action never takes a session's lease.\n */\nexport function userGitFor(pool: OrchestratorPool, reader: WorkspaceReader): UserGit {\n return createUserGit({\n reader,\n landingRuns: (checkout) => landingRuns(checkout, (workspace, sessionId, plan) => pool.userRunIsLive(sessionId, workspace, plan)),\n record: (workspace, held, text) => pool.recordUserAction(held.sessionId, workspace, text),\n });\n}\n\nexport function createApp(\n pool: OrchestratorPool,\n admission: AdmissionContext,\n reader: WorkspaceReader = createWorkspaceReader({ config: new WebConfig() }),\n userGit: UserGit = userGitFor(pool, reader),\n) {\n const app = new Hono();\n\n // There is no CORS allowlist: the daemon ships no browser front end, so a\n // browser has no legitimate reason to reach it at all. The bearer token\n // supersedes it, and covers every local caller rather than only browsers.\n app.use('*', async (c, next) => {\n const decision = decideAdmission({\n origin: c.req.header('origin') ?? null,\n // The request URL's authority is built from the Host header upstream, so\n // it is the same value; the fallback only matters when the header is\n // absent entirely, which fails the check anyway.\n host: c.req.header('host') ?? new URL(c.req.url).host,\n authorization: c.req.header('authorization') ?? null,\n }, admission);\n if (!decision.admit) return c.json({ error: decision.reason }, decision.status as 401 | 403);\n await next();\n });\n\n // `ordewell stop --server` verifies a PID file against the process that\n // actually owns the port before signalling anything, so a stale file cannot\n // terminate an unrelated process. The desktop app reads the version and the\n // contract before it drives a daemon it did not start (ADR-0063 H3), and a\n // newer CLI whether it may replace one it cannot drive (ADR-0048). Behind\n // admission like every other route.\n app.get('/api/server', (c) => c.json({\n pid: process.pid,\n port: admission.port,\n version: serverVersion(),\n contract: DAEMON_CONTRACT,\n live: pool.workLive(),\n } satisfies ServerInfoResponse));\n\n app.route('/api/sessions', sessionsRoute(pool));\n app.route('/api/sessions', childrenRoute(pool));\n // A run's reads come first: they read the named workspace's saved run, never\n // the pool (ADR-0064 R2), and Hono runs handlers in the order they were\n // mounted, so the plans router's live-session guard never reaches them.\n app.route('/api/plans', taskDiffRoute(reader));\n app.route('/api/plans', mergePreflightRoute(reader));\n app.route('/api/plans', plansRoute(pool));\n app.route('/api/runners', runnersRoute(pool));\n app.route('/api/models', modelsRoute(pool));\n app.route('/api/settings', settingsRoute(pool));\n app.route('/api/workspaces', workspacesRoute(pool));\n app.route('/api/approvals', approvalsRoute(pool));\n // The user's reads of files and git (ADR-0064): the reader, never the pool.\n app.route('/api/files', filesRoute(reader));\n app.route('/api/git', gitRoute(reader));\n // The user's actions on their own checkout (ADR-0062), beside those reads.\n app.route('/api/files', fileWriteRoute(userGit));\n app.route('/api/git', gitWriteRoute(userGit));\n\n return app;\n}\n\nexport function attachWsHandler(server: Server, pool: OrchestratorPool, admission: AdmissionContext) {\n const handler = createWsHandler(pool);\n server.on('upgrade', (request, socket, head) => {\n const decision = decideAdmission({\n origin: request.headers.origin ?? null,\n host: request.headers.host ?? null,\n authorization: request.headers.authorization ?? null,\n secWebSocketProtocol: request.headers['sec-websocket-protocol'] ?? null,\n }, admission);\n if (!decision.admit) {\n refuseUpgrade(socket, decision);\n return;\n }\n\n const url = new URL(request.url ?? '', `http://${request.headers.host}`);\n if (url.pathname.startsWith('/ws/session/')) {\n handler(request, socket, head);\n } else {\n socket.destroy();\n }\n });\n}\n\nconst REASON_PHRASE: Record<number, string> = { 401: 'Unauthorized', 403: 'Forbidden' };\n\nfunction refuseUpgrade(socket: Duplex, decision: Extract<AdmissionDecision, { admit: false }>): void {\n const body = JSON.stringify({ error: decision.reason });\n socket.end(\n `HTTP/1.1 ${decision.status} ${REASON_PHRASE[decision.status] ?? 'Forbidden'}\\r\\n` +\n 'Connection: close\\r\\n' +\n 'Content-Type: application/json\\r\\n' +\n `Content-Length: ${Buffer.byteLength(body)}\\r\\n` +\n `\\r\\n${body}`,\n );\n socket.destroy();\n}\n","import type { IncomingMessage, ServerResponse } from 'http';\nimport type { Hono } from 'hono';\nimport { decideAdmission, type AdmissionContext } from './security/admission';\n\n/**\n * How much of a request body the daemon will hold in memory. Plans, task edits\n * and conversation messages are small; a body past this is not one of ours.\n * Without a cap, the admission check below could never run before a browser's\n * multi-gigabyte `text/plain` POST was already buffered.\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024;\n\nclass BodyTooLargeError extends Error {}\n\n/** A body over the cap, or a request the admission check refused, answered and closed. */\nfunction refuse(req: IncomingMessage, res: ServerResponse, status: number, message: string): void {\n const payload = JSON.stringify({ error: message });\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(payload),\n // Nothing more is read from this request, so its connection cannot be reused.\n Connection: 'close',\n });\n res.end(payload, () => req.destroy());\n}\n\n/**\n * Read at most `max` bytes, leaving the stream paused once it is over. The\n * caller answers 413 and destroys the request; draining it instead would let a\n * browser keep the daemon busy for as long as it liked.\n */\nfunction readBody(req: IncomingMessage, max: number): Promise<string | undefined> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const cleanup = () => {\n req.off('data', onData);\n req.off('end', onEnd);\n req.off('error', onError);\n };\n const onData = (chunk: Buffer) => {\n size += chunk.length;\n if (size > max) {\n cleanup();\n req.pause();\n reject(new BodyTooLargeError());\n return;\n }\n chunks.push(chunk);\n };\n const onEnd = () => {\n cleanup();\n resolve(chunks.length > 0 ? Buffer.concat(chunks).toString() : undefined);\n };\n const onError = (err: Error) => {\n cleanup();\n reject(err);\n };\n req.on('data', onData);\n req.on('end', onEnd);\n req.on('error', onError);\n });\n}\n\n/**\n * Bridges node's http server onto the Hono app. Kept out of `main.ts` so the\n * real request path — including the Host header the admission check reads — is\n * testable against a listening server.\n *\n * Admission runs here as well as in the Hono middleware, and first: the\n * middleware only sees the request after the body has been read, which is too\n * late to keep a browser from making the daemon buffer it.\n */\nexport function createRequestListener(app: Hono, admission: AdmissionContext, maxBodyBytes = MAX_BODY_BYTES) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const decision = decideAdmission({\n origin: req.headers.origin ?? null,\n host: req.headers.host ?? null,\n authorization: req.headers.authorization ?? null,\n }, admission);\n if (!decision.admit) {\n refuse(req, res, decision.status, decision.reason);\n return;\n }\n\n const declared = Number(req.headers['content-length']);\n if (Number.isFinite(declared) && declared > maxBodyBytes) {\n refuse(req, res, 413, `Request body must be at most ${maxBodyBytes} bytes.`);\n return;\n }\n\n let body: string | undefined;\n try {\n body = await readBody(req, maxBodyBytes);\n } catch (err) {\n if (err instanceof BodyTooLargeError) {\n refuse(req, res, 413, `Request body must be at most ${maxBodyBytes} bytes.`);\n return;\n }\n throw err;\n }\n\n const url = `http://${req.headers.host || 'localhost'}${req.url}`;\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (v) {\n if (Array.isArray(v)) v.forEach(vv => headers.append(k, vv));\n else headers.set(k, v as string);\n }\n }\n if (body && !headers.has('content-type')) headers.set('content-type', 'application/json');\n\n const webReq = new Request(url, {\n method: req.method || 'GET',\n headers,\n body: req.method !== 'GET' && req.method !== 'HEAD' ? body : undefined,\n });\n\n try {\n const webRes = await app.fetch(webReq);\n res.writeHead(webRes.status, Object.fromEntries(webRes.headers.entries()));\n if (webRes.body) {\n const reader = webRes.body.getReader();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n }\n res.end();\n } catch (err) {\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: err instanceof Error ? (err as Error).message : 'Internal server error' }));\n }\n }\n };\n}\n","import { createApp, attachWsHandler } from './app';\nimport { createRequestListener } from './nodeAdapter';\nimport { OrchestratorPool } from './pool/orchestratorPool';\nimport { createServer } from 'http';\nimport { mkdirSync, unlinkSync, writeFileSync } from 'fs';\nimport { dirname } from 'path';\nimport { clearDaemonToken, mintDaemonToken, processLeaseHost, StructuredRunner, type LeaseHostKind } from '@ordewell/core';\n\n/**\n * What another host's refusal names this one as, and the surface its planner\n * is told its user has (ADR-0049). Only a TUI starts a daemon it watches, as\n * its private one; the desktop app marks the one it forks.\n */\nexport function daemonHostKind(args: readonly string[], port: number): LeaseHostKind {\n const watchParentIdx = args.indexOf('--watch-parent');\n const ownerPid = watchParentIdx !== -1 ? parseInt(args[watchParentIdx + 1], 10) : undefined;\n return {\n kind: 'daemon',\n port,\n ...(ownerPid ? { ownerPid } : {}),\n ...(args.includes('--desktop-app') ? { app: 'desktop' as const } : {}),\n };\n}\n\n/**\n * The daemon: the API server the CLI, the TUI and the desktop app drive over\n * 127.0.0.1. `main.ts` runs it with its own argv; the standalone CLI binary\n * runs it in-process as `ordewell __daemon ...`, having no server file to\n * spawn (ADR-0065). It owns the process from here on: its signal handlers end it.\n */\nexport function runDaemon(args: string[]): void {\n let port = 3742;\n\n const portIdx = args.indexOf('--port');\n if (portIdx !== -1 && args[portIdx + 1]) {\n port = parseInt(args[portIdx + 1], 10) || 3742;\n }\n\n // Set only for a daemon owned by one CLI invocation (e.g. `ordewell tui`),\n // which spawns it non-detached expecting it to die with the caller. A\n // closed terminal delivers SIGHUP to both via the shared process group, but\n // that misses a caller killed by PID directly or a multiplexer that doesn't\n // relay the signal — this poll is the fallback so an owned daemon never\n // outlives its CLI and orphans don't accumulate.\n const watchParentIdx = args.indexOf('--watch-parent');\n const watchParentPid = watchParentIdx !== -1 ? parseInt(args[watchParentIdx + 1], 10) : undefined;\n\n // Written by the daemon itself only once it is listening, and removed on\n // shutdown, so `ordewell stop --server` never reads an entry belonging to a\n // process that failed to bind or a daemon that is already gone.\n const pidFileIdx = args.indexOf('--pid-file');\n const pidFile = pidFileIdx !== -1 ? args[pidFileIdx + 1] : undefined;\n let ownsPidFile = false;\n\n processLeaseHost().describe(daemonHostKind(args, port));\n\n // Tasks run on the structured transport (ADR-0018) as plain child processes,\n // so one runner serves every plan whatever the host has.\n const pool = new OrchestratorPool({ runner: new StructuredRunner() });\n // Before listening, so the first request already finds the probe in flight\n // and waits on it rather than reading the openrouter fallback (ADR-0009).\n void pool.detectInstalledPlanner();\n const server = createServer();\n let ownsToken = false;\n\n server.listen(port, '127.0.0.1', () => {\n // A losing startup must not replace the listening daemon's credential.\n // This callback installs admission before the event loop can serve a request.\n const { token, file: tokenFile } = mintDaemonToken(port);\n ownsToken = true;\n if (pidFile) {\n mkdirSync(dirname(pidFile), { recursive: true });\n writeFileSync(pidFile, String(process.pid), { mode: 0o600 });\n ownsPidFile = true;\n }\n const admission = { port, token, tokenFile };\n const app = createApp(pool, admission);\n app.get('/', (c) => c.json({ message: 'Ordewell API', docs: '/api/workspaces' }));\n server.on('request', createRequestListener(app, admission));\n attachWsHandler(server, pool, admission);\n pool.getProviderModels().catch((err) => {\n console.error(`[web] model discovery warmup failed: ${err?.message ?? err}`);\n });\n console.error(`[web] Ordewell API server: http://localhost:${port}`);\n });\n\n function shutdown(): void {\n if (ownsToken) clearDaemonToken(port);\n if (ownsPidFile && pidFile) {\n try { unlinkSync(pidFile); } catch { /* already gone */ }\n }\n pool.destroyAll();\n server.close();\n process.exit(0);\n }\n\n // A stray rejection in one session's background work must not take every\n // session's runners down with the daemon.\n process.on('unhandledRejection', (reason) => {\n console.error(`[web] unhandled rejection: ${reason instanceof Error ? reason.stack ?? reason.message : String(reason)}`);\n });\n\n // A daemon this CLI owns shares its foreground process group. Ctrl-C while a\n // login child holds the terminal is a SIGINT to that whole group, and the TUI\n // ignores it so the child alone is cancelled; shutting down here would take\n // every in-memory session with it. The owner stops us with SIGTERM, and the\n // parent watch below still catches an owner that dies.\n process.on('SIGINT', () => { if (!watchParentPid) shutdown(); });\n process.on('SIGTERM', () => { shutdown(); });\n process.on('SIGHUP', () => { shutdown(); });\n\n if (watchParentPid) {\n const parentCheck = setInterval(() => {\n try {\n process.kill(watchParentPid, 0);\n } catch {\n clearInterval(parentCheck);\n shutdown();\n }\n }, 5000);\n }\n}\n","#!/usr/bin/env node\nimport { runDaemon } from './daemon';\n\nrunDaemon(process.argv.slice(2));\n"]}