@ordewell/core 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/{ModeResolver-BmG9O08A.d.ts → ModeResolver-CXGnEhbN.d.ts} +1 -1
  2. package/dist/{ModeResolver-CNKcOksr.d.mts → ModeResolver-DqpwKbfJ.d.mts} +1 -1
  3. package/dist/{Task-CH1z4L3h.d.mts → Task-TFPWtKoz.d.mts} +2 -0
  4. package/dist/{Task-CH1z4L3h.d.ts → Task-TFPWtKoz.d.ts} +2 -0
  5. package/dist/{chunk-7ACNW5CD.mjs → chunk-4OARA73Z.mjs} +2 -2
  6. package/dist/{chunk-3P5UIXTR.mjs → chunk-5ETS2NIB.mjs} +13 -3
  7. package/dist/{chunk-3P5UIXTR.mjs.map → chunk-5ETS2NIB.mjs.map} +1 -1
  8. package/dist/{chunk-I436RXQT.mjs → chunk-62MSJNOG.mjs} +3 -3
  9. package/dist/{chunk-I436RXQT.mjs.map → chunk-62MSJNOG.mjs.map} +1 -1
  10. package/dist/{chunk-MGMQKUIJ.mjs → chunk-DFRDXOEG.mjs} +15 -5
  11. package/dist/chunk-DFRDXOEG.mjs.map +1 -0
  12. package/dist/{chunk-O52PN7P2.mjs → chunk-FOGPFLRO.mjs} +4 -4
  13. package/dist/chunk-FOGPFLRO.mjs.map +1 -0
  14. package/dist/daemon-client.js +14 -4
  15. package/dist/daemon-client.js.map +1 -1
  16. package/dist/daemon-client.mjs +1 -1
  17. package/dist/{eventStore-ClHaWY9b.d.mts → eventStore-D9Kv5dTu.d.mts} +27 -2
  18. package/dist/{eventStore-s1fpKwFe.d.ts → eventStore-DeuZxnKm.d.ts} +27 -2
  19. package/dist/index.d.mts +21 -12
  20. package/dist/index.d.ts +21 -12
  21. package/dist/index.js +1487 -1362
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +1104 -1002
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{maxParallel-fSAdLIMh.d.mts → maxParallel-CSTmqKeu.d.mts} +44 -8
  26. package/dist/{maxParallel-DXvhdlD5.d.ts → maxParallel-Ds9VI1KO.d.ts} +44 -8
  27. package/dist/parsing.d.mts +2 -2
  28. package/dist/parsing.d.ts +2 -2
  29. package/dist/parsing.js +1 -1
  30. package/dist/parsing.js.map +1 -1
  31. package/dist/parsing.mjs +3 -3
  32. package/dist/plan-utils.d.mts +4 -4
  33. package/dist/plan-utils.d.ts +4 -4
  34. package/dist/plan-utils.js.map +1 -1
  35. package/dist/plan-utils.mjs +3 -3
  36. package/dist/testing.d.mts +4 -2
  37. package/dist/testing.d.ts +4 -2
  38. package/dist/testing.js +2 -0
  39. package/dist/testing.js.map +1 -1
  40. package/dist/testing.mjs +3 -1
  41. package/dist/testing.mjs.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-MGMQKUIJ.mjs.map +0 -1
  44. package/dist/chunk-O52PN7P2.mjs.map +0 -1
  45. /package/dist/{chunk-7ACNW5CD.mjs.map → chunk-4OARA73Z.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/daemon-client.ts","../src/utils/daemonProcess.ts","../src/utils/globalDataDir.ts","../src/utils/daemonToken.ts","../src/utils/shellPath.ts","../src/utils/version.ts","../src/utils/leaseRecord.ts","../src/utils/processTree.ts","../src/utils/sessionDir.ts","../src/utils/fsHelpers.ts"],"sourcesContent":["/**\n * Node entry point for a client of the local daemon that is not itself a\n * host: the desktop app's main process (ADR-0063 H1). It reaches the daemon's\n * files and handshake without loading the main barrel, which brings the\n * planner, the runners and every AI service with it.\n */\nexport {\n DEFAULT_DAEMON_PORT,\n DAEMON_CONTRACT,\n daemonPidFilePath,\n legacyDaemonPidFilePath,\n daemonLogPath,\n readPidFile,\n resolveDaemonPort,\n isConnectionRefused,\n daemonHttpGet,\n isDaemonRunning,\n probeDaemon,\n stopDaemonAt,\n} from './utils/daemonProcess';\nexport type { DaemonHttpResponse, DaemonIdentity, DaemonProbe, DaemonStopOutcome } from './utils/daemonProcess';\nexport {\n daemonTokenPath,\n readDaemonToken,\n bearerHeaderValue,\n tokenSubprotocols,\n DAEMON_SUBPROTOCOL,\n} from './utils/daemonToken';\nexport { augmentedPath, withPath } from './utils/shellPath';\nexport { globalDataDir } from './utils/globalDataDir';\nexport { compareVersions } from './utils/version';\nexport { readLiveHolder, LEASE_STALE_MS } from './utils/leaseRecord';\nexport type { LeaseHostKind, SessionLeaseRecord, LiveHolderProbes } from './utils/leaseRecord';\n","/**\n * How a client finds, probes and stops the local daemon: its port, its PID\n * file, its log, and the `GET /api/server` handshake. The CLI and the desktop\n * app both read these files, and they must read them the same way, or one of\n * them stops a daemon the other cannot see (ADR-0063 H2).\n *\n * Starting a daemon is not here: the CLI spawns its own Node binary and the\n * desktop app forks a utility process, and neither can do the other's.\n */\n\nimport http from 'http';\nimport { existsSync, readFileSync, unlinkSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { bearerHeaderValue, clearDaemonToken, readDaemonToken } from './daemonToken';\n\nexport const DEFAULT_DAEMON_PORT = 3742;\n\n/**\n * The daemon contract's number, answered by `GET /api/server` and compared by\n * a client before it drives a daemon it did not start (ADR-0063 H3). Raise it\n * whenever a body in `daemonContract.ts` or a socket frame changes in a way an\n * older client or daemon would misread, and whenever a client comes to need a\n * route, or a value on an existing route, that an older daemon lacks or\n * refuses: the same contract attaches, so such a client would drive that\n * daemon into a 404 or a refusal it cannot tell from a real one. A field only\n * added, which an older side ignores or does without, need not.\n *\n * 2: the desktop's card edits go to `plans.cardEdit`, which no contract-1\n * daemon serves.\n * 3: the desktop's Explorer reads the workspace folder itself, as repo `.`,\n * which a contract-2 daemon refuses in a folder that is not a repository.\n */\nexport const DAEMON_CONTRACT = 3;\n\n// Paths are read at call time, not import time: a test (and a shell that\n// re-exports HOME) changes the home directory after this module loads.\n\n/**\n * One PID file per port so a second daemon doesn't clobber the first one's\n * entry (and `stop --server --port N` kills the daemon the user meant).\n */\nexport function daemonPidFilePath(port: number): string {\n return pidFileIn(globalDataDir(), port);\n}\n\n/**\n * Pre-`.ordewell` install: a daemon spawned by old code wrote its PID file\n * here, so a stop falls back to it rather than orphaning that daemon behind a\n * path it doesn't know moved.\n */\nexport function legacyDaemonPidFilePath(port: number): string {\n return pidFileIn(join(homedir(), '.config', 'ordewell'), port);\n}\n\nfunction pidFileIn(dir: string, port: number): string {\n return port === DEFAULT_DAEMON_PORT ? join(dir, 'server.pid') : join(dir, `server-${port}.pid`);\n}\n\nexport function daemonLogPath(): string {\n return join(globalDataDir(), 'server.log');\n}\n\n/** The PID a file names, or undefined when it is missing or not a positive integer. */\nexport function readPidFile(file: string): number | undefined {\n try {\n const pid = parseInt(readFileSync(file, 'utf8').trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Which daemon a client should talk to: an explicit port, else ORDEWELL_PORT,\n * else the default. Lets a client target an isolated second daemon instead of\n * whatever is already on 3742.\n */\nexport function resolveDaemonPort(\n explicit?: string | number,\n env: NodeJS.ProcessEnv = process.env,\n): number {\n const parsedArg = typeof explicit === 'number' ? explicit : parseInt(explicit ?? '', 10);\n if (Number.isInteger(parsedArg) && parsedArg > 0) return parsedArg;\n const fromEnv = parseInt(env.ORDEWELL_PORT ?? '', 10);\n if (!isNaN(fromEnv) && fromEnv > 0) return fromEnv;\n return DEFAULT_DAEMON_PORT;\n}\n\n/**\n * True when this error means \"nothing was listening\", as opposed to \"the\n * server answered badly\" or \"the connection broke mid-flight\".\n *\n * The distinction is what makes an automatic retry safe. ECONNREFUSED is\n * refused at the TCP handshake, so the request was never delivered and cannot\n * have been half-applied — replaying it is not a second execution. ECONNRESET\n * and EPIPE are deliberately *not* included: those can arrive after the server\n * read the request, so a retry could start a second plan or a second run.\n */\nexport function isConnectionRefused(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code;\n if (code === 'ECONNREFUSED') return true;\n // The code survives a normal reject, but not every layer preserves it —\n // `String(err)` through a worker boundary keeps only the message.\n const message = err instanceof Error ? err.message : String(err ?? '');\n return message.includes('ECONNREFUSED');\n}\n\nexport interface DaemonHttpResponse {\n status: number;\n data: string;\n}\n\n/**\n * A GET to the daemon on `port`, carrying the token file's bearer when there\n * is one. No `Origin` is ever sent: admission refuses any request with one.\n */\nexport function daemonHttpGet(\n port: number,\n path: string,\n timeoutMs: number = 2000,\n): Promise<DaemonHttpResponse> {\n const token = readDaemonToken(port);\n const headers: Record<string, string> = token ? { Authorization: bearerHeaderValue(token) } : {};\n return new Promise((resolvePromise, reject) => {\n const req = http.get({ host: '127.0.0.1', port, path, timeout: timeoutMs, headers }, (res) => {\n // Decoded once the body is whole: a multi-byte character split across two\n // chunks would otherwise turn into U+FFFD at the seam.\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer) => { chunks.push(chunk); });\n res.on('end', () => resolvePromise({ status: res.statusCode || 0, data: Buffer.concat(chunks).toString('utf8') }));\n });\n req.on('error', reject);\n req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });\n });\n}\n\nexport async function isDaemonRunning(port: number = DEFAULT_DAEMON_PORT): Promise<boolean> {\n try {\n const res = await daemonHttpGet(port, '/api/workspaces');\n // 401 still means a daemon owns this port. Reporting it as absent would\n // send a caller to spawn a second one that cannot bind; reporting it as\n // present lets the next real request answer with the token-file message.\n return res.status === 200 || res.status === 401;\n } catch {\n return false;\n }\n}\n\n/** What `GET /api/server` said about the process that owns the port. */\nexport interface DaemonIdentity {\n pid: number;\n /** The daemon's package version; absent from a daemon older than the field. */\n version?: string;\n /** The daemon contract it speaks (ADR-0063 H3); absent from a daemon older than the field. */\n contract?: number;\n /** Work is under way in a session it holds; absent from a daemon older than the field, which cannot say. */\n live?: boolean;\n}\n\nexport type DaemonProbe =\n | { kind: 'daemon'; identity: DaemonIdentity }\n /** Nothing owns the port: a stale PID file and token are safe to remove. */\n | { kind: 'unreachable' }\n /**\n * The daemon's own refusal of the token presented, or of none: it runs, but\n * for another user or install, or its token file has gone stale.\n */\n | { kind: 'unauthorized'; tokenPresented: boolean }\n /** Something owns the port, but it cannot prove which process it is. Never signal it. */\n | { kind: 'unverifiable' };\n\n// The daemon's 401 body names its token file; a stranger's 401 does not. That\n// is what tells \"a daemon that refuses us\" from \"some other server\".\nconst DAEMON_REFUSAL_MARK = 'bearer token';\n\n/**\n * Ask the daemon on `port` which process it is. A daemon older than this\n * route answers 404, and anything that is not a daemon answers whatever it\n * answers: both are `unverifiable`.\n */\nexport async function probeDaemon(port: number, timeoutMs: number = 2000): Promise<DaemonProbe> {\n let res: DaemonHttpResponse;\n try {\n res = await daemonHttpGet(port, '/api/server', timeoutMs);\n } catch (err) {\n return isConnectionRefused(err) ? { kind: 'unreachable' } : { kind: 'unverifiable' };\n }\n if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {\n return { kind: 'unauthorized', tokenPresented: readDaemonToken(port) !== undefined };\n }\n if (res.status !== 200) return { kind: 'unverifiable' };\n const identity = parseIdentity(res.data);\n return identity ? { kind: 'daemon', identity } : { kind: 'unverifiable' };\n}\n\nfunction parseIdentity(body: string): DaemonIdentity | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const fields = parsed as Partial<Record<'pid' | 'version' | 'contract' | 'live', unknown>>;\n const { pid, version, contract, live } = fields;\n if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return undefined;\n return {\n pid,\n ...(typeof version === 'string' ? { version } : {}),\n ...(typeof contract === 'number' && Number.isInteger(contract) ? { contract } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n}\n\nexport type DaemonStopOutcome =\n | { kind: 'no-pid-file' }\n /** The file named no PID; it and the token were removed. */\n | { kind: 'unreadable-pid-file' }\n /** Something owns the port but cannot name itself: nothing was signalled. */\n | { kind: 'unverifiable'; filePid: number }\n /** Nothing was running; the stale PID file (and token) were removed. */\n | { kind: 'stale' }\n | { kind: 'stopped'; pid: number; filePid: number };\n\n/**\n * Stop the daemon on `port` the way `ordewell stop --server` does: signal the\n * PID the daemon itself reports, and only when the PID file can be checked\n * against it, so a stale file never terminates an unrelated process.\n */\nexport async function stopDaemonAt(port: number = DEFAULT_DAEMON_PORT): Promise<DaemonStopOutcome> {\n let pidFile = daemonPidFilePath(port);\n if (!existsSync(pidFile) && existsSync(legacyDaemonPidFilePath(port))) pidFile = legacyDaemonPidFilePath(port);\n if (!existsSync(pidFile)) return { kind: 'no-pid-file' };\n\n const filePid = readPidFile(pidFile);\n if (!filePid) {\n removeQuietly(pidFile);\n clearDaemonToken(port);\n return { kind: 'unreadable-pid-file' };\n }\n\n const probe = await probeDaemon(port);\n if (probe.kind === 'unreachable') {\n removeQuietly(pidFile);\n // A daemon killed outright never ran its own shutdown, so its token file\n // may still be sitting there looking usable.\n clearDaemonToken(port);\n return { kind: 'stale' };\n }\n if (probe.kind !== 'daemon') {\n // A PID from an unverified file may now belong to any process the OS has\n // recycled it for. Refuse rather than risk killing something unrelated.\n return { kind: 'unverifiable', filePid };\n }\n\n const pid = probe.identity.pid;\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n const code = (err as Error & { code?: string }).code;\n if (code !== 'ESRCH') throw err;\n removeQuietly(pidFile);\n return { kind: 'stale' };\n }\n removeQuietly(pidFile);\n return { kind: 'stopped', pid, filePid };\n}\n\nfunction removeQuietly(file: string): void {\n try { unlinkSync(file); } catch { /* already gone */ }\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\n/**\n * Where Ordewell keeps machine-global data (settings, daemon tokens, caches,\n * credentials). A single home for everything not tied to a project directory,\n * so per-project state in `.ordewell/` and global state never collide.\n */\nexport function globalDataDir(): string {\n return path.join(os.homedir(), '.ordewell');\n}\n\nlet migrated = false;\n\n/**\n * One-time lift of a pre-`.ordewell` install's files into the new location.\n * Each file/dir is checked independently — old exists, new doesn't — rather\n * than gating the whole thing on \"new dir doesn't exist yet\". A machine that\n * migrated `settings.json` under an earlier release already has `globalDataDir()`\n * on disk, which would otherwise permanently skip lifting anything added to\n * this list later (`.env` did exactly that: real API keys stranded in the old\n * dir because the settings.json move had already made the new dir exist).\n *\n * Best-effort: a home it cannot write (read-only, full disk) must not take the\n * CLI down before `--help`, and the old file stays where it is.\n */\nexport function migrateOldConfigDir(): void {\n if (migrated) return;\n migrated = true;\n\n const oldDir = path.join(os.homedir(), '.config', 'ordewell');\n if (!fs.existsSync(oldDir)) return;\n const newDir = globalDataDir();\n\n const liftFile = (name: string): void => {\n const oldFile = path.join(oldDir, name);\n const newFile = path.join(newDir, name);\n if (!fs.existsSync(oldFile) || fs.existsSync(newFile)) return;\n try {\n fs.mkdirSync(newDir, { recursive: true });\n fs.copyFileSync(oldFile, newFile);\n } catch (err) {\n console.warn(`Could not move ${oldFile} to ${newFile}: ${String(err)}`);\n }\n };\n\n liftFile('settings.json');\n liftFile('.env');\n}\n","/**\n * The daemon's bearer token: minted at startup, written beside the per-port\n * process-id file, read by the CLI.\n *\n * Header validation defends against browsers and nothing else. This is what\n * stops another process running as the same user — an install script in the\n * very repository the planner was pointed at, say — from driving the daemon\n * just because it can see the port.\n *\n * Both ends of the wire live here so the carrier encodings cannot drift: the\n * daemon extracts with the same functions the CLI attaches with.\n */\n\nimport { randomBytes, timingSafeEqual } from 'crypto';\nimport { readFileSync, unlinkSync } from 'fs';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { writePrivateFile } from './privateFile';\n\nconst BEARER_PREFIX = 'bearer ';\n\n/**\n * The subprotocol the token rides on during the WebSocket upgrade. A query\n * parameter would land in access logs and in `ps`; a subprotocol travels in a\n * request header like the HTTP `Authorization` it stands in for.\n */\nexport const DAEMON_TOKEN_SUBPROTOCOL_PREFIX = 'ordewell.token.';\n\n/**\n * Offered alongside the token subprotocol, and the one the server selects, so\n * the 101 response never echoes the secret back.\n */\nexport const DAEMON_SUBPROTOCOL = 'ordewell.v1';\n\nfunction configDir(): string {\n return globalDataDir();\n}\n\n/**\n * One token file per port, with no default-port special case: unlike the\n * process-id file there is no legacy name to preserve, and naming every file\n * after its port is what stops a second daemon clobbering the first's token.\n */\nexport function daemonTokenPath(port: number): string {\n return join(configDir(), `server-${port}.token`);\n}\n\n/**\n * Mint this daemon's token and hand it off through the filesystem.\n *\n * The write goes through `writePrivateFile` rather than a plain write because\n * `mode` is ignored when the file already exists: writing over a pre-created\n * file would leave the token at whatever permissions that file already had, and\n * an existing symlink would carry the write somewhere else entirely. The helper\n * writes a fresh 0600 temp file and renames it into place, so neither applies.\n */\nexport function mintDaemonToken(port: number): { token: string; file: string } {\n const token = randomBytes(32).toString('base64url');\n const file = daemonTokenPath(port);\n writePrivateFile(file, token);\n return { token, file };\n}\n\n/** The token a client should present to the daemon on `port`, if one has been minted. */\nexport function readDaemonToken(port: number): string | undefined {\n try {\n const token = readFileSync(daemonTokenPath(port), 'utf8').trim();\n return token === '' ? undefined : token;\n } catch {\n return undefined;\n }\n}\n\n/** Best-effort cleanup on shutdown, so a dead daemon leaves no usable-looking token behind. */\nexport function clearDaemonToken(port: number): void {\n try {\n unlinkSync(daemonTokenPath(port));\n } catch {\n // Already gone, or never written.\n }\n}\n\n/** The `Authorization` header value for HTTP requests. */\nexport function bearerHeaderValue(token: string): string {\n return `Bearer ${token}`;\n}\n\n/** What a client offers on the upgrade: the real subprotocol first, the token second. */\nexport function tokenSubprotocols(token: string): string[] {\n return [DAEMON_SUBPROTOCOL, `${DAEMON_TOKEN_SUBPROTOCOL_PREFIX}${token}`];\n}\n\nexport interface TokenCarriers {\n /** `Authorization: Bearer <token>` — the HTTP carrier. */\n authorization?: string | null;\n /** `Sec-WebSocket-Protocol` — the upgrade carrier. */\n secWebSocketProtocol?: string | null;\n}\n\n/** Pull the token out of whichever carrier it arrived on. */\nexport function extractPresentedToken(carriers: TokenCarriers): string | undefined {\n const authorization = carriers.authorization;\n if (authorization && authorization.toLowerCase().startsWith(BEARER_PREFIX)) {\n const value = authorization.slice(BEARER_PREFIX.length).trim();\n if (value !== '') return value;\n }\n\n for (const offered of (carriers.secWebSocketProtocol ?? '').split(',')) {\n const value = offered.trim();\n if (!value.startsWith(DAEMON_TOKEN_SUBPROTOCOL_PREFIX)) continue;\n const token = value.slice(DAEMON_TOKEN_SUBPROTOCOL_PREFIX.length);\n if (token !== '') return token;\n }\n\n return undefined;\n}\n\n/** Constant-time comparison, so a wrong token leaks no information about the right one. */\nexport function tokensMatch(presented: string | undefined, expected: string): boolean {\n if (presented === undefined) return false;\n const a = Buffer.from(presented, 'utf8');\n const b = Buffer.from(expected, 'utf8');\n // timingSafeEqual throws on a length mismatch; the length is not the secret.\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n","import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as os from 'os';\nimport * as path from 'path';\n\nconst execAsync = promisify(exec);\n\n/**\n * GUI-launched processes (the VS Code extension host, a desktop-spawned web\n * server) often inherit a minimal PATH that misses user-level install dirs\n * (~/.local/bin, ~/.opencode/bin, nvm shims, …), so spawning `claude` or\n * `opencode` fails even though the user has them installed. This module\n * resolves an augmented PATH once per process: the interactive login shell's\n * PATH (which runs the user's profile, covering nvm/volta/asdf and friends)\n * merged over the current PATH, plus the well-known per-user bin dirs as a\n * final safety net when the login shell itself can't be queried. On Windows\n * there is no login shell to query, so the well-known dirs are the whole net —\n * see {@link windowsBinDirs}.\n *\n * {@link withPath} is the other half: handing the resolved PATH to a child\n * without accidentally giving it two.\n */\n\nconst LOGIN_SHELL_TIMEOUT_MS = 5000;\nconst PATH_MARKER = '__ORDEWELL_PATH__';\n\ntype ExecFn = (command: string, options?: { timeout?: number }) => Promise<{ stdout: string }>;\n\nconst defaultExec: ExecFn = async (command, options) => {\n const { stdout } = await execAsync(command, options);\n return { stdout: String(stdout) };\n};\n\nfunction posixBinDirs(): string[] {\n const home = os.homedir();\n return [\n path.join(home, '.local', 'bin'),\n path.join(home, '.opencode', 'bin'),\n path.join(home, '.claude', 'bin'),\n path.join(home, '.bun', 'bin'),\n path.join(home, '.volta', 'bin'),\n path.join(home, '.npm-global', 'bin'),\n path.join(home, 'bin'),\n '/usr/local/bin',\n '/opt/homebrew/bin',\n ];\n}\n\n/**\n * The Windows counterpart of {@link posixBinDirs}. There is no login shell to\n * ask on Windows, so this list is the only safety net when a runner was\n * installed after the host process started (the registry PATH a GUI-launched\n * VS Code inherited is a snapshot from launch time) or by an installer that\n * writes its own directory rather than amending PATH.\n *\n * The three built-in runners can each arrive by several routes, and the list\n * has to cover all of them or the picker greys out a CLI the user just\n * installed:\n *\n * - **PowerShell one-liner installers.** `irm https://claude.ai/install.ps1 |\n * iex` writes a native `claude.exe` to `%USERPROFILE%\\.local\\bin`, and\n * OpenCode's writes to `%USERPROFILE%\\.opencode\\bin`. `.local\\bin` was the\n * conspicuous omission — it is in {@link posixBinDirs}, where the same\n * installer puts the same binary, and its absence here meant the officially\n * documented Windows install of the flagship runner was the one Ordewell\n * could not find.\n * - **Node package managers.** npm's global prefix, and pnpm's and Yarn's,\n * which are not under it.\n * - **Windows package managers.** Scoop and Chocolatey shim directories, and\n * WinGet's `Links` folder for portable packages (distinct from\n * `WindowsApps`, which is MSIX only).\n * - **Version managers.** Volta spells its home `%LOCALAPPDATA%\\Volta` here,\n * not `~/.volta` as it does on POSIX.\n */\nfunction windowsBinDirs(env: NodeJS.ProcessEnv, home: string): string[] {\n const join = (...parts: string[]) => path.win32.join(...parts);\n const under = (base: string | undefined, ...parts: string[]) => (base ? [join(base, ...parts)] : []);\n const appData = env.APPDATA;\n const localAppData = env.LOCALAPPDATA;\n const programData = env.ProgramData;\n\n return [\n // Native per-user installers, PowerShell-driven and otherwise.\n join(home, '.local', 'bin'),\n join(home, '.opencode', 'bin'),\n join(home, '.claude', 'bin'),\n join(home, '.codex', 'bin'),\n ...under(localAppData, 'Programs', 'claude'),\n\n // Node package managers. npm's global prefix is `%APPDATA%\\npm`; the\n // literal spelling is kept as a fallback for a host that does not export\n // APPDATA (a service account, a stripped CI container).\n ...under(appData, 'npm'),\n join(home, 'AppData', 'Roaming', 'npm'),\n ...under(localAppData, 'pnpm'),\n ...under(localAppData, 'Yarn', 'bin'),\n join(home, '.bun', 'bin'),\n\n // Windows package managers.\n join(home, 'scoop', 'shims'),\n ...under(env.SCOOP, 'shims'),\n ...under(env.SCOOP_GLOBAL ?? programData, 'scoop', 'shims'),\n ...under(programData, 'chocolatey', 'bin'),\n // WinGet portable packages land here; `WindowsApps` only ever holds MSIX\n // aliases, so both are needed and neither substitutes for the other.\n ...under(localAppData, 'Microsoft', 'WinGet', 'Links'),\n ...under(localAppData, 'Microsoft', 'WindowsApps'),\n\n // Version managers. Volta's Windows home is not the POSIX `~/.volta`.\n ...under(localAppData, 'Volta', 'bin'),\n join(home, '.volta', 'bin'),\n ];\n}\n\n/**\n * Exported for test: the Windows arm cannot be exercised from a Linux CI box\n * through {@link augmentedPath}, which reads `process.platform` and the real\n * environment. Production always calls it through the no-argument form.\n */\nexport function wellKnownBinDirs(deps: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; home?: string } = {}): string[] {\n const platform = deps.platform ?? process.platform;\n if (platform !== 'win32') return posixBinDirs();\n return [...new Set(windowsBinDirs(deps.env ?? process.env, deps.home ?? os.homedir()))];\n}\n\nasync function loginShellPath(execImpl: ExecFn): Promise<string | null> {\n if (process.platform === 'win32') return null;\n const shell = process.env.SHELL || '/bin/sh';\n try {\n // Markers isolate $PATH from any profile noise (motd, echo in .zprofile…).\n const { stdout } = await execImpl(\n `${shell} -l -c 'echo \"${PATH_MARKER}$PATH${PATH_MARKER}\"'`,\n { timeout: LOGIN_SHELL_TIMEOUT_MS },\n );\n const match = stdout.match(new RegExp(`${PATH_MARKER}([^\\\\n]*)${PATH_MARKER}`));\n return match?.[1] || null;\n } catch {\n return null;\n }\n}\n\nlet cachedPath: Promise<string> | null = null;\n\n/**\n * The augmented PATH for spawning user-installed CLI tools. Resolved once per\n * process and cached (the login shell query costs ~50-200ms).\n */\nexport function augmentedPath(execImpl: ExecFn = defaultExec): Promise<string> {\n if (!cachedPath) {\n cachedPath = (async () => {\n const segments: string[] = [];\n const push = (p: string | null | undefined) => {\n if (!p) return;\n for (const seg of p.split(path.delimiter)) {\n if (seg && !segments.includes(seg)) segments.push(seg);\n }\n };\n push(process.env.PATH);\n push(await loginShellPath(execImpl));\n for (const dir of wellKnownBinDirs()) push(dir);\n return segments.join(path.delimiter);\n })();\n }\n return cachedPath;\n}\n\n/** Test seam: drop the per-process cache so the next call re-resolves. */\nexport function clearAugmentedPathCache(): void {\n cachedPath = null;\n}\n\n/**\n * The value `env` gives `name`, read as `platform` reads it: on Windows a name\n * in any case is the same variable, and the last spelling is the one\n * {@link withPath} keeps.\n */\nexport function envValue(env: Readonly<Record<string, string | undefined>>, name: string, platform: NodeJS.Platform = process.platform): string | undefined {\n if (platform !== 'win32') return env[name];\n const wanted = name.toLowerCase();\n let found: string | undefined;\n for (const [key, value] of Object.entries(env)) if (key.toLowerCase() === wanted) found = value;\n return found;\n}\n\n/**\n * Build a child environment whose PATH is `resolvedPath`, with exactly one\n * PATH-ish key in it.\n *\n * `{ ...process.env, PATH }` is the obvious spelling and it is wrong on\n * Windows. Node's `process.env` is a case-insensitive proxy, but spreading it\n * yields the OS's actual casing — `Path` — so adding `PATH` produces an\n * environment block carrying both. Which one the child sees is undefined, and\n * the loser is silently discarded. Every existing site passed the same value\n * under both keys, so the bug was latent rather than live; this makes it\n * impossible instead of unlikely.\n */\nexport function withPath(\n base: NodeJS.ProcessEnv,\n resolvedPath: string,\n overrides: Record<string, string> = {},\n platform: NodeJS.Platform = process.platform,\n): NodeJS.ProcessEnv {\n // Windows names a variable in any case, and Node hands a child only the first\n // spelling in sort order, so a host's `FOO` would silently beat an override's\n // `foo`: a later spelling has to replace an earlier one, not sit beside it,\n // whether the earlier came from `base` or from `overrides` itself.\n const name = platform === 'win32' ? (key: string) => key.toLowerCase() : (key: string) => key;\n const entries = new Map<string, [string, string | undefined]>();\n // Both sources are filtered, not just `base`: an `overrides` map carrying its\n // own PATH is exactly how the duplicate reappears.\n for (const source of [base, overrides]) {\n for (const [key, value] of Object.entries(source)) {\n if (key.toLowerCase() === 'path') continue;\n entries.set(name(key), [key, value]);\n }\n }\n const env: NodeJS.ProcessEnv = Object.fromEntries(entries.values());\n // Windows canonically spells it `Path`; POSIX requires `PATH`. Matching the\n // platform keeps anything downstream that reads the raw block unsurprised.\n env[platform === 'win32' ? 'Path' : 'PATH'] = resolvedPath;\n return env;\n}\n","/**\n * A dotted numeric version, compared the way a harness reports it: `2.1.304`.\n * A missing component counts as zero, so `2.1` and `2.1.0` are the same\n * version, and a `v` prefix is not part of it. A prerelease (`2.1.304-beta`)\n * sorts before the release it names, so a build the live checks did not cover\n * is never mistaken for the checked one.\n */\ninterface Version {\n numbers: number[];\n /** Everything after the first `-`, without the build suffix; null for a release. */\n prerelease: string | null;\n}\n\nfunction parse(version: string): Version | null {\n const match = /^v?(\\d+(?:\\.\\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/i.exec(version.trim());\n if (!match) return null;\n return { numbers: match[1].split('.').map(Number), prerelease: match[2] ?? null };\n}\n\n/** The numeric components of a version, or null when it cannot be read. */\nexport function parseVersion(version: string): number[] | null {\n return parse(version)?.numbers ?? null;\n}\n\n/** Negative, zero or positive as `a` is older than, the same as, or newer than `b`; an unreadable version sorts oldest. */\nexport function compareVersions(a: string, b: string): number {\n const left = parse(a);\n const right = parse(b);\n if (!left || !right) return left ? 1 : right ? -1 : 0;\n const length = Math.max(left.numbers.length, right.numbers.length);\n for (let i = 0; i < length; i++) {\n const one = left.numbers[i] ?? 0;\n const other = right.numbers[i] ?? 0;\n if (one !== other) return one < other ? -1 : 1;\n }\n if (left.prerelease === right.prerelease) return 0;\n if (left.prerelease === null) return 1;\n if (right.prerelease === null) return -1;\n return left.prerelease < right.prerelease ? -1 : 1;\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { processAlive } from './processTree';\nimport { getSessionsDir, idSegment } from './sessionDir';\n\n/**\n * A session's lease file as any process reads it (ADR-0049): the record a\n * host writes, and the judgement of whether that host still lives. The hosts\n * themselves take and refresh it in `services/sessionLease`; this half is\n * apart so a client that is no host can read it through `daemon-client`.\n */\n\n/**\n * A lease not refreshed for this long is stale: its holder is gone, or its pid\n * now names another process. Several heartbeats, so a host whose event loop is\n * busy for a moment keeps its session.\n */\nexport const LEASE_STALE_MS = 60_000;\n\n/**\n * What kind of process a host is, for the words a refusal names it in and the\n * surface the planner is told its user has. `ownerPid` is the TUI a private\n * daemon serves; `app` marks the daemon the desktop app forked.\n */\nexport type LeaseHostKind =\n | { kind: 'daemon'; port: number; ownerPid?: number; app?: 'desktop' }\n | { kind: 'vscode' };\n\n/** A session's lease as its file records it. */\nexport interface SessionLeaseRecord {\n /** Minted once per host, so a restarted process at a reused pid is not mistaken for the holder. */\n hostId: string;\n pid: number;\n host?: LeaseHostKind;\n /** When this host took the lease. */\n since: string;\n /** Refreshed every heartbeat; stale past {@link LEASE_STALE_MS}. */\n heartbeatAt: string;\n /**\n * The process groups of the runners the holder had started and not seen\n * end. A host killed outright cannot stop them, and they go on writing in\n * the session's worktrees, so a takeover waits for them.\n */\n runnerGroups: number[];\n /**\n * Whether the holder's run is live: an attempt at work, a start pending, a\n * landing or Merge all under way. Much of that is only in the holder's\n * memory, so it says it here, for another host's landing interlock\n * (ADR-0062 G7). Absent from a holder that predates it.\n */\n runLive?: boolean;\n}\n\nconst LEASE_FILE = 'lease.json';\n\n/** A root session's lease file; a child writes none (ADR-0055 D13). */\nexport function leaseFile(sessionId: string, workspace: string): string {\n return path.join(getSessionsDir(workspace), idSegment(sessionId), LEASE_FILE);\n}\n\nfunction isRecord(value: unknown): value is SessionLeaseRecord {\n if (typeof value !== 'object' || value === null) return false;\n const r = value as Record<string, unknown>;\n return typeof r.hostId === 'string' && typeof r.pid === 'number' && typeof r.since === 'string'\n && typeof r.heartbeatAt === 'string' && Array.isArray(r.runnerGroups) && r.runnerGroups.every((g) => typeof g === 'number');\n}\n\n/** The record on disk; null when there is none, or none any host could have written (every write is a rename). */\nexport function readLeaseRecord(file: string): SessionLeaseRecord | null {\n let raw: string;\n try {\n raw = fs.readFileSync(file, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/** Whether the host that wrote `record` lives, judged by its heartbeat and its pid. */\nexport function holderLives(record: SessionLeaseRecord, now: number, alive: (pid: number) => boolean): boolean {\n const beat = Date.parse(record.heartbeatAt);\n if (Number.isNaN(beat) || now - beat > LEASE_STALE_MS) return false;\n return alive(record.pid);\n}\n\nexport interface LiveHolderProbes {\n now?: () => number;\n alive?: (pid: number) => boolean;\n}\n\n/**\n * The host that holds `sessionId` in `workspace` now, or null when none does.\n * For a client that holds no lease of its own and only needs to know whom to\n * reach: it does not weigh orphaned runners, which only a host taking over must.\n */\nexport function readLiveHolder(sessionId: string, workspace: string, probes: LiveHolderProbes = {}): SessionLeaseRecord | null {\n const record = readLeaseRecord(leaseFile(sessionId, workspace));\n if (!record) return null;\n return holderLives(record, (probes.now ?? Date.now)(), probes.alive ?? processAlive) ? record : null;\n}\n","import { ChildProcess, execFile, spawn as spawnProcess } from 'child_process';\nimport type { Socket } from 'net';\n\n/**\n * Stopping an agent process, on every platform.\n *\n * POSIX gets SIGTERM, then SIGKILL after a grace period — sent to the runner's\n * whole process group when it was started by {@link spawnInOwnGroup}, because\n * the direct child is a CLI and what kept running after Stop was everything it\n * had started: shells, MCP servers, test runs, dev servers. Windows has no signals — `ChildProcess.kill` calls TerminateProcess\n * on the direct child only — and on Windows the direct child is frequently not\n * the agent. A `claude.cmd` shim launched through cmd.exe puts an interpreter\n * between Ordewell and the `node cli.js` doing the work, so terminating the child\n * left the real agent running: still holding the workspace, still spending the\n * user's subscription, invisible to the surface that thought it had stopped.\n * `taskkill /T` walks the tree instead.\n *\n * Both paths are best-effort and idempotent by construction. A process that has\n * already exited is not an error here — every caller is on a dispose path.\n */\n\n/** Grace period between the polite stop and the forced one. */\nconst HARD_KILL_DELAY_MS = 5000;\n\nfunction isNoSuchProcess(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ESRCH';\n}\n\n/**\n * Whether `proc` has reported its own end. A process killed by a signal\n * reports `exitCode` null and `signalCode` set, and is as gone as one that\n * exited with a code. Only a reported value counts: an object that reports\n * neither is treated as running — the cost of a redundant kill is nothing,\n * the cost of skipping a live one is an orphaned agent.\n */\nfunction hasExited(proc: ChildProcess): boolean {\n return typeof proc.exitCode === 'number' || typeof proc.signalCode === 'string';\n}\n\nexport interface KillTreeDeps {\n platform?: NodeJS.Platform;\n /** Runs `taskkill`. Injected so the Windows path is testable off Windows. */\n execFileImpl?: (file: string, args: string[], cb: (err: Error | null) => void) => void;\n /** Schedules the forced kill. Injected so tests need no timers. */\n setTimeoutImpl?: (fn: () => void, ms: number) => { unref?: () => void };\n clearTimeoutImpl?: (handle: unknown) => void;\n /** Signals a pid, or a process group as its negated id. Injected so the group path needs no real processes. */\n killImpl?: (pid: number, signal: NodeJS.Signals | 0) => void;\n}\n\n/** Processes {@link spawnInOwnGroup} made group leaders. */\nconst groupLeaders = new WeakSet<ChildProcess>();\n/** Leaders already signalled: a group signal leaves `proc.killed` false, so it cannot say. */\nconst stopping = new WeakSet<ChildProcess>();\n/**\n * Groups led by a runner, by id, for the host's teardown. Kept while the group\n * still has members, which a leader's exit does not end: a runner that crashes\n * leaves its shells and dev servers behind, and those are what teardown has to\n * reach. Dropped when the group is empty (its id is recyclable then, and no\n * longer ours to vouch for) or when {@link killTree} takes it over.\n */\nconst ownGroups = new Map<number, ChildProcess>();\nlet hostTeardownHooked = false;\n/** What stops each runner group if the host dies without running any of its code; see {@link watchForHostDeath}. */\nconst hostWatches = new Map<number, ChildProcess>();\n/** Told of each runner group as it starts, so a session lease records it at once (ADR-0049). */\nconst groupStartListeners = new Set<() => void>();\n/** What else goes with the host: see {@link onHostTeardown}. */\nconst teardownListeners = new Set<() => void>();\n\n/**\n * Start a runner as the leader of a new process group, so {@link killTree}\n * reaches everything it starts. `spawn` is handed the `detached` flag to pass\n * to Node, which on POSIX is what makes a child a group (and session) leader.\n * Stdio pipes and the host's event loop are unaffected; only `unref` changes\n * the latter, and nothing here calls it.\n *\n * Not on Windows: there `detached` gives the child a console of its own, and\n * `taskkill /T` already walks the tree.\n */\nexport function spawnInOwnGroup(spawn: (detached: boolean) => ChildProcess, platform: NodeJS.Platform = process.platform): ChildProcess {\n if (platform === 'win32') return spawn(false);\n const proc = spawn(true);\n const pgid = proc.pid;\n // No pid: the spawn failed, and its 'error' event reports that.\n if (typeof pgid !== 'number') return proc;\n groupLeaders.add(proc);\n ownGroups.set(pgid, proc);\n if (proc instanceof ChildProcess) watchForHostDeath(pgid);\n // The leader's exit does not end the group: the shells, MCP servers and dev\n // servers it started outlive it, and those are exactly what Stop and host\n // teardown still have to reach. The entry is dropped only once the group is\n // empty — an id with no members left can be recycled, and is no longer ours\n // to signal.\n proc.once('exit', () => { if (!groupHasMembers(pgid)) forgetGroup(proc, pgid); });\n hookHostTeardown();\n for (const listener of groupStartListeners) listener();\n return proc;\n}\n\n/**\n * Stop `pgid` when this host is gone, however it went. SIGKILL and a crash run\n * none of its code, so nothing in it can do this, and a runner in a group of\n * its own would go on editing, committing and spending with nobody to see\n * (ADR-0049 L3). A shell waits on a pipe only this host writes: the kernel\n * closes that as the host dies, and the shell stops the group as `killTree`\n * would. A line down the pipe is a host going politely, which has asked already\n * and cannot stay for the forced stop, so that one is all the shell owes. Started\n * in `/` so no worktree is held open.\n */\nfunction watchForHostDeath(pgid: number): void {\n const group = `-- -${pgid}`;\n const seconds = HARD_KILL_DELAY_MS / 1000;\n const stop = `read _ || kill -s TERM ${group} 2>/dev/null; i=0; while [ \"$i\" -lt ${seconds} ] && kill -s 0 ${group} 2>/dev/null; do sleep 1; i=$((i + 1)); done; kill -s 0 ${group} 2>/dev/null && kill -s KILL ${group} 2>/dev/null`;\n const watch = spawnProcess('/bin/sh', ['-c', stop], { detached: true, cwd: '/', stdio: ['pipe', 'ignore', 'ignore'] });\n // No shell to watch with leaves the runner as it was; the lease still names it.\n watch.on('error', () => { hostWatches.delete(pgid); });\n watch.stdin?.on('error', () => undefined);\n (watch.stdin as Socket | null)?.unref();\n watch.unref();\n hostWatches.set(pgid, watch);\n}\n\nfunction endHostWatch(pgid: number): void {\n hostWatches.get(pgid)?.kill('SIGKILL');\n hostWatches.delete(pgid);\n}\n\n/**\n * The process groups this host's runners lead that still have members. A\n * session lease records them (ADR-0049): the teardown below cannot run for a\n * host killed outright, and {@link watchForHostDeath} may not have finished as\n * a new host looks. Asked on every heartbeat, which is also where a group that\n * outlived its leader and has since emptied is let go.\n */\nexport function runnerGroups(): number[] {\n for (const [pgid, proc] of ownGroups) {\n if (hasExited(proc) && !groupHasMembers(pgid)) forgetGroup(proc, pgid);\n }\n return [...ownGroups.keys()];\n}\n\n/** Hear of each runner group {@link spawnInOwnGroup} starts; the returned function stops it. */\nexport function onRunnerGroupStarted(listener: () => void): () => void {\n groupStartListeners.add(listener);\n return () => { groupStartListeners.delete(listener); };\n}\n\n/**\n * Stop something else as the host goes, with its runner groups but not among\n * them: {@link runnerGroups} never names it, so no lease is held by it. Here\n * rather than in a hook of the caller's, because two signal hooks would each\n * read the other as the host's own handler, and neither would end the host.\n * The returned function stops it being called. Nothing runs for a host killed\n * outright, as for the groups.\n */\nexport function onHostTeardown(stop: () => void): () => void {\n teardownListeners.add(stop);\n hookHostTeardown();\n return () => { teardownListeners.delete(stop); };\n}\n\n/** Whether a process answers to `pid`: one owned by another user, which refuses the signal, is alive too. */\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Whether any process is left in the group `pgid` leads. */\nexport function groupAlive(pgid: number): boolean {\n return groupHasMembers(pgid);\n}\n\n/** Whether any process still answers to `pgid`, as `kill(2)` sees it. */\nfunction groupHasMembers(pgid: number, killImpl: (pid: number, signal: 0) => void = (pid, signal) => { process.kill(pid, signal); }): boolean {\n try {\n killImpl(-pgid, 0);\n return true;\n } catch (err) {\n return !isNoSuchProcess(err);\n }\n}\n\n/**\n * An empty group's id is recyclable, so it is no longer ours to signal: from\n * here on `proc` is an ordinary exited process to {@link killTree}.\n */\nfunction forgetGroup(proc: ChildProcess, pgid: number): void {\n if (ownGroups.get(pgid) === proc) ownGroups.delete(pgid);\n groupLeaders.delete(proc);\n endHostWatch(pgid);\n}\n\n/**\n * A detached runner has left the terminal's foreground group, so Ctrl-C (or a\n * closed terminal) no longer reaches it — the host has to pass that on to the\n * groups it leads. Polite only, and not again to a group already asked: a\n * host disposing its sessions on the way out has just sent SIGTERM, and a\n * second one reads to some CLIs as \"quit without cleaning up\".\n */\nfunction hookHostTeardown(): void {\n if (hostTeardownHooked) return;\n hostTeardownHooked = true;\n const stopAll = () => {\n for (const [pgid, leader] of ownGroups) {\n if (stopping.has(leader)) continue;\n if (hasExited(leader) && !groupHasMembers(pgid)) continue;\n try { process.kill(-pgid, 'SIGTERM'); } catch { /* already gone */ }\n }\n ownGroups.clear();\n for (const watch of hostWatches.values()) watch.stdin?.write('\\n');\n hostWatches.clear();\n for (const stop of teardownListeners) {\n try { stop(); } catch { /* already gone */ }\n }\n teardownListeners.clear();\n };\n process.on('exit', stopAll);\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {\n const onSignal = () => {\n stopAll();\n // A host with a handler of its own decides how to exit. One without was\n // relying on the default, which listening has replaced, so this listener\n // steps aside and the signal is raised again to end the host as before.\n if (process.listenerCount(signal) > 1) return;\n process.removeListener(signal, onSignal);\n process.kill(process.pid, signal);\n };\n process.on(signal, onSignal);\n }\n}\n\nfunction defaultExecFile(file: string, args: string[], cb: (err: Error | null) => void): void {\n execFile(file, args, (err) => cb(err ?? null));\n}\n\n/**\n * Terminate `proc` and everything it started.\n *\n * Returns immediately; the forced follow-up (SIGKILL, or `taskkill /F`) is\n * scheduled and unref'd, so a disposed session is never the reason the host\n * process refuses to exit.\n */\nexport function killTree(proc: ChildProcess | null, deps: KillTreeDeps = {}): void {\n if (!proc) return;\n\n const platform = deps.platform ?? process.platform;\n // A group leader is the exception: its group outlives it, so a crashed\n // runner's shells, dev servers and MCP servers are still there to stop even\n // though the runner is not. That case falls through to the group path below.\n if (!groupLeaders.has(proc) && (proc.killed || hasExited(proc))) return;\n\n const setTimeoutImpl = deps.setTimeoutImpl ?? ((fn, ms) => setTimeout(fn, ms) as unknown as { unref?: () => void });\n const clearTimeoutImpl = deps.clearTimeoutImpl ?? ((h) => clearTimeout(h as NodeJS.Timeout));\n\n if (platform === 'win32') {\n // No pid means the process never started; there is no tree to walk.\n if (typeof proc.pid !== 'number') return;\n const pid = proc.pid;\n const run = deps.execFileImpl ?? defaultExecFile;\n\n // `/T` is the whole point: without it this is the TerminateProcess call\n // that already failed to reach the agent. The unforced pass only asks a\n // window to close, so a console process — every runner — refuses it, and\n // is forced at once: left for the grace, it would go on writing to a\n // workspace the user has stopped it in, and holding it from removal.\n // `/F` follows on the timer too, for one that agreed and did not go.\n const force = () => run('taskkill', ['/pid', String(pid), '/T', '/F'], () => { /* already gone */ });\n // A pass that failed because the process had already gone forces nothing:\n // its pid may be another's by then.\n run('taskkill', ['/pid', String(pid), '/T'], (err) => { if (err && !hasExited(proc)) force(); });\n const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n return;\n }\n\n if (groupLeaders.has(proc) && typeof proc.pid === 'number') {\n if (stopping.has(proc)) return;\n const pgid = proc.pid;\n const killImpl = deps.killImpl ?? ((pid: number, signal: NodeJS.Signals | 0) => { process.kill(pid, signal); });\n // Never signal a group we can't vouch for. While the leader lives its pid\n // holds the id; once it is gone, only a member still in the group does,\n // and an empty group's id may already be a stranger's. So once the leader\n // has exited, every signal is preceded by asking.\n const vouched = () => !hasExited(proc) || groupHasMembers(pgid, killImpl);\n if (!vouched()) {\n forgetGroup(proc, pgid);\n return;\n }\n stopping.add(proc);\n // Taken over here, so the host's teardown and this path do not both signal\n // it (from here on `stopping`, not `ownGroups`, is what says so).\n ownGroups.delete(pgid);\n const signalGroup = (signal: NodeJS.Signals) => {\n try {\n killImpl(-pgid, signal);\n } catch {\n try { proc.kill(signal); } catch { /* already gone */ }\n }\n };\n signalGroup('SIGTERM');\n // Survives the leader's exit: what it started can outlive it, and a\n // process ignoring SIGTERM is exactly the one that does. Asked again when\n // it fires, so a group that emptied during the grace period is left alone;\n // a stranger taking the id between that probe and the signal is the\n // residual risk.\n const hardKill = setTimeoutImpl(() => {\n if (vouched()) signalGroup('SIGKILL');\n endHostWatch(pgid);\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n if (!hasExited(proc)) {\n proc.once('exit', () => { if (!groupHasMembers(pgid, killImpl)) clearTimeoutImpl(hardKill); });\n }\n return;\n }\n\n try {\n proc.kill('SIGTERM');\n const hardKill = setTimeoutImpl(() => {\n try { proc.kill('SIGKILL'); } catch { /* already gone */ }\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n } catch {\n // Process already gone — nothing to clean up.\n }\n}\n","import * as path from 'path';\nimport { getStateDir } from './fsHelpers';\n\n/**\n * Where sessions keep their state, apart from the store that reads it: a\n * client that is no host (the desktop app's main process) finds a session's\n * lease here without loading the plan model the store brings with it.\n */\n\nconst SESSIONS_SUBDIR = 'sessions';\n\nexport function getSessionsDir(baseDir?: string): string {\n return path.join(getStateDir(baseDir), SESSIONS_SUBDIR);\n}\n\n/**\n * A path segment for an id that came from outside — a session id from a URL,\n * a task id a planner wrote. A plain id is used as is; anything that could\n * climb out of its directory, or is not portable as a file name, is hex-encoded.\n */\nexport function idSegment(id: string): string {\n return /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/.test(id) ? id : `~${Buffer.from(id, 'utf-8').toString('hex')}`;\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport const STATE_DIR = '.ordewell';\n\nexport function ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Replace `filePath` with `content` in one step. Writing in place truncates\n * the old bytes first, so a crash, power loss or a full disk mid-write leaves\n * an empty or half-written file where the last good one was — silent loss of\n * the only copy, for a session or a saved plan. The bytes go to a fresh temp\n * file beside the target and a rename swaps it in; within one directory that\n * is atomic, so a reader sees the old file or the new one.\n */\nexport function writeFileAtomic(filePath: string, content: string): void {\n const dir = path.dirname(filePath);\n ensureDir(dir);\n // Same directory, so the rename stays on one filesystem; random, so the name\n // can never collide with another process writing the same file.\n const tempPath = path.join(dir, `.${path.basename(filePath)}.${randomUUID()}.tmp`);\n fs.writeFileSync(tempPath, content, { flag: 'wx' });\n try {\n fs.renameSync(tempPath, filePath);\n } catch (err) {\n try {\n fs.unlinkSync(tempPath);\n } catch {\n // Already gone; the rename error is the one worth reporting.\n }\n throw err;\n }\n}\n\nexport function getStateDir(baseDir?: string): string {\n return path.join(baseDir ?? process.cwd(), STATE_DIR);\n}\n\nconst IGNORE_FILE = '.gitignore';\n\n/**\n * Ignores the state directory's contents except this file and `skills/`, so a\n * project's skills are committed and reach every task worktree through git —\n * the bootstrap never links `.ordewell/` (ADR-0013). Plans and sessions stay\n * uncommittable without touching a file the developer wrote; editing their\n * root `.gitignore` would be the intrusive version of this.\n */\nexport const STATE_DIR_IGNORE = '*\\n!.gitignore\\n!skills/\\n!skills/**\\n';\n\n/** What older builds wrote: everything ignored, the rules file included. */\nconst LEGACY_IGNORES = new Set(['*', '*\\n']);\n\n/**\n * Idempotent, and never overwrites a file the developer customised (to commit\n * their plans deliberately, say). Only the exact legacy rule is upgraded.\n */\nexport function ensureStateDirIgnored(baseDir?: string): void {\n const dir = getStateDir(baseDir);\n ensureDir(dir);\n const file = path.join(dir, IGNORE_FILE);\n try {\n // `wx` rather than an existsSync check: two surfaces can save concurrently,\n // and the loser of that race must not clobber the winner's file.\n fs.writeFileSync(file, STATE_DIR_IGNORE, { flag: 'wx' });\n return;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n }\n if (LEGACY_IGNORES.has(fs.readFileSync(file, 'utf8'))) fs.writeFileSync(file, STATE_DIR_IGNORE);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,kBAAiB;AACjB,IAAAA,aAAqD;AACrD,gBAAwB;AACxB,IAAAC,eAAqB;;;ACZrB,WAAsB;AACtB,SAAoB;AAOb,SAAS,gBAAwB;AACtC,SAAY,UAAQ,WAAQ,GAAG,WAAW;AAC5C;;;ACGA,gBAAyC;AACzC,kBAAqB;AAWd,IAAM,kCAAkC;AAMxC,IAAM,qBAAqB;AAElC,SAAS,YAAoB;AAC3B,SAAO,cAAc;AACvB;AAOO,SAAS,gBAAgB,MAAsB;AACpD,aAAO,kBAAK,UAAU,GAAG,UAAU,IAAI,QAAQ;AACjD;AAmBO,SAAS,gBAAgB,MAAkC;AAChE,MAAI;AACF,UAAM,YAAQ,wBAAa,gBAAgB,IAAI,GAAG,MAAM,EAAE,KAAK;AAC/D,WAAO,UAAU,KAAK,SAAY;AAAA,EACpC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,iBAAiB,MAAoB;AACnD,MAAI;AACF,8BAAW,gBAAgB,IAAI,CAAC;AAAA,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,eAAgB,QAAO;AAC9D,SAAO,MAAM,OAAO,GAAG;AACzB;AAYO,SAAS,eAAe,WAAmB,WAAmB,SAA2B,CAAC,GAA8B;AAC7H,QAAM,SAAS,gBAAgB,UAAU,WAAW,SAAS,CAAC;AAC9D,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,YAAY,SAAS,OAAO,OAAO,KAAK,KAAK,GAAG,OAAO,SAAS,YAAY,IAAI,SAAS;AAClG;","names":["import_fs","import_path","path","http","os","path","join","path","path","path"]}
1
+ {"version":3,"sources":["../src/daemon-client.ts","../src/utils/daemonProcess.ts","../src/utils/globalDataDir.ts","../src/utils/daemonToken.ts","../src/utils/shellPath.ts","../src/utils/version.ts","../src/utils/leaseRecord.ts","../src/utils/processTree.ts","../src/utils/sessionDir.ts","../src/utils/fsHelpers.ts"],"sourcesContent":["/**\n * Node entry point for a client of the local daemon that is not itself a\n * host: the desktop app's main process (ADR-0063 H1). It reaches the daemon's\n * files and handshake without loading the main barrel, which brings the\n * planner, the runners and every AI service with it.\n */\nexport {\n DEFAULT_DAEMON_PORT,\n DAEMON_CONTRACT,\n daemonPidFilePath,\n legacyDaemonPidFilePath,\n daemonLogPath,\n readPidFile,\n resolveDaemonPort,\n isConnectionRefused,\n daemonHttpGet,\n isDaemonRunning,\n probeDaemon,\n stopDaemonAt,\n} from './utils/daemonProcess';\nexport type { DaemonHttpResponse, DaemonIdentity, DaemonProbe, DaemonStopOutcome } from './utils/daemonProcess';\nexport {\n daemonTokenPath,\n readDaemonToken,\n bearerHeaderValue,\n tokenSubprotocols,\n DAEMON_SUBPROTOCOL,\n} from './utils/daemonToken';\nexport { augmentedPath, withPath } from './utils/shellPath';\nexport { globalDataDir } from './utils/globalDataDir';\nexport { compareVersions } from './utils/version';\nexport { readLiveHolder, LEASE_STALE_MS } from './utils/leaseRecord';\nexport type { LeaseHostKind, SessionLeaseRecord, LiveHolderProbes } from './utils/leaseRecord';\n","/**\n * How a client finds, probes and stops the local daemon: its port, its PID\n * file, its log, and the `GET /api/server` handshake. The CLI and the desktop\n * app both read these files, and they must read them the same way, or one of\n * them stops a daemon the other cannot see (ADR-0063 H2).\n *\n * Starting a daemon is not here: the CLI spawns its own Node binary and the\n * desktop app forks a utility process, and neither can do the other's.\n */\n\nimport http from 'http';\nimport { existsSync, readFileSync, unlinkSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { bearerHeaderValue, clearDaemonToken, readDaemonToken } from './daemonToken';\n\nexport const DEFAULT_DAEMON_PORT = 3742;\n\n/**\n * The daemon contract's number, answered by `GET /api/server` and compared by\n * a client before it drives a daemon it did not start (ADR-0063 H3). Raise it\n * whenever a body in `daemonContract.ts` or a socket frame changes in a way an\n * older client or daemon would misread, and whenever a client comes to need a\n * route, or a value on an existing route, that an older daemon lacks or\n * refuses: the same contract attaches, so such a client would drive that\n * daemon into a 404 or a refusal it cannot tell from a real one. A field only\n * added, which an older side ignores or does without, need not.\n *\n * 2: the desktop's card edits go to `plans.cardEdit`, which no contract-1\n * daemon serves.\n * 3: the desktop's Explorer reads the workspace folder itself, as repo `.`,\n * which a contract-2 daemon refuses in a folder that is not a repository.\n */\nexport const DAEMON_CONTRACT = 3;\n\n// Paths are read at call time, not import time: a test (and a shell that\n// re-exports HOME) changes the home directory after this module loads.\n\n/**\n * One PID file per port so a second daemon doesn't clobber the first one's\n * entry (and `stop --server --port N` kills the daemon the user meant).\n */\nexport function daemonPidFilePath(port: number): string {\n return pidFileIn(globalDataDir(), port);\n}\n\n/**\n * Pre-`.ordewell` install: a daemon spawned by old code wrote its PID file\n * here, so a stop falls back to it rather than orphaning that daemon behind a\n * path it doesn't know moved.\n */\nexport function legacyDaemonPidFilePath(port: number): string {\n return pidFileIn(join(homedir(), '.config', 'ordewell'), port);\n}\n\nfunction pidFileIn(dir: string, port: number): string {\n return port === DEFAULT_DAEMON_PORT ? join(dir, 'server.pid') : join(dir, `server-${port}.pid`);\n}\n\nexport function daemonLogPath(): string {\n return join(globalDataDir(), 'server.log');\n}\n\n/** The PID a file names, or undefined when it is missing or not a positive integer. */\nexport function readPidFile(file: string): number | undefined {\n try {\n const pid = parseInt(readFileSync(file, 'utf8').trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Which daemon a client should talk to: an explicit port, else ORDEWELL_PORT,\n * else the default. Lets a client target an isolated second daemon instead of\n * whatever is already on 3742.\n */\nexport function resolveDaemonPort(\n explicit?: string | number,\n env: NodeJS.ProcessEnv = process.env,\n): number {\n const parsedArg = typeof explicit === 'number' ? explicit : parseInt(explicit ?? '', 10);\n if (Number.isInteger(parsedArg) && parsedArg > 0) return parsedArg;\n const fromEnv = parseInt(env.ORDEWELL_PORT ?? '', 10);\n if (!isNaN(fromEnv) && fromEnv > 0) return fromEnv;\n return DEFAULT_DAEMON_PORT;\n}\n\n/**\n * True when this error means \"nothing was listening\", as opposed to \"the\n * server answered badly\" or \"the connection broke mid-flight\".\n *\n * The distinction is what makes an automatic retry safe. ECONNREFUSED is\n * refused at the TCP handshake, so the request was never delivered and cannot\n * have been half-applied — replaying it is not a second execution. ECONNRESET\n * and EPIPE are deliberately *not* included: those can arrive after the server\n * read the request, so a retry could start a second plan or a second run.\n */\nexport function isConnectionRefused(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code;\n if (code === 'ECONNREFUSED') return true;\n // The code survives a normal reject, but not every layer preserves it —\n // `String(err)` through a worker boundary keeps only the message.\n const message = err instanceof Error ? err.message : String(err ?? '');\n return message.includes('ECONNREFUSED');\n}\n\nexport interface DaemonHttpResponse {\n status: number;\n data: string;\n}\n\n/**\n * A GET to the daemon on `port`, carrying the token file's bearer when there\n * is one. No `Origin` is ever sent: admission refuses any request with one.\n */\nexport function daemonHttpGet(\n port: number,\n path: string,\n timeoutMs: number = 2000,\n): Promise<DaemonHttpResponse> {\n return httpGetWithToken(port, path, timeoutMs, readDaemonToken(port));\n}\n\nfunction httpGetWithToken(port: number, path: string, timeoutMs: number, token: string | undefined): Promise<DaemonHttpResponse> {\n const headers: Record<string, string> = token ? { Authorization: bearerHeaderValue(token) } : {};\n return new Promise((resolvePromise, reject) => {\n const req = http.get({ host: '127.0.0.1', port, path, timeout: timeoutMs, headers }, (res) => {\n // Decoded once the body is whole: a multi-byte character split across two\n // chunks would otherwise turn into U+FFFD at the seam.\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer) => { chunks.push(chunk); });\n res.on('end', () => resolvePromise({ status: res.statusCode || 0, data: Buffer.concat(chunks).toString('utf8') }));\n });\n req.on('error', reject);\n req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });\n });\n}\n\nexport async function isDaemonRunning(port: number = DEFAULT_DAEMON_PORT): Promise<boolean> {\n try {\n const res = await daemonHttpGet(port, '/api/workspaces');\n // 401 still means a daemon owns this port. Reporting it as absent would\n // send a caller to spawn a second one that cannot bind; reporting it as\n // present lets the next real request answer with the token-file message.\n return res.status === 200 || res.status === 401;\n } catch {\n return false;\n }\n}\n\n/** What `GET /api/server` said about the process that owns the port. */\nexport interface DaemonIdentity {\n pid: number;\n /** The daemon's package version; absent from a daemon older than the field. */\n version?: string;\n /** The daemon contract it speaks (ADR-0063 H3); absent from a daemon older than the field. */\n contract?: number;\n /** Work is under way in a session it holds; absent from a daemon older than the field, which cannot say. */\n live?: boolean;\n}\n\nexport type DaemonProbe =\n | { kind: 'daemon'; identity: DaemonIdentity }\n /** Nothing owns the port: a stale PID file and token are safe to remove. */\n | { kind: 'unreachable' }\n /**\n * The daemon's own refusal of the token presented, or of none: it runs, but\n * for another user or install, or its token file has gone stale.\n */\n | { kind: 'unauthorized'; tokenPresented: boolean }\n /** Something owns the port, but it cannot prove which process it is. Never signal it. */\n | { kind: 'unverifiable' };\n\n// The daemon's 401 body names its token file; a stranger's 401 does not. That\n// is what tells \"a daemon that refuses us\" from \"some other server\".\nconst DAEMON_REFUSAL_MARK = 'bearer token';\n\n/**\n * Ask the daemon on `port` which process it is. A daemon older than this\n * route answers 404, and anything that is not a daemon answers whatever it\n * answers: both are `unverifiable`.\n */\nexport async function probeDaemon(port: number, timeoutMs: number = 2000): Promise<DaemonProbe> {\n let res: DaemonHttpResponse;\n let token = readDaemonToken(port);\n try {\n res = await httpGetWithToken(port, '/api/server', timeoutMs, token);\n if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {\n const fresh = readDaemonToken(port);\n // A startup can bind between reading the old credential and sending\n // this request. Recheck once with a changed token; a stable refusal stays one.\n if (fresh !== undefined && fresh !== token) {\n token = fresh;\n res = await httpGetWithToken(port, '/api/server', timeoutMs, token);\n }\n }\n } catch (err) {\n return isConnectionRefused(err) ? { kind: 'unreachable' } : { kind: 'unverifiable' };\n }\n if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {\n return { kind: 'unauthorized', tokenPresented: token !== undefined };\n }\n if (res.status !== 200) return { kind: 'unverifiable' };\n const identity = parseIdentity(res.data);\n return identity ? { kind: 'daemon', identity } : { kind: 'unverifiable' };\n}\n\nfunction parseIdentity(body: string): DaemonIdentity | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const fields = parsed as Partial<Record<'pid' | 'version' | 'contract' | 'live', unknown>>;\n const { pid, version, contract, live } = fields;\n if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return undefined;\n return {\n pid,\n ...(typeof version === 'string' ? { version } : {}),\n ...(typeof contract === 'number' && Number.isInteger(contract) ? { contract } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n}\n\nexport type DaemonStopOutcome =\n | { kind: 'no-pid-file' }\n /** The file named no PID; it and the token were removed. */\n | { kind: 'unreadable-pid-file' }\n /** Something owns the port but cannot name itself: nothing was signalled. */\n | { kind: 'unverifiable'; filePid: number }\n /** Nothing was running; the stale PID file (and token) were removed. */\n | { kind: 'stale' }\n | { kind: 'stopped'; pid: number; filePid: number };\n\n/**\n * Stop the daemon on `port` the way `ordewell stop --server` does: signal the\n * PID the daemon itself reports, and only when the PID file can be checked\n * against it, so a stale file never terminates an unrelated process.\n */\nexport async function stopDaemonAt(port: number = DEFAULT_DAEMON_PORT): Promise<DaemonStopOutcome> {\n let pidFile = daemonPidFilePath(port);\n if (!existsSync(pidFile) && existsSync(legacyDaemonPidFilePath(port))) pidFile = legacyDaemonPidFilePath(port);\n if (!existsSync(pidFile)) return { kind: 'no-pid-file' };\n\n const filePid = readPidFile(pidFile);\n if (!filePid) {\n removeQuietly(pidFile);\n clearDaemonToken(port);\n return { kind: 'unreadable-pid-file' };\n }\n\n const probe = await probeDaemon(port);\n if (probe.kind === 'unreachable') {\n removeQuietly(pidFile);\n // A daemon killed outright never ran its own shutdown, so its token file\n // may still be sitting there looking usable.\n clearDaemonToken(port);\n return { kind: 'stale' };\n }\n if (probe.kind !== 'daemon') {\n // A PID from an unverified file may now belong to any process the OS has\n // recycled it for. Refuse rather than risk killing something unrelated.\n return { kind: 'unverifiable', filePid };\n }\n\n const pid = probe.identity.pid;\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n const code = (err as Error & { code?: string }).code;\n if (code !== 'ESRCH') throw err;\n removeQuietly(pidFile);\n return { kind: 'stale' };\n }\n removeQuietly(pidFile);\n return { kind: 'stopped', pid, filePid };\n}\n\nfunction removeQuietly(file: string): void {\n try { unlinkSync(file); } catch { /* already gone */ }\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\n/**\n * Where Ordewell keeps machine-global data (settings, daemon tokens, caches,\n * credentials). A single home for everything not tied to a project directory,\n * so per-project state in `.ordewell/` and global state never collide.\n */\nexport function globalDataDir(): string {\n return path.join(os.homedir(), '.ordewell');\n}\n\nlet migrated = false;\n\n/**\n * One-time lift of a pre-`.ordewell` install's files into the new location.\n * Each file/dir is checked independently — old exists, new doesn't — rather\n * than gating the whole thing on \"new dir doesn't exist yet\". A machine that\n * migrated `settings.json` under an earlier release already has `globalDataDir()`\n * on disk, which would otherwise permanently skip lifting anything added to\n * this list later (`.env` did exactly that: real API keys stranded in the old\n * dir because the settings.json move had already made the new dir exist).\n *\n * Best-effort: a home it cannot write (read-only, full disk) must not take the\n * CLI down before `--help`, and the old file stays where it is.\n */\nexport function migrateOldConfigDir(): void {\n if (migrated) return;\n migrated = true;\n\n const oldDir = path.join(os.homedir(), '.config', 'ordewell');\n if (!fs.existsSync(oldDir)) return;\n const newDir = globalDataDir();\n\n const liftFile = (name: string): void => {\n const oldFile = path.join(oldDir, name);\n const newFile = path.join(newDir, name);\n if (!fs.existsSync(oldFile) || fs.existsSync(newFile)) return;\n try {\n fs.mkdirSync(newDir, { recursive: true });\n fs.copyFileSync(oldFile, newFile);\n } catch (err) {\n console.warn(`Could not move ${oldFile} to ${newFile}: ${String(err)}`);\n }\n };\n\n liftFile('settings.json');\n liftFile('.env');\n}\n","/**\n * The daemon's bearer token: minted at startup, written beside the per-port\n * process-id file, read by the CLI.\n *\n * Header validation defends against browsers and nothing else. This is what\n * stops another process running as the same user — an install script in the\n * very repository the planner was pointed at, say — from driving the daemon\n * just because it can see the port.\n *\n * Both ends of the wire live here so the carrier encodings cannot drift: the\n * daemon extracts with the same functions the CLI attaches with.\n */\n\nimport { randomBytes, timingSafeEqual } from 'crypto';\nimport { readFileSync, unlinkSync } from 'fs';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { writePrivateFile } from './privateFile';\n\nconst BEARER_PREFIX = 'bearer ';\n\n/**\n * The subprotocol the token rides on during the WebSocket upgrade. A query\n * parameter would land in access logs and in `ps`; a subprotocol travels in a\n * request header like the HTTP `Authorization` it stands in for.\n */\nexport const DAEMON_TOKEN_SUBPROTOCOL_PREFIX = 'ordewell.token.';\n\n/**\n * Offered alongside the token subprotocol, and the one the server selects, so\n * the 101 response never echoes the secret back.\n */\nexport const DAEMON_SUBPROTOCOL = 'ordewell.v1';\n\nfunction configDir(): string {\n return globalDataDir();\n}\n\n/**\n * One token file per port, with no default-port special case: unlike the\n * process-id file there is no legacy name to preserve, and naming every file\n * after its port is what stops a second daemon clobbering the first's token.\n */\nexport function daemonTokenPath(port: number): string {\n return join(configDir(), `server-${port}.token`);\n}\n\n/**\n * Mint this daemon's token and hand it off through the filesystem.\n *\n * The write goes through `writePrivateFile` rather than a plain write because\n * `mode` is ignored when the file already exists: writing over a pre-created\n * file would leave the token at whatever permissions that file already had, and\n * an existing symlink would carry the write somewhere else entirely. The helper\n * writes a fresh 0600 temp file and renames it into place, so neither applies.\n */\nexport function mintDaemonToken(port: number): { token: string; file: string } {\n const token = randomBytes(32).toString('base64url');\n const file = daemonTokenPath(port);\n writePrivateFile(file, token);\n return { token, file };\n}\n\n/** The token a client should present to the daemon on `port`, if one has been minted. */\nexport function readDaemonToken(port: number): string | undefined {\n try {\n const token = readFileSync(daemonTokenPath(port), 'utf8').trim();\n return token === '' ? undefined : token;\n } catch {\n return undefined;\n }\n}\n\n/** Best-effort cleanup on shutdown, so a dead daemon leaves no usable-looking token behind. */\nexport function clearDaemonToken(port: number): void {\n try {\n unlinkSync(daemonTokenPath(port));\n } catch {\n // Already gone, or never written.\n }\n}\n\n/** The `Authorization` header value for HTTP requests. */\nexport function bearerHeaderValue(token: string): string {\n return `Bearer ${token}`;\n}\n\n/** What a client offers on the upgrade: the real subprotocol first, the token second. */\nexport function tokenSubprotocols(token: string): string[] {\n return [DAEMON_SUBPROTOCOL, `${DAEMON_TOKEN_SUBPROTOCOL_PREFIX}${token}`];\n}\n\nexport interface TokenCarriers {\n /** `Authorization: Bearer <token>` — the HTTP carrier. */\n authorization?: string | null;\n /** `Sec-WebSocket-Protocol` — the upgrade carrier. */\n secWebSocketProtocol?: string | null;\n}\n\n/** Pull the token out of whichever carrier it arrived on. */\nexport function extractPresentedToken(carriers: TokenCarriers): string | undefined {\n const authorization = carriers.authorization;\n if (authorization && authorization.toLowerCase().startsWith(BEARER_PREFIX)) {\n const value = authorization.slice(BEARER_PREFIX.length).trim();\n if (value !== '') return value;\n }\n\n for (const offered of (carriers.secWebSocketProtocol ?? '').split(',')) {\n const value = offered.trim();\n if (!value.startsWith(DAEMON_TOKEN_SUBPROTOCOL_PREFIX)) continue;\n const token = value.slice(DAEMON_TOKEN_SUBPROTOCOL_PREFIX.length);\n if (token !== '') return token;\n }\n\n return undefined;\n}\n\n/** Constant-time comparison, so a wrong token leaks no information about the right one. */\nexport function tokensMatch(presented: string | undefined, expected: string): boolean {\n if (presented === undefined) return false;\n const a = Buffer.from(presented, 'utf8');\n const b = Buffer.from(expected, 'utf8');\n // timingSafeEqual throws on a length mismatch; the length is not the secret.\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n","import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as os from 'os';\nimport * as path from 'path';\n\nconst execAsync = promisify(exec);\n\n/**\n * GUI-launched processes (the VS Code extension host, a desktop-spawned web\n * server) often inherit a minimal PATH that misses user-level install dirs\n * (~/.local/bin, ~/.opencode/bin, nvm shims, …), so spawning `claude` or\n * `opencode` fails even though the user has them installed. This module\n * resolves an augmented PATH once per process: the interactive login shell's\n * PATH (which runs the user's profile, covering nvm/volta/asdf and friends)\n * merged over the current PATH, plus the well-known per-user bin dirs as a\n * final safety net when the login shell itself can't be queried. On Windows\n * there is no login shell to query, so the well-known dirs are the whole net —\n * see {@link windowsBinDirs}.\n *\n * {@link withPath} is the other half: handing the resolved PATH to a child\n * without accidentally giving it two.\n */\n\nconst LOGIN_SHELL_TIMEOUT_MS = 5000;\nconst PATH_MARKER = '__ORDEWELL_PATH__';\n\ntype ExecFn = (command: string, options?: { timeout?: number }) => Promise<{ stdout: string }>;\n\nconst defaultExec: ExecFn = async (command, options) => {\n const { stdout } = await execAsync(command, options);\n return { stdout: String(stdout) };\n};\n\nfunction posixBinDirs(): string[] {\n const home = os.homedir();\n return [\n path.join(home, '.local', 'bin'),\n path.join(home, '.opencode', 'bin'),\n path.join(home, '.claude', 'bin'),\n path.join(home, '.bun', 'bin'),\n path.join(home, '.volta', 'bin'),\n path.join(home, '.npm-global', 'bin'),\n path.join(home, 'bin'),\n '/usr/local/bin',\n '/opt/homebrew/bin',\n ];\n}\n\n/**\n * The Windows counterpart of {@link posixBinDirs}. There is no login shell to\n * ask on Windows, so this list is the only safety net when a runner was\n * installed after the host process started (the registry PATH a GUI-launched\n * VS Code inherited is a snapshot from launch time) or by an installer that\n * writes its own directory rather than amending PATH.\n *\n * The three built-in runners can each arrive by several routes, and the list\n * has to cover all of them or the picker greys out a CLI the user just\n * installed:\n *\n * - **PowerShell one-liner installers.** `irm https://claude.ai/install.ps1 |\n * iex` writes a native `claude.exe` to `%USERPROFILE%\\.local\\bin`, and\n * OpenCode's writes to `%USERPROFILE%\\.opencode\\bin`. `.local\\bin` was the\n * conspicuous omission — it is in {@link posixBinDirs}, where the same\n * installer puts the same binary, and its absence here meant the officially\n * documented Windows install of the flagship runner was the one Ordewell\n * could not find.\n * - **Node package managers.** npm's global prefix, and pnpm's and Yarn's,\n * which are not under it.\n * - **Windows package managers.** Scoop and Chocolatey shim directories, and\n * WinGet's `Links` folder for portable packages (distinct from\n * `WindowsApps`, which is MSIX only).\n * - **Version managers.** Volta spells its home `%LOCALAPPDATA%\\Volta` here,\n * not `~/.volta` as it does on POSIX.\n */\nfunction windowsBinDirs(env: NodeJS.ProcessEnv, home: string): string[] {\n const join = (...parts: string[]) => path.win32.join(...parts);\n const under = (base: string | undefined, ...parts: string[]) => (base ? [join(base, ...parts)] : []);\n const appData = env.APPDATA;\n const localAppData = env.LOCALAPPDATA;\n const programData = env.ProgramData;\n\n return [\n // Native per-user installers, PowerShell-driven and otherwise.\n join(home, '.local', 'bin'),\n join(home, '.opencode', 'bin'),\n join(home, '.claude', 'bin'),\n join(home, '.codex', 'bin'),\n ...under(localAppData, 'Programs', 'claude'),\n\n // Node package managers. npm's global prefix is `%APPDATA%\\npm`; the\n // literal spelling is kept as a fallback for a host that does not export\n // APPDATA (a service account, a stripped CI container).\n ...under(appData, 'npm'),\n join(home, 'AppData', 'Roaming', 'npm'),\n ...under(localAppData, 'pnpm'),\n ...under(localAppData, 'Yarn', 'bin'),\n join(home, '.bun', 'bin'),\n\n // Windows package managers.\n join(home, 'scoop', 'shims'),\n ...under(env.SCOOP, 'shims'),\n ...under(env.SCOOP_GLOBAL ?? programData, 'scoop', 'shims'),\n ...under(programData, 'chocolatey', 'bin'),\n // WinGet portable packages land here; `WindowsApps` only ever holds MSIX\n // aliases, so both are needed and neither substitutes for the other.\n ...under(localAppData, 'Microsoft', 'WinGet', 'Links'),\n ...under(localAppData, 'Microsoft', 'WindowsApps'),\n\n // Version managers. Volta's Windows home is not the POSIX `~/.volta`.\n ...under(localAppData, 'Volta', 'bin'),\n join(home, '.volta', 'bin'),\n ];\n}\n\n/**\n * Exported for test: the Windows arm cannot be exercised from a Linux CI box\n * through {@link augmentedPath}, which reads `process.platform` and the real\n * environment. Production always calls it through the no-argument form.\n */\nexport function wellKnownBinDirs(deps: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; home?: string } = {}): string[] {\n const platform = deps.platform ?? process.platform;\n if (platform !== 'win32') return posixBinDirs();\n return [...new Set(windowsBinDirs(deps.env ?? process.env, deps.home ?? os.homedir()))];\n}\n\nasync function loginShellPath(execImpl: ExecFn): Promise<string | null> {\n if (process.platform === 'win32') return null;\n const shell = process.env.SHELL || '/bin/sh';\n try {\n // Markers isolate $PATH from any profile noise (motd, echo in .zprofile…).\n const { stdout } = await execImpl(\n `${shell} -l -c 'echo \"${PATH_MARKER}\\${PATH}${PATH_MARKER}\"'`,\n { timeout: LOGIN_SHELL_TIMEOUT_MS },\n );\n const match = stdout.match(new RegExp(`${PATH_MARKER}([^\\\\n]*)${PATH_MARKER}`));\n return match?.[1] || null;\n } catch {\n return null;\n }\n}\n\nlet cachedPath: Promise<string> | null = null;\n\n/**\n * The augmented PATH for spawning user-installed CLI tools. Resolved once per\n * process and cached (the login shell query costs ~50-200ms).\n */\nexport function augmentedPath(execImpl: ExecFn = defaultExec): Promise<string> {\n if (!cachedPath) {\n cachedPath = (async () => {\n const segments: string[] = [];\n const push = (p: string | null | undefined) => {\n if (!p) return;\n for (const seg of p.split(path.delimiter)) {\n if (seg && !segments.includes(seg)) segments.push(seg);\n }\n };\n push(process.env.PATH);\n push(await loginShellPath(execImpl));\n for (const dir of wellKnownBinDirs()) push(dir);\n return segments.join(path.delimiter);\n })();\n }\n return cachedPath;\n}\n\n/** Test seam: drop the per-process cache so the next call re-resolves. */\nexport function clearAugmentedPathCache(): void {\n cachedPath = null;\n}\n\n/**\n * The value `env` gives `name`, read as `platform` reads it: on Windows a name\n * in any case is the same variable, and the last spelling is the one\n * {@link withPath} keeps.\n */\nexport function envValue(env: Readonly<Record<string, string | undefined>>, name: string, platform: NodeJS.Platform = process.platform): string | undefined {\n if (platform !== 'win32') return env[name];\n const wanted = name.toLowerCase();\n let found: string | undefined;\n for (const [key, value] of Object.entries(env)) if (key.toLowerCase() === wanted) found = value;\n return found;\n}\n\n/**\n * Build a child environment whose PATH is `resolvedPath`, with exactly one\n * PATH-ish key in it.\n *\n * `{ ...process.env, PATH }` is the obvious spelling and it is wrong on\n * Windows. Node's `process.env` is a case-insensitive proxy, but spreading it\n * yields the OS's actual casing — `Path` — so adding `PATH` produces an\n * environment block carrying both. Which one the child sees is undefined, and\n * the loser is silently discarded. Every existing site passed the same value\n * under both keys, so the bug was latent rather than live; this makes it\n * impossible instead of unlikely.\n */\nexport function withPath(\n base: NodeJS.ProcessEnv,\n resolvedPath: string,\n overrides: Record<string, string> = {},\n platform: NodeJS.Platform = process.platform,\n): NodeJS.ProcessEnv {\n // Windows names a variable in any case, and Node hands a child only the first\n // spelling in sort order, so a host's `FOO` would silently beat an override's\n // `foo`: a later spelling has to replace an earlier one, not sit beside it,\n // whether the earlier came from `base` or from `overrides` itself.\n const name = platform === 'win32' ? (key: string) => key.toLowerCase() : (key: string) => key;\n const entries = new Map<string, [string, string | undefined]>();\n // Both sources are filtered, not just `base`: an `overrides` map carrying its\n // own PATH is exactly how the duplicate reappears.\n for (const source of [base, overrides]) {\n for (const [key, value] of Object.entries(source)) {\n if (key.toLowerCase() === 'path') continue;\n entries.set(name(key), [key, value]);\n }\n }\n const env: NodeJS.ProcessEnv = Object.fromEntries(entries.values());\n // Windows canonically spells it `Path`; POSIX requires `PATH`. Matching the\n // platform keeps anything downstream that reads the raw block unsurprised.\n env[platform === 'win32' ? 'Path' : 'PATH'] = resolvedPath;\n return env;\n}\n","/**\n * A dotted numeric version, compared the way a harness reports it: `2.1.304`.\n * A missing component counts as zero, so `2.1` and `2.1.0` are the same\n * version, and a `v` prefix is not part of it. A prerelease (`2.1.304-beta`)\n * sorts before the release it names, so a build the live checks did not cover\n * is never mistaken for the checked one.\n */\ninterface Version {\n numbers: number[];\n /** Everything after the first `-`, without the build suffix; null for a release. */\n prerelease: string | null;\n}\n\nfunction parse(version: string): Version | null {\n const match = /^v?(\\d+(?:\\.\\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/i.exec(version.trim());\n if (!match) return null;\n return { numbers: match[1].split('.').map(Number), prerelease: match[2] ?? null };\n}\n\n/** The numeric components of a version, or null when it cannot be read. */\nexport function parseVersion(version: string): number[] | null {\n return parse(version)?.numbers ?? null;\n}\n\n/** Negative, zero or positive as `a` is older than, the same as, or newer than `b`; an unreadable version sorts oldest. */\nexport function compareVersions(a: string, b: string): number {\n const left = parse(a);\n const right = parse(b);\n if (!left || !right) return left ? 1 : right ? -1 : 0;\n const length = Math.max(left.numbers.length, right.numbers.length);\n for (let i = 0; i < length; i++) {\n const one = left.numbers[i] ?? 0;\n const other = right.numbers[i] ?? 0;\n if (one !== other) return one < other ? -1 : 1;\n }\n if (left.prerelease === right.prerelease) return 0;\n if (left.prerelease === null) return 1;\n if (right.prerelease === null) return -1;\n return left.prerelease < right.prerelease ? -1 : 1;\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { processAlive } from './processTree';\nimport { getSessionsDir, idSegment } from './sessionDir';\n\n/**\n * A session's lease file as any process reads it (ADR-0049): the record a\n * host writes, and the judgement of whether that host still lives. The hosts\n * themselves take and refresh it in `services/sessionLease`; this half is\n * apart so a client that is no host can read it through `daemon-client`.\n */\n\n/**\n * A lease not refreshed for this long is stale: its holder is gone, or its pid\n * now names another process. Several heartbeats, so a host whose event loop is\n * busy for a moment keeps its session.\n */\nexport const LEASE_STALE_MS = 60_000;\n\n/**\n * What kind of process a host is, for the words a refusal names it in and the\n * surface the planner is told its user has. `ownerPid` is the TUI a private\n * daemon serves; `app` marks the daemon the desktop app forked.\n */\nexport type LeaseHostKind =\n | { kind: 'daemon'; port: number; ownerPid?: number; app?: 'desktop' }\n | { kind: 'vscode' };\n\n/** A session's lease as its file records it. */\nexport interface SessionLeaseRecord {\n /** Minted once per host, so a restarted process at a reused pid is not mistaken for the holder. */\n hostId: string;\n pid: number;\n host?: LeaseHostKind;\n /** When this host took the lease. */\n since: string;\n /** Refreshed every heartbeat; stale past {@link LEASE_STALE_MS}. */\n heartbeatAt: string;\n /**\n * The process groups of the runners the holder had started and not seen\n * end. A host killed outright cannot stop them, and they go on writing in\n * the session's worktrees, so a takeover waits for them.\n */\n runnerGroups: number[];\n /**\n * Whether the holder's run is live: an attempt at work, a start pending, a\n * landing or Merge all under way. Much of that is only in the holder's\n * memory, so it says it here, for another host's landing interlock\n * (ADR-0062 G7). Absent from a holder that predates it.\n */\n runLive?: boolean;\n}\n\nconst LEASE_FILE = 'lease.json';\n\n/** A root session's lease file; a child writes none (ADR-0055 D13). */\nexport function leaseFile(sessionId: string, workspace: string): string {\n return path.join(getSessionsDir(workspace), idSegment(sessionId), LEASE_FILE);\n}\n\nfunction isRecord(value: unknown): value is SessionLeaseRecord {\n if (typeof value !== 'object' || value === null) return false;\n const r = value as Record<string, unknown>;\n return typeof r.hostId === 'string' && typeof r.pid === 'number' && typeof r.since === 'string'\n && typeof r.heartbeatAt === 'string' && Array.isArray(r.runnerGroups) && r.runnerGroups.every((g) => typeof g === 'number');\n}\n\n/** The record on disk; null when there is none, or none any host could have written (every write is a rename). */\nexport function readLeaseRecord(file: string): SessionLeaseRecord | null {\n let raw: string;\n try {\n raw = fs.readFileSync(file, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/** Whether the host that wrote `record` lives, judged by its heartbeat and its pid. */\nexport function holderLives(record: SessionLeaseRecord, now: number, alive: (pid: number) => boolean): boolean {\n const beat = Date.parse(record.heartbeatAt);\n if (Number.isNaN(beat) || now - beat > LEASE_STALE_MS) return false;\n return alive(record.pid);\n}\n\nexport interface LiveHolderProbes {\n now?: () => number;\n alive?: (pid: number) => boolean;\n}\n\n/**\n * The host that holds `sessionId` in `workspace` now, or null when none does.\n * For a client that holds no lease of its own and only needs to know whom to\n * reach: it does not weigh orphaned runners, which only a host taking over must.\n */\nexport function readLiveHolder(sessionId: string, workspace: string, probes: LiveHolderProbes = {}): SessionLeaseRecord | null {\n const record = readLeaseRecord(leaseFile(sessionId, workspace));\n if (!record) return null;\n return holderLives(record, (probes.now ?? Date.now)(), probes.alive ?? processAlive) ? record : null;\n}\n","import { ChildProcess, execFile, spawn as spawnProcess } from 'child_process';\nimport type { Socket } from 'net';\n\n/**\n * Stopping an agent process, on every platform.\n *\n * POSIX gets SIGTERM, then SIGKILL after a grace period — sent to the runner's\n * whole process group when it was started by {@link spawnInOwnGroup}, because\n * the direct child is a CLI and what kept running after Stop was everything it\n * had started: shells, MCP servers, test runs, dev servers. Windows has no signals — `ChildProcess.kill` calls TerminateProcess\n * on the direct child only — and on Windows the direct child is frequently not\n * the agent. A `claude.cmd` shim launched through cmd.exe puts an interpreter\n * between Ordewell and the `node cli.js` doing the work, so terminating the child\n * left the real agent running: still holding the workspace, still spending the\n * user's subscription, invisible to the surface that thought it had stopped.\n * `taskkill /T` walks the tree instead.\n *\n * Both paths are best-effort and idempotent by construction. A process that has\n * already exited is not an error here — every caller is on a dispose path.\n */\n\n/** Grace period between the polite stop and the forced one. */\nconst HARD_KILL_DELAY_MS = 5000;\n\nfunction isNoSuchProcess(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ESRCH';\n}\n\n/**\n * Whether `proc` has reported its own end. A process killed by a signal\n * reports `exitCode` null and `signalCode` set, and is as gone as one that\n * exited with a code. Only a reported value counts: an object that reports\n * neither is treated as running — the cost of a redundant kill is nothing,\n * the cost of skipping a live one is an orphaned agent.\n */\nfunction hasExited(proc: ChildProcess): boolean {\n return typeof proc.exitCode === 'number' || typeof proc.signalCode === 'string';\n}\n\nexport interface KillTreeDeps {\n platform?: NodeJS.Platform;\n /** Runs `taskkill`. Injected so the Windows path is testable off Windows. */\n execFileImpl?: (file: string, args: string[], cb: (err: Error | null) => void) => void;\n /** Schedules the forced kill. Injected so tests need no timers. */\n setTimeoutImpl?: (fn: () => void, ms: number) => { unref?: () => void };\n clearTimeoutImpl?: (handle: unknown) => void;\n /** Signals a pid, or a process group as its negated id. Injected so the group path needs no real processes. */\n killImpl?: (pid: number, signal: NodeJS.Signals | 0) => void;\n}\n\n/** Processes {@link spawnInOwnGroup} made group leaders. */\nconst groupLeaders = new WeakSet<ChildProcess>();\n/** Leaders already signalled: a group signal leaves `proc.killed` false, so it cannot say. */\nconst stopping = new WeakSet<ChildProcess>();\n/**\n * Groups led by a runner, by id, for the host's teardown. Kept while the group\n * still has members, which a leader's exit does not end: a runner that crashes\n * leaves its shells and dev servers behind, and those are what teardown has to\n * reach. Dropped when the group is empty (its id is recyclable then, and no\n * longer ours to vouch for) or when {@link killTree} takes it over.\n */\nconst ownGroups = new Map<number, ChildProcess>();\nlet hostTeardownHooked = false;\n/** What stops each runner group if the host dies without running any of its code; see {@link watchForHostDeath}. */\nconst hostWatches = new Map<number, ChildProcess>();\n/** Told of each runner group as it starts, so a session lease records it at once (ADR-0049). */\nconst groupStartListeners = new Set<() => void>();\n/** What else goes with the host: see {@link onHostTeardown}. */\nconst teardownListeners = new Set<() => void>();\n\n/**\n * Start a runner as the leader of a new process group, so {@link killTree}\n * reaches everything it starts. `spawn` is handed the `detached` flag to pass\n * to Node, which on POSIX is what makes a child a group (and session) leader.\n * Stdio pipes and the host's event loop are unaffected; only `unref` changes\n * the latter, and nothing here calls it.\n *\n * Not on Windows: there `detached` gives the child a console of its own, and\n * `taskkill /T` already walks the tree.\n */\nexport function spawnInOwnGroup(spawn: (detached: boolean) => ChildProcess, platform: NodeJS.Platform = process.platform): ChildProcess {\n if (platform === 'win32') return spawn(false);\n const proc = spawn(true);\n const pgid = proc.pid;\n // No pid: the spawn failed, and its 'error' event reports that.\n if (typeof pgid !== 'number') return proc;\n groupLeaders.add(proc);\n ownGroups.set(pgid, proc);\n if (proc instanceof ChildProcess) watchForHostDeath(pgid);\n // The leader's exit does not end the group: the shells, MCP servers and dev\n // servers it started outlive it, and those are exactly what Stop and host\n // teardown still have to reach. The entry is dropped only once the group is\n // empty — an id with no members left can be recycled, and is no longer ours\n // to signal.\n proc.once('exit', () => { if (!groupHasMembers(pgid)) forgetGroup(proc, pgid); });\n hookHostTeardown();\n for (const listener of groupStartListeners) listener();\n return proc;\n}\n\n/**\n * Stop `pgid` when this host is gone, however it went. SIGKILL and a crash run\n * none of its code, so nothing in it can do this, and a runner in a group of\n * its own would go on editing, committing and spending with nobody to see\n * (ADR-0049 L3). A shell waits on a pipe only this host writes: the kernel\n * closes that as the host dies, and the shell stops the group as `killTree`\n * would. A line down the pipe is a host going politely, which has asked already\n * and cannot stay for the forced stop, so that one is all the shell owes. Started\n * in `/` so no worktree is held open.\n */\nfunction watchForHostDeath(pgid: number): void {\n const group = `-- -${pgid}`;\n const seconds = HARD_KILL_DELAY_MS / 1000;\n const stop = `read _ || kill -s TERM ${group} 2>/dev/null; i=0; while [ \"$i\" -lt ${seconds} ] && kill -s 0 ${group} 2>/dev/null; do sleep 1; i=$((i + 1)); done; kill -s 0 ${group} 2>/dev/null && kill -s KILL ${group} 2>/dev/null`;\n const watch = spawnProcess('/bin/sh', ['-c', stop], { detached: true, cwd: '/', stdio: ['pipe', 'ignore', 'ignore'] });\n // No shell to watch with leaves the runner as it was; the lease still names it.\n watch.on('error', () => { hostWatches.delete(pgid); });\n watch.stdin?.on('error', () => undefined);\n (watch.stdin as Socket | null)?.unref();\n watch.unref();\n hostWatches.set(pgid, watch);\n}\n\nfunction endHostWatch(pgid: number): void {\n hostWatches.get(pgid)?.kill('SIGKILL');\n hostWatches.delete(pgid);\n}\n\n/**\n * The process groups this host's runners lead that still have members. A\n * session lease records them (ADR-0049): the teardown below cannot run for a\n * host killed outright, and {@link watchForHostDeath} may not have finished as\n * a new host looks. Asked on every heartbeat, which is also where a group that\n * outlived its leader and has since emptied is let go.\n */\nexport function runnerGroups(): number[] {\n for (const [pgid, proc] of ownGroups) {\n if (hasExited(proc) && !groupHasMembers(pgid)) forgetGroup(proc, pgid);\n }\n return [...ownGroups.keys()];\n}\n\n/** Hear of each runner group {@link spawnInOwnGroup} starts; the returned function stops it. */\nexport function onRunnerGroupStarted(listener: () => void): () => void {\n groupStartListeners.add(listener);\n return () => { groupStartListeners.delete(listener); };\n}\n\n/**\n * Stop something else as the host goes, with its runner groups but not among\n * them: {@link runnerGroups} never names it, so no lease is held by it. Here\n * rather than in a hook of the caller's, because two signal hooks would each\n * read the other as the host's own handler, and neither would end the host.\n * The returned function stops it being called. Nothing runs for a host killed\n * outright, as for the groups.\n */\nexport function onHostTeardown(stop: () => void): () => void {\n teardownListeners.add(stop);\n hookHostTeardown();\n return () => { teardownListeners.delete(stop); };\n}\n\n/** Whether a process answers to `pid`: one owned by another user, which refuses the signal, is alive too. */\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Whether any process is left in the group `pgid` leads. */\nexport function groupAlive(pgid: number): boolean {\n return groupHasMembers(pgid);\n}\n\n/** Whether any process still answers to `pgid`, as `kill(2)` sees it. */\nfunction groupHasMembers(pgid: number, killImpl: (pid: number, signal: 0) => void = (pid, signal) => { process.kill(pid, signal); }): boolean {\n try {\n killImpl(-pgid, 0);\n return true;\n } catch (err) {\n return !isNoSuchProcess(err);\n }\n}\n\n/**\n * An empty group's id is recyclable, so it is no longer ours to signal: from\n * here on `proc` is an ordinary exited process to {@link killTree}.\n */\nfunction forgetGroup(proc: ChildProcess, pgid: number): void {\n if (ownGroups.get(pgid) === proc) ownGroups.delete(pgid);\n groupLeaders.delete(proc);\n endHostWatch(pgid);\n}\n\n/**\n * A detached runner has left the terminal's foreground group, so Ctrl-C (or a\n * closed terminal) no longer reaches it — the host has to pass that on to the\n * groups it leads. Polite only, and not again to a group already asked: a\n * host disposing its sessions on the way out has just sent SIGTERM, and a\n * second one reads to some CLIs as \"quit without cleaning up\".\n */\nfunction hookHostTeardown(): void {\n if (hostTeardownHooked) return;\n hostTeardownHooked = true;\n const stopAll = () => {\n for (const [pgid, leader] of ownGroups) {\n if (stopping.has(leader)) continue;\n if (hasExited(leader) && !groupHasMembers(pgid)) continue;\n try { process.kill(-pgid, 'SIGTERM'); } catch { /* already gone */ }\n }\n ownGroups.clear();\n for (const watch of hostWatches.values()) watch.stdin?.write('\\n');\n hostWatches.clear();\n for (const stop of teardownListeners) {\n try { stop(); } catch { /* already gone */ }\n }\n teardownListeners.clear();\n };\n process.on('exit', stopAll);\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {\n const onSignal = () => {\n stopAll();\n // A host with a handler of its own decides how to exit. One without was\n // relying on the default, which listening has replaced, so this listener\n // steps aside and the signal is raised again to end the host as before.\n if (process.listenerCount(signal) > 1) return;\n process.removeListener(signal, onSignal);\n process.kill(process.pid, signal);\n };\n process.on(signal, onSignal);\n }\n}\n\nfunction defaultExecFile(file: string, args: string[], cb: (err: Error | null) => void): void {\n execFile(file, args, (err) => cb(err ?? null));\n}\n\n/**\n * Terminate `proc` and everything it started.\n *\n * Returns immediately; the forced follow-up (SIGKILL, or `taskkill /F`) is\n * scheduled and unref'd, so a disposed session is never the reason the host\n * process refuses to exit.\n */\nexport function killTree(proc: ChildProcess | null, deps: KillTreeDeps = {}): void {\n if (!proc) return;\n\n const platform = deps.platform ?? process.platform;\n // A group leader is the exception: its group outlives it, so a crashed\n // runner's shells, dev servers and MCP servers are still there to stop even\n // though the runner is not. That case falls through to the group path below.\n if (!groupLeaders.has(proc) && (proc.killed || hasExited(proc))) return;\n\n const setTimeoutImpl = deps.setTimeoutImpl ?? ((fn, ms) => setTimeout(fn, ms) as unknown as { unref?: () => void });\n const clearTimeoutImpl = deps.clearTimeoutImpl ?? ((h) => clearTimeout(h as NodeJS.Timeout));\n\n if (platform === 'win32') {\n // No pid means the process never started; there is no tree to walk.\n if (typeof proc.pid !== 'number') return;\n const pid = proc.pid;\n const run = deps.execFileImpl ?? defaultExecFile;\n\n // `/T` is the whole point: without it this is the TerminateProcess call\n // that already failed to reach the agent. The unforced pass only asks a\n // window to close, so a console process — every runner — refuses it, and\n // is forced at once: left for the grace, it would go on writing to a\n // workspace the user has stopped it in, and holding it from removal.\n // `/F` follows on the timer too, for one that agreed and did not go.\n const force = () => run('taskkill', ['/pid', String(pid), '/T', '/F'], () => { /* already gone */ });\n // A pass that failed because the process had already gone forces nothing:\n // its pid may be another's by then.\n run('taskkill', ['/pid', String(pid), '/T'], (err) => { if (err && !hasExited(proc)) force(); });\n const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n return;\n }\n\n if (groupLeaders.has(proc) && typeof proc.pid === 'number') {\n if (stopping.has(proc)) return;\n const pgid = proc.pid;\n const killImpl = deps.killImpl ?? ((pid: number, signal: NodeJS.Signals | 0) => { process.kill(pid, signal); });\n // Never signal a group we can't vouch for. While the leader lives its pid\n // holds the id; once it is gone, only a member still in the group does,\n // and an empty group's id may already be a stranger's. So once the leader\n // has exited, every signal is preceded by asking.\n const vouched = () => !hasExited(proc) || groupHasMembers(pgid, killImpl);\n if (!vouched()) {\n forgetGroup(proc, pgid);\n return;\n }\n stopping.add(proc);\n // Taken over here, so the host's teardown and this path do not both signal\n // it (from here on `stopping`, not `ownGroups`, is what says so).\n ownGroups.delete(pgid);\n const signalGroup = (signal: NodeJS.Signals) => {\n try {\n killImpl(-pgid, signal);\n } catch {\n try { proc.kill(signal); } catch { /* already gone */ }\n }\n };\n signalGroup('SIGTERM');\n // Survives the leader's exit: what it started can outlive it, and a\n // process ignoring SIGTERM is exactly the one that does. Asked again when\n // it fires, so a group that emptied during the grace period is left alone;\n // a stranger taking the id between that probe and the signal is the\n // residual risk.\n const hardKill = setTimeoutImpl(() => {\n if (vouched()) signalGroup('SIGKILL');\n endHostWatch(pgid);\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n if (!hasExited(proc)) {\n proc.once('exit', () => { if (!groupHasMembers(pgid, killImpl)) clearTimeoutImpl(hardKill); });\n }\n return;\n }\n\n try {\n proc.kill('SIGTERM');\n const hardKill = setTimeoutImpl(() => {\n try { proc.kill('SIGKILL'); } catch { /* already gone */ }\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n } catch {\n // Process already gone — nothing to clean up.\n }\n}\n","import * as path from 'path';\nimport { getStateDir } from './fsHelpers';\n\n/**\n * Where sessions keep their state, apart from the store that reads it: a\n * client that is no host (the desktop app's main process) finds a session's\n * lease here without loading the plan model the store brings with it.\n */\n\nconst SESSIONS_SUBDIR = 'sessions';\n\nexport function getSessionsDir(baseDir?: string): string {\n return path.join(getStateDir(baseDir), SESSIONS_SUBDIR);\n}\n\n/**\n * A path segment for an id that came from outside — a session id from a URL,\n * a task id a planner wrote. A plain id is used as is; anything that could\n * climb out of its directory, or is not portable as a file name, is hex-encoded.\n */\nexport function idSegment(id: string): string {\n return /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/.test(id) ? id : `~${Buffer.from(id, 'utf-8').toString('hex')}`;\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport const STATE_DIR = '.ordewell';\n\nexport function ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Replace `filePath` with `content` in one step. Writing in place truncates\n * the old bytes first, so a crash, power loss or a full disk mid-write leaves\n * an empty or half-written file where the last good one was — silent loss of\n * the only copy, for a session or a saved plan. The bytes go to a fresh temp\n * file beside the target and a rename swaps it in; within one directory that\n * is atomic, so a reader sees the old file or the new one.\n */\nexport function writeFileAtomic(filePath: string, content: string): void {\n const dir = path.dirname(filePath);\n ensureDir(dir);\n // Same directory, so the rename stays on one filesystem; random, so the name\n // can never collide with another process writing the same file.\n const tempPath = path.join(dir, `.${path.basename(filePath)}.${randomUUID()}.tmp`);\n fs.writeFileSync(tempPath, content, { flag: 'wx' });\n try {\n fs.renameSync(tempPath, filePath);\n } catch (err) {\n try {\n fs.unlinkSync(tempPath);\n } catch {\n // Already gone; the rename error is the one worth reporting.\n }\n throw err;\n }\n}\n\nexport function getStateDir(baseDir?: string): string {\n return path.join(baseDir ?? process.cwd(), STATE_DIR);\n}\n\nconst IGNORE_FILE = '.gitignore';\n\n/**\n * Ignores the state directory's contents except this file and `skills/`, so a\n * project's skills are committed and reach every task worktree through git —\n * the bootstrap never links `.ordewell/` (ADR-0013). Plans and sessions stay\n * uncommittable without touching a file the developer wrote; editing their\n * root `.gitignore` would be the intrusive version of this.\n */\nexport const STATE_DIR_IGNORE = '*\\n!.gitignore\\n!skills/\\n!skills/**\\n';\n\n/** What older builds wrote: everything ignored, the rules file included. */\nconst LEGACY_IGNORES = new Set(['*', '*\\n']);\n\n/**\n * Idempotent, and never overwrites a file the developer customised (to commit\n * their plans deliberately, say). Only the exact legacy rule is upgraded.\n */\nexport function ensureStateDirIgnored(baseDir?: string): void {\n const dir = getStateDir(baseDir);\n ensureDir(dir);\n const file = path.join(dir, IGNORE_FILE);\n try {\n // `wx` rather than an existsSync check: two surfaces can save concurrently,\n // and the loser of that race must not clobber the winner's file.\n fs.writeFileSync(file, STATE_DIR_IGNORE, { flag: 'wx' });\n return;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n }\n if (LEGACY_IGNORES.has(fs.readFileSync(file, 'utf8'))) fs.writeFileSync(file, STATE_DIR_IGNORE);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,kBAAiB;AACjB,IAAAA,aAAqD;AACrD,gBAAwB;AACxB,IAAAC,eAAqB;;;ACZrB,WAAsB;AACtB,SAAoB;AAOb,SAAS,gBAAwB;AACtC,SAAY,UAAQ,WAAQ,GAAG,WAAW;AAC5C;;;ACGA,gBAAyC;AACzC,kBAAqB;AAWd,IAAM,kCAAkC;AAMxC,IAAM,qBAAqB;AAElC,SAAS,YAAoB;AAC3B,SAAO,cAAc;AACvB;AAOO,SAAS,gBAAgB,MAAsB;AACpD,aAAO,kBAAK,UAAU,GAAG,UAAU,IAAI,QAAQ;AACjD;AAmBO,SAAS,gBAAgB,MAAkC;AAChE,MAAI;AACF,UAAM,YAAQ,wBAAa,gBAAgB,IAAI,GAAG,MAAM,EAAE,KAAK;AAC/D,WAAO,UAAU,KAAK,SAAY;AAAA,EACpC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,iBAAiB,MAAoB;AACnD,MAAI;AACF,8BAAW,gBAAgB,IAAI,CAAC;AAAA,EAClC,QAAQ;AAAA,EAER;AACF;AAGO,SAAS,kBAAkB,OAAu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AAM;AAAA,EACR;AACA,MAAI;AACF,UAAM,SAAkB,KAAK,MAAM,GAAG;AACtC,WAAO,SAAS,MAAM,IAAI,SAAS;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,YAAY,QAA4B,KAAa,OAA0C;AAC7G,QAAM,OAAO,KAAK,MAAM,OAAO,WAAW;AAC1C,MAAI,OAAO,MAAM,IAAI,KAAK,MAAM,OAAO,eAAgB,QAAO;AAC9D,SAAO,MAAM,OAAO,GAAG;AACzB;AAYO,SAAS,eAAe,WAAmB,WAAmB,SAA2B,CAAC,GAA8B;AAC7H,QAAM,SAAS,gBAAgB,UAAU,WAAW,SAAS,CAAC;AAC9D,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,YAAY,SAAS,OAAO,OAAO,KAAK,KAAK,GAAG,OAAO,SAAS,YAAY,IAAI,SAAS;AAClG;","names":["import_fs","import_path","path","http","os","path","join","path","path","path"]}
@@ -22,7 +22,7 @@ import {
22
22
  stopDaemonAt,
23
23
  tokenSubprotocols,
24
24
  withPath
25
- } from "./chunk-MGMQKUIJ.mjs";
25
+ } from "./chunk-DFRDXOEG.mjs";
26
26
  export {
27
27
  DAEMON_CONTRACT,
28
28
  DAEMON_SUBPROTOCOL,
@@ -1,5 +1,5 @@
1
1
  import { ChildProcess } from 'child_process';
2
- import { aH as PlannerAllowlist, bb as RunnerId, aE as PlanStatus, ao as LegacyPlanState, aD as PlanState, O as HandoffCommit, af as IsolationRevertTask, ai as IsolationTaskRef, b7 as RevertCommand, bC as Task, ag as IsolationRun, bw as SkillsService, br as SkillInfo, a_ as RepoGroupLayout, Y as IWorktreeIsolation, a0 as IsolationHandoff, aC as PlanIsolation, ak as IsolationTaskStatus, bH as TaskIsolation, al as IsolationView, ab as IsolationRemoval, aO as PrepareIntent, aS as PreviousWork, a8 as IsolationOutcome, aX as RepairEvidence, bU as TreeSnapshot, bE as TaskDiffRead, bF as TaskDiffResult, a7 as IsolationMergeResult, an as LandedWork, b8 as RevertWatch, ae as IsolationRevertResult, bX as UsageRecord, bz as SubagentOutcome, bc as RunnerSessionCost, t as DiscoveredModel, b_ as VerificationCheck, bO as TaskSkillSnapshot, bj as ScriptBody, N as HandoffCheck } from './Task-CH1z4L3h.mjs';
2
+ import { aH as PlannerAllowlist, bb as RunnerId, aE as PlanStatus, ao as LegacyPlanState, aD as PlanState, O as HandoffCommit, af as IsolationRevertTask, ai as IsolationTaskRef, b7 as RevertCommand, bC as Task, ag as IsolationRun, bw as SkillsService, br as SkillInfo, a_ as RepoGroupLayout, Y as IWorktreeIsolation, a0 as IsolationHandoff, aC as PlanIsolation, ak as IsolationTaskStatus, bH as TaskIsolation, al as IsolationView, ab as IsolationRemoval, aO as PrepareIntent, aS as PreviousWork, a8 as IsolationOutcome, aX as RepairEvidence, bU as TreeSnapshot, bE as TaskDiffRead, bF as TaskDiffResult, a7 as IsolationMergeResult, an as LandedWork, b8 as RevertWatch, ae as IsolationRevertResult, bX as UsageRecord, bz as SubagentOutcome, bc as RunnerSessionCost, t as DiscoveredModel, b_ as VerificationCheck, bO as TaskSkillSnapshot, bj as ScriptBody, N as HandoffCheck } from './Task-TFPWtKoz.mjs';
3
3
  import { z } from 'zod/v4';
4
4
 
5
5
  /**
@@ -1093,6 +1093,19 @@ interface IFileSystem {
1093
1093
  taskShell?(site: TaskShellSite): TaskShell;
1094
1094
  }
1095
1095
 
1096
+ /**
1097
+ * Who made a tool call, as far as the runner's own request metadata says. It
1098
+ * is read for one purpose: leaving a delegate's reads out of the planner's
1099
+ * read limit (ADR-0068 R2). The model writes none of it, and it never decides
1100
+ * what a call may do: the envelope (ADR-0008) still does.
1101
+ */
1102
+ interface McpCaller {
1103
+ /** The runner says one of its subagents made the call. */
1104
+ subagent?: true;
1105
+ /** The runner's id for the tool use this call answers, for the harness to tie to the agent it announced. */
1106
+ toolUseId?: string;
1107
+ }
1108
+
1096
1109
  /** A subplanner's report (ADR-0057 R2): it passes a finding up only by reference, so nothing is reworded on the way, and only its token takes these. */
1097
1110
  declare const subplannerCompleteInput: z.ZodObject<{
1098
1111
  status: z.ZodEnum<{
@@ -1397,6 +1410,8 @@ type CheckpointAnswer = {
1397
1410
  interface McpToolContext {
1398
1411
  /** Aborts when the token is revoked or the caller cancels — a waiting handler must stop. */
1399
1412
  signal: AbortSignal;
1413
+ /** Who made the call, when the runner's request says (ADR-0068 R2). */
1414
+ caller?: McpCaller;
1400
1415
  }
1401
1416
  type Run<A> = (args: A, context: McpToolContext) => Promise<McpToolReply>;
1402
1417
  interface TaskToolHandler {
@@ -3156,6 +3171,7 @@ type AgentEvent =
3156
3171
  * `decided` marks a request already answered — by the adapter, as the
3157
3172
  * manifest says the task's mode does, or as a denial — so it is shown, never asked.
3158
3173
  * `ask` is what a planner's open request is for, in the envelope's terms.
3174
+ * `bySubagent` marks one the runner says a subagent of its own raised.
3159
3175
  */
3160
3176
  | {
3161
3177
  type: 'permission_request';
@@ -3165,6 +3181,7 @@ type AgentEvent =
3165
3181
  input?: Record<string, unknown>;
3166
3182
  suggestions?: unknown[];
3167
3183
  toolUseId?: string;
3184
+ bySubagent?: boolean;
3168
3185
  decided?: ApprovalDecision;
3169
3186
  ask?: PlannerAsk;
3170
3187
  }
@@ -3519,6 +3536,8 @@ interface AgentAdapter {
3519
3536
  }
3520
3537
  /** What an adapter adds to run a task rather than a planner (ADR-0018). */
3521
3538
  interface TaskModeAgentAdapter extends AgentAdapter {
3539
+ /** The size Ordewell set the task's runner to compact its context at, when it did (ADR-0057 R4). */
3540
+ readonly compactWindowTokens?: number;
3522
3541
  mcpAttached(sendFirstTurn?: () => Promise<unknown>): Promise<boolean | AttachState>;
3523
3542
  /**
3524
3543
  * Ask the running turn to stop, keeping the process and its session. Resolves
@@ -4076,6 +4095,12 @@ interface IRunnerSession {
4076
4095
  * runner nothing secret has none.
4077
4096
  */
4078
4097
  readonly secrets?: HeldSecrets;
4098
+ /**
4099
+ * The size, in tokens, at which Ordewell has set this runner to compact its
4100
+ * own context (ADR-0057 R4): a compaction at it is routine. Absent where
4101
+ * Ordewell sets none, so the runner compacts near its model's own window.
4102
+ */
4103
+ readonly compactWindowTokens?: number;
4079
4104
  onOutput(callback: (text: string) => void): void;
4080
4105
  onExit(callback: (code: number) => void): void;
4081
4106
  /** End the process at once. {@link stop} is how an attempt that is over lets it go. */
@@ -4413,4 +4438,4 @@ interface EventStore {
4413
4438
  close(): Promise<void>;
4414
4439
  }
4415
4440
 
4416
- export { type IRunner as $, AUTO_COMMANDS as A, type BashOptions as B, type CatalogModel as C, type CommandClassification as D, type CommandTier as E, ConsoleLogger as F, DENY_ALL as G, type DiscoveryCommand as H, type EditPlanArgs as I, type EventStore as J, type ExecutionBackend as K, type FetchAllProviderModelsOptions as L, type FindSymbolOptions as M, GIT_READONLY_SUBCOMMANDS as N, GREP_DEFAULT_HEAD_LIMIT as O, type GlobOptions as P, type GrepOptions as Q, type GrepOutputMode as R, type Guarantee as S, type GuaranteeReport as T, HeldSecrets as U, type HeldValue as V, type IApproval as W, type IConfig as X, type IFileSystem as Y, type ILogger as Z, type INotification as _, type AgentAdapter as a, type RevertRefusal as a$, type IRunnerSession as a0, type InvokedCommand as a1, type IsolatedExecution as a2, IsolationRunController as a3, type LeaseRecord as a4, type LeaseRepo as a5, type LeaseRequest as a6, type LeaseSpec as a7, LineBuffer as a8, type ListModelsArgs as a9, PLANNER_TOOLS as aA, type PlannerBackendId as aB, type PlannerModes as aC, type PlannerSandboxAvailability as aD, type PlannerSandboxDeps as aE, PlannerShellSandbox as aF, type PlannerStartOptions as aG, type PlannerTokenScope as aH, type PlannerToolHandler as aI, type PostArgs as aJ, type ProjectMcpServer as aK, type ProviderCredentialSource as aL, type ProviderModelLists as aM, type ProviderModelsResult as aN, type QueuedTaskMessage as aO, READ_ONLY_TASK_TOOLS as aP, REFUSED_COMMANDS as aQ, RESEARCH_READ_TOOLS as aR, type ReadFileOpts as aS, type ReadTaskArgs as aT, type ResearchShell as aU, type ResearchShellDeps as aV, type ResearchTokenScope as aW, type ResearchToolHandler as aX, type ReservedLease as aY, type RetryTaskArgs as aZ, type RevertPreviewTask as a_, type ListRunnersArgs as aa, type LoadSkillArgs as ab, type McpClientConfig as ac, type McpContact as ad, type McpCredential as ae, type McpRefusal as af, type McpTool as ag, type McpToolContext as ah, type McpToolReply as ai, type MessageTaskArgs as aj, ModelCatalog as ak, type ModelShortcut as al, type NodePath as am, type NotificationAction as an, ORCHESTRATOR_SHORTCUTS as ao, ORDEWELL_MCP_PATH as ap, ORDEWELL_MCP_SERVER_NAME as aq, type OneTaskArgs as ar, type OpenLease as as, type OrchestratorOption as at, OrdewellMcpServer as au, type OwnSealedRuns as av, type OwnerOnlyFile as aw, PLANNER_EXECUTION_TOOLS as ax, PLANNER_RESEARCH_AGENT as ay, PLANNER_SANDBOX_DOCS as az, type AgentAdapterFactory as b, type TaskWebReads as b$, type RevertRefusalReason as b0, type RevertScope as b1, type RunCommandArgs as b2, type RunPlanArgs as b3, type RunnerAuthSpec as b4, type RunnerAuthStatus as b5, type RunnerCommand as b6, type RunnerCommandKind as b7, type RunnerEntry as b8, type RunnerEnv as b9, type SkillLookup as bA, type SpawnFn as bB, type SpawnResearchAgentArgs as bC, type StandingDecision as bD, type StructuredEvent as bE, type StructuredTurnEnd as bF, type SubmitPlanArgs as bG, TASK_COMPLETE_TOOL as bH, TASK_COMPLETION_CONTRACT as bI, TASK_SEALED_LIMITS as bJ, TASK_TOOLS as bK, type TaskCompleteArgs as bL, type TaskDiffArgs as bM, type TaskMessageFrom as bN, type TaskModeAgentAdapter as bO, TaskModeUnsupportedError as bP, type TaskOutputArgs as bQ, type TaskQueryArgs as bR, type TaskRevertPreview as bS, type TaskRunCommandArgs as bT, type TaskRunnerConfig as bU, type TaskRunnerFlags as bV, type TaskShell as bW, type TaskShellSite as bX, type TaskStartOptions as bY, type TaskTokenScope as bZ, type TaskToolHandler as b_, type RunnerFeatures as ba, type RunnerLaunch as bb, type RunnerManifest as bc, type RunnerMcpServer as bd, type RunnerMode as be, type RunnerModelDiscovery as bf, type RunnerModelRef as bg, type RunnerPlacement as bh, RunnerRegistry as bi, SEALED_LIMITS as bj, SEARCH_EXCLUSIONS as bk, type SandboxBackend as bl, type SandboxInvocation as bm, type SandboxLaunch as bn, type SandboxLimits as bo, type SandboxProfile as bp, type ScriptExit as bq, type ScriptFullOutput as br, type ScriptRun as bs, type ScriptStatus as bt, type SealedAvailability as bu, type SealedRunOptions as bv, type SessionData as bw, type SessionMeta as bx, type ShellDialect as by, type ShellLaunch as bz, type AgentEvent as c, type ToolOutcome as c0, type TreeEvent as c1, type TreeFact as c2, type UsageLimitSignal as c3, approvalScopes as c4, classifyCommand as c5, clearPlannerSandboxCache as c6, clearResearchShellCache as c7, collectProviderCredentials as c8, defaultLogger as c9, saveChildSession as cA, saveSession as cB, sessionDataDir as cC, sharedMcpServer as cD, taskCompletionContract as cE, taskToolSet as cF, toApprovalDecision as cG, toOrchestratorOptions as cH, toolListing as cI, deleteSession as ca, effectiveApprovalMode as cb, enabledRunners as cc, fetchAllProviderModels as cd, findRunnerCommand as ce, getLatestSession as cf, grantScopeFor as cg, isGranted as ch, isRunnerApproval as ci, knownModelId as cj, listChildSessions as ck, listSessions as cl, loadChildSession as cm, loadSession as cn, loadSessionPlanState as co, mcpClientConfig as cp, ownerOnlyConfigFile as cq, parseApprovalModeSetting as cr, plannerToolSet as cs, researchShellWarning as ct, researchToolsPath as cu, resolveModelShortcut as cv, resolvePlannerSandbox as cw, resolveProvider as cx, resolveResearchShell as cy, resolveWithin as cz, type AgentProcessDeps as d, type AgentStartOptions as e, type AiProvider as f, type AllProviderModels as g, type AnswerApprovalArgs as h, type ApplyPatchArgs as i, type ApprovalAnswer as j, type ApprovalDecision as k, type ApprovalKind as l, type ApprovalMode as m, type ApprovalModeSetting as n, ApprovalPolicy as o, type ApprovalPolicyOptions as p, type ApprovalRequest as q, type ApprovalSource as r, type AttachState as s, type BoardAuthor as t, type BoardDraft as u, type BoardEntry as v, type BoardPost as w, type CheckpointAnswer as x, type CheckpointArgs as y, type ChildSessionPlace as z };
4441
+ export { type IRunner as $, AUTO_COMMANDS as A, type BashOptions as B, type CatalogModel as C, type CommandClassification as D, type CommandTier as E, ConsoleLogger as F, DENY_ALL as G, type DiscoveryCommand as H, type EditPlanArgs as I, type EventStore as J, type ExecutionBackend as K, type FetchAllProviderModelsOptions as L, type FindSymbolOptions as M, GIT_READONLY_SUBCOMMANDS as N, GREP_DEFAULT_HEAD_LIMIT as O, type GlobOptions as P, type GrepOptions as Q, type GrepOutputMode as R, type Guarantee as S, type GuaranteeReport as T, HeldSecrets as U, type HeldValue as V, type IApproval as W, type IConfig as X, type IFileSystem as Y, type ILogger as Z, type INotification as _, type AgentAdapter as a, type RevertPreviewTask as a$, type IRunnerSession as a0, type InvokedCommand as a1, type IsolatedExecution as a2, IsolationRunController as a3, type LeaseRecord as a4, type LeaseRepo as a5, type LeaseRequest as a6, type LeaseSpec as a7, LineBuffer as a8, type ListModelsArgs as a9, PLANNER_SANDBOX_DOCS as aA, PLANNER_TOOLS as aB, type PlannerBackendId as aC, type PlannerModes as aD, type PlannerSandboxAvailability as aE, type PlannerSandboxDeps as aF, PlannerShellSandbox as aG, type PlannerStartOptions as aH, type PlannerTokenScope as aI, type PlannerToolHandler as aJ, type PostArgs as aK, type ProjectMcpServer as aL, type ProviderCredentialSource as aM, type ProviderModelLists as aN, type ProviderModelsResult as aO, type QueuedTaskMessage as aP, READ_ONLY_TASK_TOOLS as aQ, REFUSED_COMMANDS as aR, RESEARCH_READ_TOOLS as aS, type ReadFileOpts as aT, type ReadTaskArgs as aU, type ResearchShell as aV, type ResearchShellDeps as aW, type ResearchTokenScope as aX, type ResearchToolHandler as aY, type ReservedLease as aZ, type RetryTaskArgs as a_, type ListRunnersArgs as aa, type LoadSkillArgs as ab, type McpCaller as ac, type McpClientConfig as ad, type McpContact as ae, type McpCredential as af, type McpRefusal as ag, type McpTool as ah, type McpToolContext as ai, type McpToolReply as aj, type MessageTaskArgs as ak, ModelCatalog as al, type ModelShortcut as am, type NodePath as an, type NotificationAction as ao, ORCHESTRATOR_SHORTCUTS as ap, ORDEWELL_MCP_PATH as aq, ORDEWELL_MCP_SERVER_NAME as ar, type OneTaskArgs as as, type OpenLease as at, type OrchestratorOption as au, OrdewellMcpServer as av, type OwnSealedRuns as aw, type OwnerOnlyFile as ax, PLANNER_EXECUTION_TOOLS as ay, PLANNER_RESEARCH_AGENT as az, type AgentAdapterFactory as b, type TaskToolHandler as b$, type RevertRefusal as b0, type RevertRefusalReason as b1, type RevertScope as b2, type RunCommandArgs as b3, type RunPlanArgs as b4, type RunnerAuthSpec as b5, type RunnerAuthStatus as b6, type RunnerCommand as b7, type RunnerCommandKind as b8, type RunnerEntry as b9, type ShellLaunch as bA, type SkillLookup as bB, type SpawnFn as bC, type SpawnResearchAgentArgs as bD, type StandingDecision as bE, type StructuredEvent as bF, type StructuredTurnEnd as bG, type SubmitPlanArgs as bH, TASK_COMPLETE_TOOL as bI, TASK_COMPLETION_CONTRACT as bJ, TASK_SEALED_LIMITS as bK, TASK_TOOLS as bL, type TaskCompleteArgs as bM, type TaskDiffArgs as bN, type TaskMessageFrom as bO, type TaskModeAgentAdapter as bP, TaskModeUnsupportedError as bQ, type TaskOutputArgs as bR, type TaskQueryArgs as bS, type TaskRevertPreview as bT, type TaskRunCommandArgs as bU, type TaskRunnerConfig as bV, type TaskRunnerFlags as bW, type TaskShell as bX, type TaskShellSite as bY, type TaskStartOptions as bZ, type TaskTokenScope as b_, type RunnerEnv as ba, type RunnerFeatures as bb, type RunnerLaunch as bc, type RunnerManifest as bd, type RunnerMcpServer as be, type RunnerMode as bf, type RunnerModelDiscovery as bg, type RunnerModelRef as bh, type RunnerPlacement as bi, RunnerRegistry as bj, SEALED_LIMITS as bk, SEARCH_EXCLUSIONS as bl, type SandboxBackend as bm, type SandboxInvocation as bn, type SandboxLaunch as bo, type SandboxLimits as bp, type SandboxProfile as bq, type ScriptExit as br, type ScriptFullOutput as bs, type ScriptRun as bt, type ScriptStatus as bu, type SealedAvailability as bv, type SealedRunOptions as bw, type SessionData as bx, type SessionMeta as by, type ShellDialect as bz, type AgentEvent as c, type TaskWebReads as c0, type ToolOutcome as c1, type TreeEvent as c2, type TreeFact as c3, type UsageLimitSignal as c4, approvalScopes as c5, classifyCommand as c6, clearPlannerSandboxCache as c7, clearResearchShellCache as c8, collectProviderCredentials as c9, resolveWithin as cA, saveChildSession as cB, saveSession as cC, sessionDataDir as cD, sharedMcpServer as cE, taskCompletionContract as cF, taskToolSet as cG, toApprovalDecision as cH, toOrchestratorOptions as cI, toolListing as cJ, defaultLogger as ca, deleteSession as cb, effectiveApprovalMode as cc, enabledRunners as cd, fetchAllProviderModels as ce, findRunnerCommand as cf, getLatestSession as cg, grantScopeFor as ch, isGranted as ci, isRunnerApproval as cj, knownModelId as ck, listChildSessions as cl, listSessions as cm, loadChildSession as cn, loadSession as co, loadSessionPlanState as cp, mcpClientConfig as cq, ownerOnlyConfigFile as cr, parseApprovalModeSetting as cs, plannerToolSet as ct, researchShellWarning as cu, researchToolsPath as cv, resolveModelShortcut as cw, resolvePlannerSandbox as cx, resolveProvider as cy, resolveResearchShell as cz, type AgentProcessDeps as d, type AgentStartOptions as e, type AiProvider as f, type AllProviderModels as g, type AnswerApprovalArgs as h, type ApplyPatchArgs as i, type ApprovalAnswer as j, type ApprovalDecision as k, type ApprovalKind as l, type ApprovalMode as m, type ApprovalModeSetting as n, ApprovalPolicy as o, type ApprovalPolicyOptions as p, type ApprovalRequest as q, type ApprovalSource as r, type AttachState as s, type BoardAuthor as t, type BoardDraft as u, type BoardEntry as v, type BoardPost as w, type CheckpointAnswer as x, type CheckpointArgs as y, type ChildSessionPlace as z };
@@ -1,5 +1,5 @@
1
1
  import { ChildProcess } from 'child_process';
2
- import { aH as PlannerAllowlist, bb as RunnerId, aE as PlanStatus, ao as LegacyPlanState, aD as PlanState, O as HandoffCommit, af as IsolationRevertTask, ai as IsolationTaskRef, b7 as RevertCommand, bC as Task, ag as IsolationRun, bw as SkillsService, br as SkillInfo, a_ as RepoGroupLayout, Y as IWorktreeIsolation, a0 as IsolationHandoff, aC as PlanIsolation, ak as IsolationTaskStatus, bH as TaskIsolation, al as IsolationView, ab as IsolationRemoval, aO as PrepareIntent, aS as PreviousWork, a8 as IsolationOutcome, aX as RepairEvidence, bU as TreeSnapshot, bE as TaskDiffRead, bF as TaskDiffResult, a7 as IsolationMergeResult, an as LandedWork, b8 as RevertWatch, ae as IsolationRevertResult, bX as UsageRecord, bz as SubagentOutcome, bc as RunnerSessionCost, t as DiscoveredModel, b_ as VerificationCheck, bO as TaskSkillSnapshot, bj as ScriptBody, N as HandoffCheck } from './Task-CH1z4L3h.js';
2
+ import { aH as PlannerAllowlist, bb as RunnerId, aE as PlanStatus, ao as LegacyPlanState, aD as PlanState, O as HandoffCommit, af as IsolationRevertTask, ai as IsolationTaskRef, b7 as RevertCommand, bC as Task, ag as IsolationRun, bw as SkillsService, br as SkillInfo, a_ as RepoGroupLayout, Y as IWorktreeIsolation, a0 as IsolationHandoff, aC as PlanIsolation, ak as IsolationTaskStatus, bH as TaskIsolation, al as IsolationView, ab as IsolationRemoval, aO as PrepareIntent, aS as PreviousWork, a8 as IsolationOutcome, aX as RepairEvidence, bU as TreeSnapshot, bE as TaskDiffRead, bF as TaskDiffResult, a7 as IsolationMergeResult, an as LandedWork, b8 as RevertWatch, ae as IsolationRevertResult, bX as UsageRecord, bz as SubagentOutcome, bc as RunnerSessionCost, t as DiscoveredModel, b_ as VerificationCheck, bO as TaskSkillSnapshot, bj as ScriptBody, N as HandoffCheck } from './Task-TFPWtKoz.js';
3
3
  import { z } from 'zod/v4';
4
4
 
5
5
  /**
@@ -1093,6 +1093,19 @@ interface IFileSystem {
1093
1093
  taskShell?(site: TaskShellSite): TaskShell;
1094
1094
  }
1095
1095
 
1096
+ /**
1097
+ * Who made a tool call, as far as the runner's own request metadata says. It
1098
+ * is read for one purpose: leaving a delegate's reads out of the planner's
1099
+ * read limit (ADR-0068 R2). The model writes none of it, and it never decides
1100
+ * what a call may do: the envelope (ADR-0008) still does.
1101
+ */
1102
+ interface McpCaller {
1103
+ /** The runner says one of its subagents made the call. */
1104
+ subagent?: true;
1105
+ /** The runner's id for the tool use this call answers, for the harness to tie to the agent it announced. */
1106
+ toolUseId?: string;
1107
+ }
1108
+
1096
1109
  /** A subplanner's report (ADR-0057 R2): it passes a finding up only by reference, so nothing is reworded on the way, and only its token takes these. */
1097
1110
  declare const subplannerCompleteInput: z.ZodObject<{
1098
1111
  status: z.ZodEnum<{
@@ -1397,6 +1410,8 @@ type CheckpointAnswer = {
1397
1410
  interface McpToolContext {
1398
1411
  /** Aborts when the token is revoked or the caller cancels — a waiting handler must stop. */
1399
1412
  signal: AbortSignal;
1413
+ /** Who made the call, when the runner's request says (ADR-0068 R2). */
1414
+ caller?: McpCaller;
1400
1415
  }
1401
1416
  type Run<A> = (args: A, context: McpToolContext) => Promise<McpToolReply>;
1402
1417
  interface TaskToolHandler {
@@ -3156,6 +3171,7 @@ type AgentEvent =
3156
3171
  * `decided` marks a request already answered — by the adapter, as the
3157
3172
  * manifest says the task's mode does, or as a denial — so it is shown, never asked.
3158
3173
  * `ask` is what a planner's open request is for, in the envelope's terms.
3174
+ * `bySubagent` marks one the runner says a subagent of its own raised.
3159
3175
  */
3160
3176
  | {
3161
3177
  type: 'permission_request';
@@ -3165,6 +3181,7 @@ type AgentEvent =
3165
3181
  input?: Record<string, unknown>;
3166
3182
  suggestions?: unknown[];
3167
3183
  toolUseId?: string;
3184
+ bySubagent?: boolean;
3168
3185
  decided?: ApprovalDecision;
3169
3186
  ask?: PlannerAsk;
3170
3187
  }
@@ -3519,6 +3536,8 @@ interface AgentAdapter {
3519
3536
  }
3520
3537
  /** What an adapter adds to run a task rather than a planner (ADR-0018). */
3521
3538
  interface TaskModeAgentAdapter extends AgentAdapter {
3539
+ /** The size Ordewell set the task's runner to compact its context at, when it did (ADR-0057 R4). */
3540
+ readonly compactWindowTokens?: number;
3522
3541
  mcpAttached(sendFirstTurn?: () => Promise<unknown>): Promise<boolean | AttachState>;
3523
3542
  /**
3524
3543
  * Ask the running turn to stop, keeping the process and its session. Resolves
@@ -4076,6 +4095,12 @@ interface IRunnerSession {
4076
4095
  * runner nothing secret has none.
4077
4096
  */
4078
4097
  readonly secrets?: HeldSecrets;
4098
+ /**
4099
+ * The size, in tokens, at which Ordewell has set this runner to compact its
4100
+ * own context (ADR-0057 R4): a compaction at it is routine. Absent where
4101
+ * Ordewell sets none, so the runner compacts near its model's own window.
4102
+ */
4103
+ readonly compactWindowTokens?: number;
4079
4104
  onOutput(callback: (text: string) => void): void;
4080
4105
  onExit(callback: (code: number) => void): void;
4081
4106
  /** End the process at once. {@link stop} is how an attempt that is over lets it go. */
@@ -4413,4 +4438,4 @@ interface EventStore {
4413
4438
  close(): Promise<void>;
4414
4439
  }
4415
4440
 
4416
- export { type IRunner as $, AUTO_COMMANDS as A, type BashOptions as B, type CatalogModel as C, type CommandClassification as D, type CommandTier as E, ConsoleLogger as F, DENY_ALL as G, type DiscoveryCommand as H, type EditPlanArgs as I, type EventStore as J, type ExecutionBackend as K, type FetchAllProviderModelsOptions as L, type FindSymbolOptions as M, GIT_READONLY_SUBCOMMANDS as N, GREP_DEFAULT_HEAD_LIMIT as O, type GlobOptions as P, type GrepOptions as Q, type GrepOutputMode as R, type Guarantee as S, type GuaranteeReport as T, HeldSecrets as U, type HeldValue as V, type IApproval as W, type IConfig as X, type IFileSystem as Y, type ILogger as Z, type INotification as _, type AgentAdapter as a, type RevertRefusal as a$, type IRunnerSession as a0, type InvokedCommand as a1, type IsolatedExecution as a2, IsolationRunController as a3, type LeaseRecord as a4, type LeaseRepo as a5, type LeaseRequest as a6, type LeaseSpec as a7, LineBuffer as a8, type ListModelsArgs as a9, PLANNER_TOOLS as aA, type PlannerBackendId as aB, type PlannerModes as aC, type PlannerSandboxAvailability as aD, type PlannerSandboxDeps as aE, PlannerShellSandbox as aF, type PlannerStartOptions as aG, type PlannerTokenScope as aH, type PlannerToolHandler as aI, type PostArgs as aJ, type ProjectMcpServer as aK, type ProviderCredentialSource as aL, type ProviderModelLists as aM, type ProviderModelsResult as aN, type QueuedTaskMessage as aO, READ_ONLY_TASK_TOOLS as aP, REFUSED_COMMANDS as aQ, RESEARCH_READ_TOOLS as aR, type ReadFileOpts as aS, type ReadTaskArgs as aT, type ResearchShell as aU, type ResearchShellDeps as aV, type ResearchTokenScope as aW, type ResearchToolHandler as aX, type ReservedLease as aY, type RetryTaskArgs as aZ, type RevertPreviewTask as a_, type ListRunnersArgs as aa, type LoadSkillArgs as ab, type McpClientConfig as ac, type McpContact as ad, type McpCredential as ae, type McpRefusal as af, type McpTool as ag, type McpToolContext as ah, type McpToolReply as ai, type MessageTaskArgs as aj, ModelCatalog as ak, type ModelShortcut as al, type NodePath as am, type NotificationAction as an, ORCHESTRATOR_SHORTCUTS as ao, ORDEWELL_MCP_PATH as ap, ORDEWELL_MCP_SERVER_NAME as aq, type OneTaskArgs as ar, type OpenLease as as, type OrchestratorOption as at, OrdewellMcpServer as au, type OwnSealedRuns as av, type OwnerOnlyFile as aw, PLANNER_EXECUTION_TOOLS as ax, PLANNER_RESEARCH_AGENT as ay, PLANNER_SANDBOX_DOCS as az, type AgentAdapterFactory as b, type TaskWebReads as b$, type RevertRefusalReason as b0, type RevertScope as b1, type RunCommandArgs as b2, type RunPlanArgs as b3, type RunnerAuthSpec as b4, type RunnerAuthStatus as b5, type RunnerCommand as b6, type RunnerCommandKind as b7, type RunnerEntry as b8, type RunnerEnv as b9, type SkillLookup as bA, type SpawnFn as bB, type SpawnResearchAgentArgs as bC, type StandingDecision as bD, type StructuredEvent as bE, type StructuredTurnEnd as bF, type SubmitPlanArgs as bG, TASK_COMPLETE_TOOL as bH, TASK_COMPLETION_CONTRACT as bI, TASK_SEALED_LIMITS as bJ, TASK_TOOLS as bK, type TaskCompleteArgs as bL, type TaskDiffArgs as bM, type TaskMessageFrom as bN, type TaskModeAgentAdapter as bO, TaskModeUnsupportedError as bP, type TaskOutputArgs as bQ, type TaskQueryArgs as bR, type TaskRevertPreview as bS, type TaskRunCommandArgs as bT, type TaskRunnerConfig as bU, type TaskRunnerFlags as bV, type TaskShell as bW, type TaskShellSite as bX, type TaskStartOptions as bY, type TaskTokenScope as bZ, type TaskToolHandler as b_, type RunnerFeatures as ba, type RunnerLaunch as bb, type RunnerManifest as bc, type RunnerMcpServer as bd, type RunnerMode as be, type RunnerModelDiscovery as bf, type RunnerModelRef as bg, type RunnerPlacement as bh, RunnerRegistry as bi, SEALED_LIMITS as bj, SEARCH_EXCLUSIONS as bk, type SandboxBackend as bl, type SandboxInvocation as bm, type SandboxLaunch as bn, type SandboxLimits as bo, type SandboxProfile as bp, type ScriptExit as bq, type ScriptFullOutput as br, type ScriptRun as bs, type ScriptStatus as bt, type SealedAvailability as bu, type SealedRunOptions as bv, type SessionData as bw, type SessionMeta as bx, type ShellDialect as by, type ShellLaunch as bz, type AgentEvent as c, type ToolOutcome as c0, type TreeEvent as c1, type TreeFact as c2, type UsageLimitSignal as c3, approvalScopes as c4, classifyCommand as c5, clearPlannerSandboxCache as c6, clearResearchShellCache as c7, collectProviderCredentials as c8, defaultLogger as c9, saveChildSession as cA, saveSession as cB, sessionDataDir as cC, sharedMcpServer as cD, taskCompletionContract as cE, taskToolSet as cF, toApprovalDecision as cG, toOrchestratorOptions as cH, toolListing as cI, deleteSession as ca, effectiveApprovalMode as cb, enabledRunners as cc, fetchAllProviderModels as cd, findRunnerCommand as ce, getLatestSession as cf, grantScopeFor as cg, isGranted as ch, isRunnerApproval as ci, knownModelId as cj, listChildSessions as ck, listSessions as cl, loadChildSession as cm, loadSession as cn, loadSessionPlanState as co, mcpClientConfig as cp, ownerOnlyConfigFile as cq, parseApprovalModeSetting as cr, plannerToolSet as cs, researchShellWarning as ct, researchToolsPath as cu, resolveModelShortcut as cv, resolvePlannerSandbox as cw, resolveProvider as cx, resolveResearchShell as cy, resolveWithin as cz, type AgentProcessDeps as d, type AgentStartOptions as e, type AiProvider as f, type AllProviderModels as g, type AnswerApprovalArgs as h, type ApplyPatchArgs as i, type ApprovalAnswer as j, type ApprovalDecision as k, type ApprovalKind as l, type ApprovalMode as m, type ApprovalModeSetting as n, ApprovalPolicy as o, type ApprovalPolicyOptions as p, type ApprovalRequest as q, type ApprovalSource as r, type AttachState as s, type BoardAuthor as t, type BoardDraft as u, type BoardEntry as v, type BoardPost as w, type CheckpointAnswer as x, type CheckpointArgs as y, type ChildSessionPlace as z };
4441
+ export { type IRunner as $, AUTO_COMMANDS as A, type BashOptions as B, type CatalogModel as C, type CommandClassification as D, type CommandTier as E, ConsoleLogger as F, DENY_ALL as G, type DiscoveryCommand as H, type EditPlanArgs as I, type EventStore as J, type ExecutionBackend as K, type FetchAllProviderModelsOptions as L, type FindSymbolOptions as M, GIT_READONLY_SUBCOMMANDS as N, GREP_DEFAULT_HEAD_LIMIT as O, type GlobOptions as P, type GrepOptions as Q, type GrepOutputMode as R, type Guarantee as S, type GuaranteeReport as T, HeldSecrets as U, type HeldValue as V, type IApproval as W, type IConfig as X, type IFileSystem as Y, type ILogger as Z, type INotification as _, type AgentAdapter as a, type RevertPreviewTask as a$, type IRunnerSession as a0, type InvokedCommand as a1, type IsolatedExecution as a2, IsolationRunController as a3, type LeaseRecord as a4, type LeaseRepo as a5, type LeaseRequest as a6, type LeaseSpec as a7, LineBuffer as a8, type ListModelsArgs as a9, PLANNER_SANDBOX_DOCS as aA, PLANNER_TOOLS as aB, type PlannerBackendId as aC, type PlannerModes as aD, type PlannerSandboxAvailability as aE, type PlannerSandboxDeps as aF, PlannerShellSandbox as aG, type PlannerStartOptions as aH, type PlannerTokenScope as aI, type PlannerToolHandler as aJ, type PostArgs as aK, type ProjectMcpServer as aL, type ProviderCredentialSource as aM, type ProviderModelLists as aN, type ProviderModelsResult as aO, type QueuedTaskMessage as aP, READ_ONLY_TASK_TOOLS as aQ, REFUSED_COMMANDS as aR, RESEARCH_READ_TOOLS as aS, type ReadFileOpts as aT, type ReadTaskArgs as aU, type ResearchShell as aV, type ResearchShellDeps as aW, type ResearchTokenScope as aX, type ResearchToolHandler as aY, type ReservedLease as aZ, type RetryTaskArgs as a_, type ListRunnersArgs as aa, type LoadSkillArgs as ab, type McpCaller as ac, type McpClientConfig as ad, type McpContact as ae, type McpCredential as af, type McpRefusal as ag, type McpTool as ah, type McpToolContext as ai, type McpToolReply as aj, type MessageTaskArgs as ak, ModelCatalog as al, type ModelShortcut as am, type NodePath as an, type NotificationAction as ao, ORCHESTRATOR_SHORTCUTS as ap, ORDEWELL_MCP_PATH as aq, ORDEWELL_MCP_SERVER_NAME as ar, type OneTaskArgs as as, type OpenLease as at, type OrchestratorOption as au, OrdewellMcpServer as av, type OwnSealedRuns as aw, type OwnerOnlyFile as ax, PLANNER_EXECUTION_TOOLS as ay, PLANNER_RESEARCH_AGENT as az, type AgentAdapterFactory as b, type TaskToolHandler as b$, type RevertRefusal as b0, type RevertRefusalReason as b1, type RevertScope as b2, type RunCommandArgs as b3, type RunPlanArgs as b4, type RunnerAuthSpec as b5, type RunnerAuthStatus as b6, type RunnerCommand as b7, type RunnerCommandKind as b8, type RunnerEntry as b9, type ShellLaunch as bA, type SkillLookup as bB, type SpawnFn as bC, type SpawnResearchAgentArgs as bD, type StandingDecision as bE, type StructuredEvent as bF, type StructuredTurnEnd as bG, type SubmitPlanArgs as bH, TASK_COMPLETE_TOOL as bI, TASK_COMPLETION_CONTRACT as bJ, TASK_SEALED_LIMITS as bK, TASK_TOOLS as bL, type TaskCompleteArgs as bM, type TaskDiffArgs as bN, type TaskMessageFrom as bO, type TaskModeAgentAdapter as bP, TaskModeUnsupportedError as bQ, type TaskOutputArgs as bR, type TaskQueryArgs as bS, type TaskRevertPreview as bT, type TaskRunCommandArgs as bU, type TaskRunnerConfig as bV, type TaskRunnerFlags as bW, type TaskShell as bX, type TaskShellSite as bY, type TaskStartOptions as bZ, type TaskTokenScope as b_, type RunnerEnv as ba, type RunnerFeatures as bb, type RunnerLaunch as bc, type RunnerManifest as bd, type RunnerMcpServer as be, type RunnerMode as bf, type RunnerModelDiscovery as bg, type RunnerModelRef as bh, type RunnerPlacement as bi, RunnerRegistry as bj, SEALED_LIMITS as bk, SEARCH_EXCLUSIONS as bl, type SandboxBackend as bm, type SandboxInvocation as bn, type SandboxLaunch as bo, type SandboxLimits as bp, type SandboxProfile as bq, type ScriptExit as br, type ScriptFullOutput as bs, type ScriptRun as bt, type ScriptStatus as bu, type SealedAvailability as bv, type SealedRunOptions as bw, type SessionData as bx, type SessionMeta as by, type ShellDialect as bz, type AgentEvent as c, type TaskWebReads as c0, type ToolOutcome as c1, type TreeEvent as c2, type TreeFact as c3, type UsageLimitSignal as c4, approvalScopes as c5, classifyCommand as c6, clearPlannerSandboxCache as c7, clearResearchShellCache as c8, collectProviderCredentials as c9, resolveWithin as cA, saveChildSession as cB, saveSession as cC, sessionDataDir as cD, sharedMcpServer as cE, taskCompletionContract as cF, taskToolSet as cG, toApprovalDecision as cH, toOrchestratorOptions as cI, toolListing as cJ, defaultLogger as ca, deleteSession as cb, effectiveApprovalMode as cc, enabledRunners as cd, fetchAllProviderModels as ce, findRunnerCommand as cf, getLatestSession as cg, grantScopeFor as ch, isGranted as ci, isRunnerApproval as cj, knownModelId as ck, listChildSessions as cl, listSessions as cm, loadChildSession as cn, loadSession as co, loadSessionPlanState as cp, mcpClientConfig as cq, ownerOnlyConfigFile as cr, parseApprovalModeSetting as cs, plannerToolSet as ct, researchShellWarning as cu, researchToolsPath as cv, resolveModelShortcut as cw, resolvePlannerSandbox as cx, resolveProvider as cy, resolveResearchShell as cz, type AgentProcessDeps as d, type AgentStartOptions as e, type AiProvider as f, type AllProviderModels as g, type AnswerApprovalArgs as h, type ApplyPatchArgs as i, type ApprovalAnswer as j, type ApprovalDecision as k, type ApprovalKind as l, type ApprovalMode as m, type ApprovalModeSetting as n, ApprovalPolicy as o, type ApprovalPolicyOptions as p, type ApprovalRequest as q, type ApprovalSource as r, type AttachState as s, type BoardAuthor as t, type BoardDraft as u, type BoardEntry as v, type BoardPost as w, type CheckpointAnswer as x, type CheckpointArgs as y, type ChildSessionPlace as z };