@tekmidian/pai 0.57.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chain-OzYgALdx.mjs → chain-Cltx0NjY.mjs} +4 -4
- package/dist/{chain-OzYgALdx.mjs.map → chain-Cltx0NjY.mjs.map} +1 -1
- package/dist/cli/index.mjs +9 -9
- package/dist/cli/program.mjs +9 -9
- package/dist/{context-handover-cache-k2kWbE6G.mjs → context-handover-cache-Dt4HW1Ro.mjs} +3 -3
- package/dist/{context-handover-cache-k2kWbE6G.mjs.map → context-handover-cache-Dt4HW1Ro.mjs.map} +1 -1
- package/dist/daemon/index.mjs +7 -7
- package/dist/{daemon-D8zXReoA.mjs → daemon-B6hx1Ysz.mjs} +7 -7
- package/dist/{daemon-Caxrq2iQ.mjs → daemon-CmqJfeb9.mjs} +24 -14
- package/dist/daemon-CmqJfeb9.mjs.map +1 -0
- package/dist/daemon-mcp/index.mjs +5 -5
- package/dist/{fallback-CiG573uw.mjs → fallback-B_2ozQHw.mjs} +4 -4
- package/dist/{fallback-CiG573uw.mjs.map → fallback-B_2ozQHw.mjs.map} +1 -1
- package/dist/hooks/worker-status-line.mjs +3 -1
- package/dist/hooks/worker-status-line.mjs.map +2 -2
- package/dist/{main-resolver-Dx-pxic1.mjs → main-resolver-DYNxxNwJ.mjs} +166 -12
- package/dist/main-resolver-DYNxxNwJ.mjs.map +1 -0
- package/dist/{main-resolver-uDtK9p6e.mjs → main-resolver-Df65bPAi.mjs} +2 -2
- package/dist/{planner-s1iQQsjj.mjs → planner-DsZZEZCA.mjs} +5 -5
- package/dist/{planner-s1iQQsjj.mjs.map → planner-DsZZEZCA.mjs.map} +1 -1
- package/dist/{program-COHW5ZtV.mjs → program-B5miXqQa.mjs} +70 -74
- package/dist/program-B5miXqQa.mjs.map +1 -0
- package/dist/{run-9HbO1gTM.mjs → run-XaA-UPdW.mjs} +14 -10
- package/dist/run-XaA-UPdW.mjs.map +1 -0
- package/dist/{config-B93YS8tP.mjs → run-env-DyTWgZC9.mjs} +112 -3
- package/dist/run-env-DyTWgZC9.mjs.map +1 -0
- package/dist/{server-CGuZFOeR.mjs → server-CzqHGbKt.mjs} +4 -113
- package/dist/server-CzqHGbKt.mjs.map +1 -0
- package/dist/{session-keepalive-Dg3wiiFJ.mjs → session-keepalive-DDsEo81Q.mjs} +4 -4
- package/dist/{session-keepalive-Dg3wiiFJ.mjs.map → session-keepalive-DDsEo81Q.mjs.map} +1 -1
- package/dist/{work-queue-worker-DEbWsrDQ.mjs → work-queue-worker-BY7xn4pw.mjs} +4 -4
- package/dist/{work-queue-worker-DufMOtrL.mjs → work-queue-worker-DL9lu8sN.mjs} +2 -2
- package/dist/{work-queue-worker-DufMOtrL.mjs.map → work-queue-worker-DL9lu8sN.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/config-B93YS8tP.mjs.map +0 -1
- package/dist/daemon-Caxrq2iQ.mjs.map +0 -1
- package/dist/main-resolver-Dx-pxic1.mjs.map +0 -1
- package/dist/program-COHW5ZtV.mjs.map +0 -1
- package/dist/run-9HbO1gTM.mjs.map +0 -1
- package/dist/server-CGuZFOeR.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-B93YS8tP.mjs","names":[],"sources":["../src/utils/model-window.ts","../src/workers/workers-config.ts","../src/workers/config.ts"],"sourcesContent":["/**\n * model-window.ts — facts derivable from a bare model id.\n *\n * Shared by the worker stack (provider registry) and the session hooks\n * (context-fill). Zero imports on purpose: this leaf is bundled into hooks\n * (scripts/build-hooks.mjs) and must never drag config or path machinery\n * into a hook process.\n */\n\n/** Last-resort window when nothing on hand reports one and the model id\n * carries no window information. */\nexport const DEFAULT_CONTEXT_WINDOW = 200_000;\n\n/** Strip a bracketed variant suffix: \"glm-5.3[1m]\" → \"glm-5.3\". The suffix\n * selects a variant of the same base model (a context-window tier, a\n * quantization), so the prefix is the id's family. */\nexport function stripModelVariant(model: string): string {\n const stripped = model.replace(/\\[[^\\]]*\\]\\s*$/, \"\").trim();\n return stripped || model;\n}\n\n/**\n * The context window a model id itself declares, or null when the id carries\n * no window information. Only the bracketed variant suffix is read\n * (\"[1m]\" → 1,000,000); a bare id says nothing and stays null so callers can\n * fall back to whatever they measured themselves.\n */\nexport function contextWindowFromModelId(model: string | null | undefined): number | null {\n if (typeof model !== \"string\" || model === \"\") return null;\n const m = /\\[(\\d+)m\\]$/i.exec(model.trim());\n if (!m) return null;\n const millions = Number(m[1]);\n if (!Number.isFinite(millions) || millions < 1) return null;\n return millions * 1_000_000;\n}\n","/**\n * workers-config.ts — workers.yaml: providers, model roles, class routing,\n * mcp_sets.\n *\n * config.ts's readWorkersSection/writeWorkersSection are the only callers —\n * every other module keeps talking to the WorkersConfig shape from config.ts\n * and never touches this file. That is deliberate: adding a provider used to\n * mean editing JSON inside an unrelated config blob; this module makes\n * providers/classes/mcp_sets/active a single human-editable file, documented\n * in docs/workers-config.md, while everything downstream is unchanged.\n *\n * Writes go through the `yaml` package's Document API and only touch the\n * entries that actually changed, so hand-written comments elsewhere in the\n * file — including a comment directly above an untouched provider — survive\n * byte-for-byte across `add`, `use`, `disable`, and every other mutation.\n */\n\nimport { existsSync, readFileSync, writeFileSync, chmodSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { Document, Scalar, parseDocument, type Node } from \"yaml\";\nimport { readJsonStrict, writeJsonAtomic } from \"../config/json-store.js\";\nimport { writeYamlFileAtomic, YamlStoreError } from \"../config/yaml-store.js\";\nimport { paiHomePath, resolvePaiFile, migratePaiFile, type MigrateFileResult } from \"../config/pai-home.js\";\nimport {\n ANTHROPIC_NATIVE,\n NATIVE_ANTHROPIC_MODELS,\n WorkersConfigError,\n expandHome,\n isModelCapability,\n parseCapabilitiesValue,\n parseClassesValue,\n parseMcpSetsValue,\n parseModelsBlock,\n parseProvider,\n parseWorkersConfig,\n type ClassTarget,\n type WorkerProvider,\n} from \"./config.js\";\n\nexport const WORKERS_YAML_FILENAME = \"workers.yaml\";\n\n/**\n * Where workers.yaml lives since 2026-09-19: under the PAI_HOME namespace\n * dir (~/.claude/pai by default) — this file is per-user state that can\n * carry API keys and must never be committed, same as the rest of PAI_HOME.\n */\nfunction defaultWorkersYamlPath(): string {\n return paiHomePath(WORKERS_YAML_FILENAME);\n}\n\n/** Briefly the canonical location between 2026-09-19's two migrations —\n * read during the transition, never written to again. */\nfunction oldWorkersYamlPath(): string {\n return join(homedir(), \".claude\", WORKERS_YAML_FILENAME);\n}\n\n/** Where workers.yaml lived before 2026-09-19 — read during the transition,\n * never written to (see `pai worker config migrate`). */\nfunction legacyWorkersYamlPath(): string {\n return join(homedir(), \".config\", \"pai\", WORKERS_YAML_FILENAME);\n}\n\n/**\n * The path any read/write of workers.yaml actually uses: PAI_WORKERS_YAML\n * (tests, power users) first, else the new PAI_HOME location if it exists,\n * else the most recent old location that is actually on disk (printing a\n * one-time notice), else the new location (the target a first write creates).\n */\nexport function workersYamlPath(): string {\n const override = process.env.PAI_WORKERS_YAML;\n if (override) return override;\n return resolvePaiFile(\n defaultWorkersYamlPath(),\n [oldWorkersYamlPath(), legacyWorkersYamlPath()],\n \"pai worker config migrate\"\n );\n}\n\n/** Where a fresh write (init, migrate, relocate's destination) always\n * targets — the new location, or PAI_WORKERS_YAML for test isolation.\n * Never an old path: nothing is ever written there again. */\nfunction writeTargetWorkersYamlPath(): string {\n return process.env.PAI_WORKERS_YAML ?? defaultWorkersYamlPath();\n}\n\n/**\n * One-line notice for `pai worker config check` and `pai worker providers`\n * when workers.yaml is still sitting at an old location. Null once it has\n * moved (or PAI_WORKERS_YAML is set — that always wins, nothing to migrate).\n */\nexport function workersYamlLegacyNotice(): string | null {\n if (process.env.PAI_WORKERS_YAML) return null;\n if (existsSync(defaultWorkersYamlPath())) return null;\n const found = [oldWorkersYamlPath(), legacyWorkersYamlPath()].find((p) => existsSync(p));\n if (!found) return null;\n return `workers.yaml is still at the old location (${found}) — run \\`pai worker config migrate\\` to move it to ${defaultWorkersYamlPath()}`;\n}\n\nexport interface WorkersYamlData {\n active: string | null;\n providers: Record<string, WorkerProvider>;\n classes: Record<string, ClassTarget>;\n capabilities: Record<string, string[]>;\n mcpSets: Record<string, string[]>;\n nativeModels: WorkerProvider[\"models\"];\n}\n\n// ---------------------------------------------------------------------------\n// Friendly (on-disk) provider shape ↔ internal WorkerProvider\n// ---------------------------------------------------------------------------\n\n/** snake_case on-disk keys → the camelCase raw shape parseProvider expects. */\nfunction yamlProviderToRaw(y: Record<string, unknown>): Record<string, unknown> {\n const raw: Record<string, unknown> = {};\n if (y.enabled !== undefined) raw.enabled = y.enabled;\n if (y.url !== undefined) raw.baseUrl = y.url;\n if (y.key_file !== undefined) raw.keyFile = y.key_file;\n if (y.key !== undefined) raw.key = y.key;\n if (y.tier !== undefined) raw.costTier = y.tier;\n if (y.models !== undefined) raw.models = y.models;\n if (y.protocol !== undefined) raw.protocol = y.protocol;\n if (y.engine !== undefined) raw.engine = y.engine;\n if (y.upstream_url !== undefined) raw.upstreamUrl = y.upstream_url;\n if (y.env !== undefined) raw.env = y.env;\n if (y.note !== undefined) raw.note = y.note;\n if (y.quota_probe !== undefined) raw.quotaProbe = y.quota_probe;\n if (y.quota_skip_at !== undefined) raw.quotaSkipAt = y.quota_skip_at;\n if (y.context_window !== undefined) raw.contextWindow = y.context_window;\n if (y.tags !== undefined) raw.tags = y.tags;\n if (y.usage !== undefined) raw.usage = y.usage;\n if (y.model_tiers !== undefined) raw.modelTiers = y.model_tiers;\n return raw;\n}\n\n/** Internal WorkerProvider → the friendly on-disk plain object for writing. */\nfunction providerToYamlPlain(p: WorkerProvider): Record<string, unknown> {\n const y: Record<string, unknown> = {};\n if (!p.enabled) y.enabled = false;\n if (p.baseUrl) y.url = p.baseUrl;\n if (p.keyFile) y.key_file = p.keyFile;\n if (p.key) y.key = p.key;\n if (p.costTier !== undefined) y.tier = p.costTier;\n y.models = { ...p.models };\n if (p.protocol && p.protocol !== \"anthropic\") y.protocol = p.protocol;\n if (p.engine && p.engine !== \"claude\") y.engine = p.engine;\n if (p.upstreamUrl) y.upstream_url = p.upstreamUrl;\n if (p.env && Object.keys(p.env).length) y.env = { ...p.env };\n if (p.note) y.note = p.note;\n if (p.quotaProbe) y.quota_probe = p.quotaProbe;\n if (p.quotaSkipAt !== undefined) y.quota_skip_at = p.quotaSkipAt;\n if (p.contextWindow !== undefined) y.context_window = p.contextWindow;\n if (p.tags?.length) y.tags = [...p.tags];\n if (p.usage) y.usage = p.usage;\n if (p.modelTiers) y.model_tiers = { ...p.modelTiers };\n return y;\n}\n\n/** The builtin `anthropic` block only ever carries `builtin: true` + `models`. */\nfunction parseBuiltinAnthropic(raw: unknown, pathPrefix: string): WorkerProvider[\"models\"] {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new WorkersConfigError(`${pathPrefix}: must be an object`);\n }\n const p = raw as Record<string, unknown>;\n if (p.builtin !== true) {\n throw new WorkersConfigError(\n `${pathPrefix}: \"${ANTHROPIC_NATIVE}\" is reserved for the built-in Claude Code login — ` +\n `set \"builtin: true\" (optionally with a \"models\" override) or rename this provider`\n );\n }\n const disallowed = [\"url\", \"key_file\", \"key\", \"engine\", \"protocol\", \"upstream_url\"].filter(\n (k) => p[k] !== undefined\n );\n if (disallowed.length) {\n throw new WorkersConfigError(\n `${pathPrefix}: a builtin provider cannot set ${disallowed.join(\", \")} — it runs on Claude Code's own login`\n );\n }\n if (p.models === undefined) return { ...NATIVE_ANTHROPIC_MODELS };\n return parseModelsBlock(`${pathPrefix}.models`, p.models);\n}\n\n// ---------------------------------------------------------------------------\n// Line-numbered errors\n// ---------------------------------------------------------------------------\n\nfunction lineOf(doc: Document, path: (string | number)[]): number | null {\n try {\n const node = doc.getIn(path, true) as Node | undefined;\n const range = node && typeof node === \"object\" && \"range\" in node ? node.range : undefined;\n if (!range) return null;\n const text = String(doc);\n return text.slice(0, range[0]).split(\"\\n\").length;\n } catch {\n return null;\n }\n}\n\nfunction withLine(doc: Document, path: (string | number)[], yamlPath: string, e: unknown): never {\n const msg = e instanceof Error ? e.message : String(e);\n const line = lineOf(doc, path);\n throw new WorkersConfigError(line ? `${yamlPath}:${line}: ${msg}` : `${yamlPath}: ${msg}`);\n}\n\n// ---------------------------------------------------------------------------\n// Load + validate\n// ---------------------------------------------------------------------------\n\n/**\n * Parse and fully validate a workers.yaml Document. Throws WorkersConfigError\n * naming `<path>:<line>` for anything wrong — an unknown provider referenced\n * by a class is a load error here, not a spawn-time surprise.\n */\nexport function parseWorkersYamlDocument(doc: Document, yamlPath: string): WorkersYamlData {\n const root = doc.toJS() ?? {};\n if (typeof root !== \"object\" || Array.isArray(root)) {\n throw new WorkersConfigError(`${yamlPath}: top level must be a mapping`);\n }\n const r = root as Record<string, unknown>;\n\n const providers: Record<string, WorkerProvider> = {};\n let nativeModels: WorkerProvider[\"models\"] = { ...NATIVE_ANTHROPIC_MODELS };\n const providersRaw = r.providers;\n if (providersRaw !== undefined) {\n if (typeof providersRaw !== \"object\" || providersRaw === null || Array.isArray(providersRaw)) {\n withLine(doc, [\"providers\"], yamlPath, new WorkersConfigError(\"providers: must be a mapping of name → provider\"));\n }\n for (const [name, raw] of Object.entries(providersRaw as Record<string, unknown>)) {\n try {\n if (name === ANTHROPIC_NATIVE) {\n nativeModels = parseBuiltinAnthropic(raw, `providers.${name}`);\n } else {\n providers[name] = parseProvider(name, yamlProviderToRaw(raw as Record<string, unknown>));\n }\n } catch (e) {\n withLine(doc, [\"providers\", name], yamlPath, e);\n }\n }\n }\n\n let classes: Record<string, ClassTarget> = {};\n if (r.classes !== undefined) {\n try {\n classes = parseClassesValue(r.classes, \"classes\");\n } catch (e) {\n withLine(doc, [\"classes\"], yamlPath, e);\n }\n // Cross-validate: every class must name a known provider (or \"anthropic\")\n // and, if it names a role, a capability that provider actually declares.\n // Unlike the JSON path (where a provider can be removed out from under a\n // class and the error surfaces at spawn time), workers.yaml catches this\n // at load time.\n for (const [cls, target] of Object.entries(classes)) {\n const provider = typeof target === \"string\" ? target.split(\"/\")[0] : target.provider;\n const alias = typeof target === \"string\" ? target.split(\"/\")[1] : undefined;\n if (provider !== undefined) {\n const native = provider === ANTHROPIC_NATIVE;\n if (!native && !providers[provider]) {\n withLine(\n doc,\n [\"classes\", cls],\n yamlPath,\n new WorkersConfigError(\n `classes.${cls}: no provider named \"${provider}\" (configured: ${Object.keys(providers).join(\", \") || \"(none)\"})`\n )\n );\n }\n if (alias !== undefined) {\n if (!isModelCapability(alias)) {\n withLine(\n doc,\n [\"classes\", cls],\n yamlPath,\n new WorkersConfigError(\n `classes.${cls}: \"${alias}\" is not a valid capability name (must match ^[a-z][a-z0-9-]*$)`\n )\n );\n } else if (!native && providers[provider] && alias !== \"default\" && !providers[provider].models[alias]) {\n // the native provider has no configurable model slots — any\n // alias resolves through resolveModelCapability's own fallback\n withLine(\n doc,\n [\"classes\", cls],\n yamlPath,\n new WorkersConfigError(`classes.${cls}: provider \"${provider}\" has no \"${alias}\" model configured`)\n );\n }\n }\n }\n }\n }\n\n let capabilities: Record<string, string[]> = {};\n if (r.capabilities !== undefined) {\n try {\n capabilities = parseCapabilitiesValue(r.capabilities, \"capabilities\");\n } catch (e) {\n withLine(doc, [\"capabilities\"], yamlPath, e);\n }\n }\n\n let mcpSets: Record<string, string[]> = {};\n if (r.mcp_sets !== undefined) {\n try {\n mcpSets = parseMcpSetsValue(r.mcp_sets, \"mcp_sets\");\n } catch (e) {\n withLine(doc, [\"mcp_sets\"], yamlPath, e);\n }\n } else {\n mcpSets = parseMcpSetsValue(undefined, \"mcp_sets\");\n }\n\n const active = r.active === undefined || r.active === null ? null : String(r.active);\n if (active !== null && active !== ANTHROPIC_NATIVE && active !== \"auto\" && !providers[active]) {\n withLine(\n doc,\n [\"active\"],\n yamlPath,\n new WorkersConfigError(\n `active: no provider named \"${active}\" (configured: ${Object.keys(providers).join(\", \") || \"(none)\"})`\n )\n );\n }\n\n return { active, providers, classes, capabilities, mcpSets, nativeModels };\n}\n\n/** Read + parse workers.yaml. Returns null if the file does not exist. */\nexport function readWorkersYaml(yamlPath: string): { doc: Document; data: WorkersYamlData } | null {\n if (!existsSync(yamlPath)) return null;\n let text: string;\n try {\n text = readFileSync(yamlPath, \"utf8\");\n } catch (e) {\n throw new WorkersConfigError(\n `Could not read ${yamlPath}: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n const doc = parseDocument(text);\n if (doc.errors.length) {\n throw new WorkersConfigError(`${yamlPath}: ${doc.errors[0].message}`);\n }\n const data = parseWorkersYamlDocument(doc, yamlPath);\n return { doc, data };\n}\n\n// ---------------------------------------------------------------------------\n// Write (diff-based, comment-preserving)\n// ---------------------------------------------------------------------------\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * A `key:` value as an explicit double-quoted YAML scalar. A key is an\n * opaque token, not YAML-authored text — plain-scalar auto-styling could\n * read one back as a number or boolean (an all-digit token, \"true\", \"no\", …)\n * if it were ever left unquoted, so every write forces the quoted form\n * regardless of what the plain style would otherwise pick.\n */\nfunction quotedKeyNode(value: string): Scalar {\n const s = new Scalar(value);\n s.type = Scalar.QUOTE_DOUBLE;\n return s;\n}\n\n/**\n * Apply the changes between `before` and `after` onto `doc`, touching only\n * the providers/classes/mcp_sets/active entries that actually differ. This is\n * what makes comment preservation possible: an untouched provider's node\n * (and any comment above it) is never revisited.\n */\nfunction syncWorkersYamlDocument(doc: Document, before: WorkersYamlData, after: WorkersYamlData): void {\n // providers: add/update changed, remove gone (never touch the builtin anthropic block)\n for (const [name, p] of Object.entries(after.providers)) {\n const beforeP = before.providers[name];\n const changed = !beforeP || !shallowEqual(providerToYamlPlain(beforeP), providerToYamlPlain(p));\n if (changed) {\n // a fresh (or wholesale-replaced) provider entry is set in one shot as\n // a plain object — the yaml lib only turns it into real Map/Scalar\n // nodes lazily at stringify time, so a follow-up setIn/deleteIn into\n // the same not-yet-a-collection value would fail. Embedding the `key`\n // as an actual Scalar node here rides along: stringify leaves already-\n // Node values alone (see stringifyPair.js), quoting only that field.\n const y: Record<string, unknown> = providerToYamlPlain(p);\n if (typeof y.key === \"string\") y.key = quotedKeyNode(y.key);\n doc.setIn([\"providers\", name], y);\n }\n }\n for (const name of Object.keys(before.providers)) {\n if (!(name in after.providers)) doc.deleteIn([\"providers\", name]);\n }\n\n // classes: same add/update/remove diff\n for (const [cls, target] of Object.entries(after.classes)) {\n if (!shallowEqual(before.classes[cls], target)) {\n doc.setIn([\"classes\", cls], target);\n }\n }\n for (const cls of Object.keys(before.classes)) {\n if (!(cls in after.classes)) doc.deleteIn([\"classes\", cls]);\n }\n\n // capabilities: same add/update/remove diff\n for (const [cap, prefs] of Object.entries(after.capabilities)) {\n if (!shallowEqual(before.capabilities[cap], prefs)) {\n doc.setIn([\"capabilities\", cap], [...prefs]);\n }\n }\n for (const cap of Object.keys(before.capabilities)) {\n if (!(cap in after.capabilities)) doc.deleteIn([\"capabilities\", cap]);\n }\n\n // mcp_sets: same add/update/remove diff\n for (const [set, servers] of Object.entries(after.mcpSets)) {\n if (!shallowEqual(before.mcpSets[set], servers)) {\n doc.setIn([\"mcp_sets\", set], [...servers]);\n }\n }\n for (const set of Object.keys(before.mcpSets)) {\n if (!(set in after.mcpSets)) doc.deleteIn([\"mcp_sets\", set]);\n }\n\n // active\n if (before.active !== after.active) {\n if (after.active === null) doc.deleteIn([\"active\"]);\n else doc.setIn([\"active\"], after.active);\n }\n}\n\n/**\n * Write `after` into workers.yaml, preserving comments on everything that did\n * not change. Re-reads the file fresh (so the diff is against what is really\n * on disk, not a stale in-memory copy) and re-validates the result before\n * committing; on failure the previous bytes are left untouched.\n */\nexport function writeWorkersYaml(yamlPath: string, after: WorkersYamlData): void {\n const existing = readWorkersYaml(yamlPath);\n const doc = existing ? existing.doc : new Document({});\n const before: WorkersYamlData = existing\n ? existing.data\n : {\n active: null,\n providers: {},\n classes: {},\n capabilities: {},\n mcpSets: {},\n nativeModels: { ...NATIVE_ANTHROPIC_MODELS },\n };\n syncWorkersYamlDocument(doc, before, after);\n writeWorkersYamlText(yamlPath, String(doc));\n}\n\n/** Atomic write with a .bak-pai backup and a re-validate-or-restore guard.\n * The file-I/O tail (backup, temp write at 0600, rename, chmod) is shared\n * with every other PAI YAML file via writeYamlFileAtomic; only the\n * workers.yaml-specific validation (parseWorkersYamlDocument) lives here. */\nexport function writeWorkersYamlText(yamlPath: string, text: string): void {\n // Validate before committing anything to disk.\n const probe = parseDocument(text);\n if (probe.errors.length) {\n throw new WorkersConfigError(`refusing to write ${yamlPath}: ${probe.errors[0].message} (previous file left unchanged)`);\n }\n try {\n parseWorkersYamlDocument(probe, yamlPath);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new WorkersConfigError(`refusing to write ${yamlPath}: ${msg} (previous file left unchanged)`);\n }\n\n try {\n writeYamlFileAtomic(yamlPath, text, { label: yamlPath });\n } catch (e) {\n throw new WorkersConfigError(e instanceof YamlStoreError ? e.message : String(e instanceof Error ? e.message : e));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Starter template, init, migrate\n// ---------------------------------------------------------------------------\n\n/** The exact commented starter shipped as examples/workers.yaml and by `init`. */\nexport function starterWorkersYamlText(): string {\n return `# PAI worker configuration.\n# Providers PAI can run workers on, the model each role uses, and which\n# provider every --class goes to. Edit by hand; \\`pai worker providers\\` shows\n# the effective result. Comments are preserved when PAI writes this file.\n#\n# Per-user state, kept 0600: this file can hold API keys (\\`key:\\`, below).\n# Never commit it or share it. \\`key_file: <path>\\` keeps a secret in its own\n# 0600 file instead, if you'd rather not put it here.\n\nactive: anthropic # provider for \\`pai worker run\\` without --provider or --class\n\nproviders:\n anthropic:\n builtin: true # Claude Code's own login: no url, no key file\n models:\n default: ${NATIVE_ANTHROPIC_MODELS.default}\n fast: ${NATIVE_ANTHROPIC_MODELS.fast}\n glm:\n url: https://api.z.ai/api/anthropic\n key: \"<your-api-key>\" # or key_file: <path to a 0600 file>\n tier: 3\n models:\n default: glm-5.3[1m]\n fast: glm-5.3-flash\n image: example-paint\n kimi:\n url: https://api.kimi.ai/coding/\n key: \"<your-api-key>\" # or key_file: <path to a 0600 file>\n tier: 3\n models:\n default: k3[1m]\n fast: kimi-for-coding[1m]\n\n# An \\`engine: image\\` provider does not spawn Claude — \\`pai worker run\n# --capability image\\` POSTs straight to its OpenAI-compatible images API and\n# writes the PNG it gets back. Uncomment and point it at a real provider\n# (still nested under providers:, above) to enable \\`--capability image\\`:\n# pictures:\n# engine: image\n# url: https://api.example.com/v1\n# key: \"<your-api-key>\"\n# models:\n# default: example-image-model\n# image: example-image-model\n\n# A class names a provider, or provider/role to pick a non-default model.\n# Workers exist to parallelise and to save cost: the default is Sonnet,\n# Haiku for the mechanical classes, and nothing here inherits the\n# orchestrating session's model.\nclasses:\n implement: anthropic\n draft: anthropic\n research: anthropic\n complex: anthropic\n plan: anthropic\n review: anthropic\n spotcheck: anthropic/fast\n simple: anthropic/fast\n image: glm/image\n\n# Cross-provider capability preference: which provider serves a --capability\n# request, in order, when more than one declares it. Unlisted capabilities\n# fall back to the active provider, then any provider that declares them.\n# capabilities:\n# image: [pictures, glm]\n# fast: [anthropic]\n\nmcp_sets:\n desktop: [clickr]\n`;\n}\n\n/**\n * Build a workers.yaml document from real (migrated) data, keeping the same\n * header/section comments as the starter. Used by `pai worker config\n * migrate` — `init` writes the literal starter instead, since it has no data\n * to carry over.\n */\nexport function buildWorkersYamlText(data: WorkersYamlData): string {\n const lines: string[] = [];\n lines.push(\"# PAI worker configuration.\");\n lines.push(\"# Providers PAI can run workers on, the model each role uses, and which\");\n lines.push(\"# provider every --class goes to. Edit by hand; `pai worker providers` shows\");\n lines.push(\"# the effective result. Comments are preserved when PAI writes this file.\");\n lines.push(\"\");\n lines.push(\n `active: ${data.active ?? \"null\"}` +\n \" # provider for `pai worker run` without --provider or --class\"\n );\n lines.push(\"\");\n lines.push(\"providers:\");\n lines.push(\" anthropic:\");\n lines.push(\" builtin: true # Claude Code's own login: no url, no key file\");\n lines.push(\" models:\");\n lines.push(` default: ${data.nativeModels.default}`);\n if (data.nativeModels.fast) lines.push(` fast: ${data.nativeModels.fast}`);\n if (data.nativeModels.image) lines.push(` image: ${data.nativeModels.image}`);\n for (const [name, p] of Object.entries(data.providers)) {\n const y = providerToYamlPlain(p);\n lines.push(` ${name}:`);\n for (const [k, v] of Object.entries(y)) {\n if (k === \"models\") continue;\n // a key is an opaque token, not YAML-authored text — always quoted so\n // it never round-trips as a number or boolean (see quotedKeyNode).\n lines.push(k === \"key\" ? ` key: ${JSON.stringify(String(v))}` : ` ${k}: ${yamlScalar(v)}`);\n }\n lines.push(\" models:\");\n for (const [k, v] of Object.entries(p.models)) lines.push(` ${k}: ${yamlScalar(v)}`);\n }\n lines.push(\"\");\n lines.push(\"# A class names a provider, or provider/role to pick a non-default model.\");\n lines.push(\"# Workers exist to parallelise and to save cost: the default is Sonnet,\");\n lines.push(\"# Haiku for the mechanical classes, and nothing here inherits the\");\n lines.push(\"# orchestrating session's model.\");\n const classEntries = Object.entries(data.classes);\n lines.push(classEntries.length ? \"classes:\" : \"classes: {}\");\n for (const [cls, target] of classEntries) {\n lines.push(` ${cls}: ${typeof target === \"string\" ? target : yamlScalar(target)}`);\n }\n lines.push(\"\");\n const capEntries = Object.entries(data.capabilities);\n if (capEntries.length) {\n lines.push(\"capabilities:\");\n for (const [cap, prefs] of capEntries) lines.push(` ${cap}: [${prefs.join(\", \")}]`);\n lines.push(\"\");\n }\n const mcpEntries = Object.entries(data.mcpSets);\n lines.push(mcpEntries.length ? \"mcp_sets:\" : \"mcp_sets: {}\");\n for (const [set, servers] of mcpEntries) {\n lines.push(` ${set}: [${servers.join(\", \")}]`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** Minimal scalar formatter for buildWorkersYamlText's flat key: value lines. */\nfunction yamlScalar(v: unknown): string {\n if (typeof v === \"string\") {\n // quote only when the plain form would be ambiguous YAML\n return /^[\\w./~\\[\\]-]+$/.test(v) ? v : JSON.stringify(v);\n }\n if (Array.isArray(v)) return `[${v.map(yamlScalar).join(\", \")}]`;\n if (v && typeof v === \"object\") return JSON.stringify(v);\n return String(v);\n}\n\n// ---------------------------------------------------------------------------\n// Migration from the JSON `workers` section\n// ---------------------------------------------------------------------------\n\nexport interface MigrateResult {\n yamlPath: string;\n yamlText: string;\n /** Path the pre-migration JSON `workers` section was backed up to; null on a dry run. */\n backupPath: string | null;\n dryRun: boolean;\n}\n\n/**\n * `pai worker config migrate`: reads the JSON `workers` section, writes\n * workers.yaml with the starter's comments, backs the JSON section up to\n * `workers.json.migrated-<date>` next to it, and strips providers/classes\n * (and the legacy `roles`)/mcpSets/active from the JSON. Idempotent: refuses\n * when workers.yaml already exists unless `force`. `dryRun` computes and\n * returns the would-be YAML text without touching either file.\n */\nexport function migrateWorkersToYaml(\n jsonPath: string,\n opts: { force?: boolean; dryRun?: boolean } = {}\n): MigrateResult {\n const existing = workersYamlPath();\n if (existsSync(existing) && !opts.force) {\n throw new WorkersConfigError(\n `${existing} already exists — refusing to overwrite without --force`\n );\n }\n const yamlPath = writeTargetWorkersYamlPath();\n const raw = readJsonStrict(jsonPath, jsonPath);\n const workers = parseWorkersConfig(raw.workers);\n const data: WorkersYamlData = {\n active: workers.active,\n providers: workers.providers,\n classes: workers.classes,\n capabilities: workers.capabilities,\n mcpSets: workers.mcpSets,\n nativeModels: workers.nativeModels,\n };\n const yamlText = buildWorkersYamlText(data);\n\n if (opts.dryRun) {\n return { yamlPath, yamlText, backupPath: null, dryRun: true };\n }\n\n writeWorkersYamlText(yamlPath, yamlText);\n\n const stamp = new Date().toISOString().slice(0, 10);\n const backupPath = join(dirname(jsonPath), `workers.json.migrated-${stamp}`);\n writeFileSync(backupPath, JSON.stringify(raw.workers ?? {}, null, 2) + \"\\n\", \"utf8\");\n\n const priorWorkers = (raw.workers as Record<string, unknown>) ?? {};\n const { providers: _p, classes: _c, roles: _r, mcpSets: _m, active: _a, ...rest } = priorWorkers;\n raw.workers = rest;\n writeJsonAtomic(jsonPath, raw, { label: jsonPath });\n\n return { yamlPath, yamlText, backupPath, dryRun: false };\n}\n\n/**\n * `pai worker config init`: write the literal commented starter (no data to\n * carry over — that is what `migrate` is for). Refuses if workers.yaml\n * already exists.\n */\nexport function initWorkersYaml(): string {\n const existing = workersYamlPath();\n if (existsSync(existing)) {\n throw new WorkersConfigError(\n `${existing} already exists — edit it directly, or run \\`pai worker config migrate --force\\` to regenerate it from the JSON config`\n );\n }\n const yamlPath = writeTargetWorkersYamlPath();\n writeWorkersYamlText(yamlPath, starterWorkersYamlText());\n return yamlPath;\n}\n\n// ---------------------------------------------------------------------------\n// Relocating from an old location\n// ---------------------------------------------------------------------------\n\nexport type RelocateResult = MigrateFileResult;\n\n/** True when an old-location workers.yaml exists and nothing is at the new one yet. */\nexport function needsWorkersYamlRelocation(): boolean {\n return (\n !process.env.PAI_WORKERS_YAML &&\n !existsSync(defaultWorkersYamlPath()) &&\n [oldWorkersYamlPath(), legacyWorkersYamlPath()].some((p) => existsSync(p))\n );\n}\n\n/**\n * `pai worker config migrate` when workers.yaml is still at an old location\n * (~/.claude/workers.yaml or, older still, ~/.config/pai/workers.yaml): a\n * byte-for-byte copy to the new path (comments, keys, everything — this only\n * changes where the file lives), verified, then the old file is renamed\n * aside as workers.yaml.migrated-<YYYYMMDD> (never deleted). No JSON\n * involved, and no secrets are read or transformed beyond copying bytes.\n */\nexport function relocateWorkersYaml(opts: { force?: boolean; dryRun?: boolean } = {}): RelocateResult {\n const toPath = writeTargetWorkersYamlPath();\n const result = migratePaiFile(toPath, [oldWorkersYamlPath(), legacyWorkersYamlPath()], opts);\n if (!result.dryRun && result.fromPath) chmodSync(toPath, 0o600);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Inlining key_file contents as `key:`\n// ---------------------------------------------------------------------------\n\nexport interface InlineKeysResult {\n yamlPath: string;\n inlined: { provider: string; keyFilePath: string }[];\n dryRun: boolean;\n}\n\n/**\n * `pai worker config inline-keys`: for every provider with a `key_file` and\n * no `key`, read the file, write its trimmed contents as a quoted `key:`,\n * and remove `key_file`. The key file itself is left on disk — this only\n * changes what workers.yaml reads from, never deletes a credential the\n * operator might still want. `dryRun` computes the plan (provider names and\n * key file paths only — never the key values) without writing anything.\n */\nexport function inlineWorkersYamlKeys(opts: { dryRun?: boolean } = {}): InlineKeysResult {\n const yamlPath = workersYamlPath();\n const existing = readWorkersYaml(yamlPath);\n if (!existing) {\n throw new WorkersConfigError(`${yamlPath} does not exist — run \\`pai worker config init\\` first`);\n }\n const { doc, data } = existing;\n const inlined: { provider: string; keyFilePath: string }[] = [];\n for (const [name, p] of Object.entries(data.providers)) {\n if (p.key || !p.keyFile) continue;\n const keyPath = expandHome(p.keyFile);\n let content: string;\n try {\n content = readFileSync(keyPath, \"utf8\");\n } catch (e) {\n throw new WorkersConfigError(\n `providers.${name}.key_file: could not read ${keyPath}: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n const token = content.trim();\n if (!token) throw new WorkersConfigError(`providers.${name}.key_file: ${keyPath} is empty`);\n inlined.push({ provider: name, keyFilePath: p.keyFile });\n if (!opts.dryRun) {\n doc.setIn([\"providers\", name, \"key\"], quotedKeyNode(token));\n doc.deleteIn([\"providers\", name, \"key_file\"]);\n }\n }\n if (!opts.dryRun && inlined.length) {\n writeWorkersYamlText(yamlPath, String(doc));\n }\n return { yamlPath, inlined, dryRun: !!opts.dryRun };\n}\n","/**\n * config.ts — the `workers` section of the PAI config file (CONFIG_FILE,\n * see src/daemon/config.ts's paiConfigFilePath — ~/.claude/pai/config.yaml\n * today, config.json until `pai config yaml` runs).\n *\n * Everything that knows about worker providers reads this module: the CLI\n * (`pai worker …`), the MCP tools (worker_*), and the Agent-routing hook.\n * Keep it free of commander/MCP imports so all three layers stay thin over it.\n *\n * Keys are never stored here — only paths to 0600 files. A provider without a\n * keyFile is a local server and gets the placeholder token \"local\".\n *\n * `protocol: \"openai\"` providers run through the PAI proxy (src/workers/proxy):\n * `upstreamUrl` is their Chat Completions base, and `run` points\n * ANTHROPIC_BASE_URL at the local proxy with the provider name in the path.\n * `engine: \"codex\"` providers run through the Codex CLI instead of Claude\n * Code.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { CONFIG_FILE, readMainConfigRaw, writeMainConfigRaw } from \"../daemon/config.js\";\nimport { paiHomePath } from \"../config/pai-home.js\";\nimport { contextWindowFromModelId, DEFAULT_CONTEXT_WINDOW } from \"../utils/model-window.js\";\nimport { readWorkersYaml, workersYamlPath, writeWorkersYaml, type WorkersYamlData } from \"./workers-config.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Wire protocol a provider speaks: \"anthropic\" natively, \"openai\" through the\n * PAI proxy (which translates the Anthropic Messages API to Chat Completions).\n */\nexport type WorkerProtocol = \"anthropic\" | \"openai\";\n\n/**\n * Runner executable behind a provider: Claude Code, the Codex CLI, or the\n * \"image\" engine (src/workers/engines/image.ts — an OpenAI-compatible\n * images API, not a claude/codex spawn).\n */\nexport type WorkerEngine = \"claude\" | \"codex\" | \"image\";\n\n/** One quota window the statusline renders for a provider (e.g. \"5h\", \"7d\"). */\nexport interface UsageWindow {\n /** Window label shown in the statusline, e.g. \"5h\". */\n name: string;\n /** jq expression against the usage response yielding a percent 0–100. */\n percent: string;\n /** jq expression against the usage response yielding the reset time. */\n resetAt?: string;\n /** How resetAt is interpreted: epoch ms (default), epoch s, or ISO string. */\n resetUnit?: \"ms\" | \"s\" | \"iso\";\n}\n\n/**\n * How the statusline fetches and renders a provider's plan quota. The block\n * names a JSON GET endpoint plus per-window jq expressions, so a new provider\n * is config, not code in statusline-command.sh.\n */\nexport interface ProviderUsage {\n /** GET endpoint returning the usage JSON. */\n url: string;\n /**\n * Auth header template, default \"Authorization: Bearer\"; the key from\n * keyFile is appended after a space. A value without a space (e.g.\n * \"x-api-key\") is sent as \"<authHeader>: <key>\".\n */\n authHeader?: string;\n /** Display label for the usage segments, default = provider name. */\n label?: string;\n windows: UsageWindow[];\n /** Statusline cache TTL in seconds, default 60. */\n ttlSeconds?: number;\n}\n\nexport interface WorkerProvider {\n enabled: boolean;\n /** Wire protocol the baseUrl speaks. */\n protocol: WorkerProtocol;\n /** Anthropic-compatible Messages API base. */\n baseUrl: string;\n /** 0600 file holding the auth token; null for local servers (\"local\"). */\n keyFile: string | null;\n /**\n * The auth token itself, inline in workers.yaml. Wins over keyFile when\n * both are set (`pai worker config check` notices this). Keeping the key\n * out of a separate file is the operator's explicit call — the file this\n * lives in must be 0600 (writeWorkersYamlText enforces that) and is never\n * committed. See resolveProviderKey for the one place this is read.\n */\n key?: string;\n /** Model id per capability; see MODEL_CAPABILITIES. Only default is required. */\n models: { default: string } & Partial<Record<ModelCapability, string>>;\n /**\n * Model id → tier alias, overriding the built-in mapping (models.fast →\n * haiku tier, models.default → sonnet tier). Lets a provider pin an extra\n * model id to a tier, e.g. a heavyweight default to the opus tier.\n */\n modelTiers?: Record<string, ModelTier>;\n /** Extra environment variables for runs through this provider (string values). */\n env: Record<string, string>;\n note?: string;\n /**\n * OpenAI Chat Completions base (e.g. \"https://api.openai.com/v1\"). Required\n * for protocol \"openai\"; read by the PAI proxy, never by the runner.\n */\n upstreamUrl?: string;\n /** Runner for this provider; \"codex\" goes through the Codex CLI. */\n engine?: WorkerEngine;\n /** Optional shell command printing 0–100 (percent of quota used). */\n quotaProbe?: string;\n /** Auto-routing skips the provider at or above this percentage. Default 95. */\n quotaSkipAt?: number;\n /**\n * Context window of the provider's model, for the context meter. No\n * default: the meter only shows a window the init event announced (or\n * this explicit value, for engines without one, e.g. codex).\n */\n contextWindow?: number;\n /** Cost tier 1 (cheapest) … 5 (most expensive); classes cap it via maxCostTier. */\n costTier?: number;\n /** Capability tags; classes filter auto-routing via requireTags. */\n tags?: ProviderTag[];\n /** Statusline plan-quota block; see ProviderUsage. Absent = \"usage n/a\". */\n usage?: ProviderUsage;\n /**\n * True only for the synthetic built-in \"anthropic\" provider (see\n * ANTHROPIC_NATIVE): plain Claude Code, on its own OAuth/Max-plan login —\n * no baseUrl, no key file, no config entry. Never set by parseProvider.\n */\n native?: boolean;\n}\n\n/**\n * Reserved provider name for plain Anthropic: Claude Code's own OAuth/Max-plan\n * login, no base URL override and no API key. It never needs (or accepts) a\n * `providers.anthropic` config entry — resolveTarget/mustExist synthesize it\n * on demand via `nativeAnthropicProvider()`.\n */\nexport const ANTHROPIC_NATIVE = \"anthropic\";\n\n/**\n * Models the built-in provider runs on. This is the only place a model id is\n * named for it: run.ts resolves the class capability against this table like\n * it does for any configured provider and passes `--model` explicitly.\n *\n * Workers exist to parallelise and to save cost, so they must never inherit\n * the orchestrator's model. A bare headless `claude` takes the interactive\n * session default, and one probe came up on the most expensive tier because\n * the chat session had been switched to it. Sonnet is the working tier;\n * haiku serves the fast classes (spotcheck, simple).\n */\nexport const NATIVE_ANTHROPIC_MODELS: WorkerProvider[\"models\"] = {\n default: \"claude-sonnet-5\",\n fast: \"claude-haiku-4-5-20251001\",\n};\n\n/**\n * The synthetic provider object for ANTHROPIC_NATIVE. `baseUrl` is empty and\n * there is no key file, so buildRunEnv strips every provider env override;\n * the models come from NATIVE_ANTHROPIC_MODELS so a run always names its\n * model on the command line.\n */\nexport function nativeAnthropicProvider(\n models: WorkerProvider[\"models\"] = NATIVE_ANTHROPIC_MODELS\n): WorkerProvider {\n return {\n enabled: true,\n protocol: \"anthropic\",\n baseUrl: \"\",\n keyFile: null,\n models: { ...models },\n env: {},\n native: true,\n };\n}\n\n/**\n * Provider by name, synthesizing ANTHROPIC_NATIVE when it is asked for. Reads\n * `config.nativeModels` (workers.yaml's documented `providers.anthropic.models`\n * override, if any) so a config that pins a different default/fast id for the\n * built-in provider is honored everywhere a provider is resolved.\n */\nexport function getProviderOrNative(\n config: { providers: Record<string, WorkerProvider>; nativeModels?: WorkerProvider[\"models\"] },\n name: string\n): WorkerProvider | undefined {\n if (name === ANTHROPIC_NATIVE) return nativeAnthropicProvider(config.nativeModels);\n return config.providers[name];\n}\n\nexport interface WorkersPaneConfig {\n enabled: boolean;\n /** Font size (points) of the follow-pane profile's font. */\n fontSize: number;\n /** Seconds a pane lingers after its worker goes quiet. */\n autoExitSecs: number;\n}\n\nexport interface WorkersRoutingConfig {\n /** Provider names in preference order; first usable one wins. */\n order: string[];\n /** Minutes a provider sits in cooldown after a quota/rate failure. */\n cooldownMinutes: number;\n /** Reroute a failed-before-first-tool run to the next provider. */\n retryOnQuota: boolean;\n}\n\n/** Sub-worker caps: how deep the worker tree may grow, how wide per parent. */\nexport interface WorkersTreeConfig {\n /** Maximum nesting depth of sub-workers (top-level = 0). */\n maxDepth: number;\n /** Maximum concurrently running children per parent. */\n maxChildren: number;\n}\n\n/** Cost/quality tier of a provider's model, 1 (cheapest) … 5 (most expensive). */\nexport type CostTier = 1 | 2 | 3 | 4 | 5;\n\n/** The tier aliases the CLI and daemon tables understand — class proxies, not\n * Anthropic model names: any provider's model maps onto one of these. */\nexport type ModelTier = \"haiku\" | \"sonnet\" | \"opus\";\n\nconst MODEL_TIERS: readonly ModelTier[] = [\"haiku\", \"sonnet\", \"opus\"];\n\nexport const DEFAULT_COST_TIER = 3;\n\n/** Tags a provider may carry; classes filter auto-routing on them. */\nexport const PROVIDER_TAGS = [\n \"code\",\n \"vision\",\n \"image-gen\",\n \"long-context\",\n \"fast\",\n \"reasoning\",\n] as const;\n\nexport type ProviderTag = (typeof PROVIDER_TAGS)[number];\n\n/** The standard task classes; `workers.classes` maps each to a target. */\nexport const WORKER_CLASSES = [\n \"draft\",\n \"plan\",\n \"implement\",\n \"review\",\n \"research\",\n \"spotcheck\",\n \"simple\",\n \"complex\",\n \"image\",\n] as const;\n\nexport type WorkerClassName = (typeof WORKER_CLASSES)[number];\n\n/**\n * The well-known model capabilities — documented, and what the starter\n * workers.yaml and `pai worker model`'s listing show by name. The set is\n * open, though: a provider's `models` block may carry any capability name\n * matching CAPABILITY_NAME_RE (see isModelCapability), e.g. \"vision\" or\n * \"longcontext\" for a provider that serves them. \"default\" is the required\n * catch-all; the others name what a model is *for* — \"fast\" the cheap tier\n * (spotcheck, haiku-tier spawns), \"image\" the image class/capability.\n * Everything resolves through resolveModelCapability, falling back to\n * default; cross-provider preference for a capability is `capabilities:` in\n * workers.yaml (see resolveCapability).\n */\nexport const MODEL_CAPABILITIES = [\"default\", \"fast\", \"image\"] as const;\n\nexport type ModelCapability = string;\n\nexport const CAPABILITY_NAME_RE = /^[a-z][a-z0-9-]*$/;\n\n/** Is this string a syntactically valid capability name (open set)? */\nexport function isModelCapability(v: string): v is ModelCapability {\n return CAPABILITY_NAME_RE.test(v);\n}\n\n/**\n * Which model capability a class runs on when its target names no alias: the\n * image class uses the image model, the cheap classes (spotcheck, simple) the\n * fast model, every other class the provider default. A provider without a\n * fast model falls back to its default (resolveModelCapability).\n */\nconst CLASS_MODEL_CAPABILITY: Record<WorkerClassName, ModelCapability> = {\n draft: \"default\",\n plan: \"default\",\n implement: \"default\",\n review: \"default\",\n research: \"default\",\n spotcheck: \"fast\",\n simple: \"fast\",\n complex: \"default\",\n image: \"image\",\n};\n\n/** Capability for a run's class (default when unset or not a standard class). */\nexport function classModelCapability(className?: string): ModelCapability {\n return (className && CLASS_MODEL_CAPABILITY[className as WorkerClassName]) || \"default\";\n}\n\n/**\n * A class target: \"<provider>\", \"<provider>/<modelAlias>\", or an object. The\n * object either pins a `provider` (plus optional `mcp` allowlist) or only\n * constrains auto-routing (`maxCostTier`, `requireTags`, per-class `order`).\n */\nexport type ClassTarget =\n | string\n | {\n provider?: string;\n mcp?: string[];\n /** Auto-routing may only use providers at or below this cost tier. */\n maxCostTier?: number;\n /** Auto-routing may only use providers carrying all these tags. */\n requireTags?: string[];\n /** Provider order for this class; defaults to routing.order. */\n order?: string[];\n };\n\n/**\n * State of the machine-wide Claude Code fallback (`pai worker fallback on`):\n * every new Claude Code process runs on `provider` until `fallback off`.\n * `saved` holds what ~/.claude/settings.json carried before the switch so\n * `off` can restore it exactly.\n */\nexport interface WorkersFallback {\n /** Provider every new Claude Code process is pointed at. */\n provider: string;\n /**\n * settings.json before the switch. `env` records the previous value of\n * every env key fallback touched (null = the key was absent), `model` the\n * previous top-level model pin (null = none), `envExisted` whether an env\n * block existed at all.\n */\n saved: {\n env: Record<string, string | null>;\n model: string | null;\n envExisted: boolean;\n };\n /** ISO stamp of the switch (shown by `fallback status`). */\n on: string;\n}\n\nexport interface WorkersConfig {\n enabled: boolean;\n /** Provider name, or \"auto\" for routing.order resolution. */\n active: string | null;\n providers: Record<string, WorkerProvider>;\n /** Class → target; see ClassTarget. (Reads the legacy `roles` key.) */\n classes: Record<string, ClassTarget>;\n /** MCP set name → server names; `--mcp <set>` and class `mcp` expand these. */\n mcpSets: Record<string, string[]>;\n /**\n * Capability → provider names in preference order (workers.yaml\n * `capabilities:`), e.g. `{ image: [\"pictures\", \"glm\"] }`. Cross-provider,\n * unlike a provider's own `models` table: this is what lets `--capability\n * image` find the one provider configured to serve it. See resolveCapability.\n */\n capabilities: Record<string, string[]>;\n pane: WorkersPaneConfig;\n logDir: string;\n routing: WorkersRoutingConfig;\n /** Sub-worker caps (workers.tree). */\n tree: WorkersTreeConfig;\n /**\n * Daemon cache-keepalive cadence in seconds: how often a trivial\n * single-turn heartbeat worker re-arms the provider prompt cache\n * (src/workers/keepalive.ts). 0 = off.\n */\n cacheKeepaliveSecs: number;\n /**\n * Run native-Anthropic workers through `caveman claude` (workers.caveman).\n * Off pins them to api.anthropic.com even when the user settings route\n * every claude through a proxy; see claudeCommand in run-env.ts.\n */\n caveman: boolean;\n /** Machine-wide Claude Code fallback; null = off. */\n fallback: WorkersFallback | null;\n /**\n * Model ids for the built-in `anthropic` provider, when workers.yaml\n * documents an override under `providers.anthropic.models`. Defaults to\n * NATIVE_ANTHROPIC_MODELS.\n */\n nativeModels: WorkerProvider[\"models\"];\n}\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_LOG_DIR = \"~/.claude/logs/workers\";\n\nexport const DEFAULT_PANE: WorkersPaneConfig = {\n enabled: true,\n fontSize: 13,\n autoExitSecs: 60,\n};\n\nexport const DEFAULT_ROUTING: WorkersRoutingConfig = {\n order: [],\n cooldownMinutes: 30,\n retryOnQuota: true,\n};\n\nexport const DEFAULT_TREE: WorkersTreeConfig = {\n maxDepth: 2,\n maxChildren: 4,\n};\n\n/**\n * Cache-keepalive cadence when the config names none. Measured 2026-09-18\n * (pair probes through the real worker spawn path, numbers in\n * docs/cache-keepalive.md): the implicit provider cache only serves a fresh\n * worker warm within roughly the first minute (positive back-to-back, gone\n * at 2 min), and it covers only ~2.6k of the ~18k-token prefix. Holding it\n * needs a beat every <2 min — a continuous bill for a small saving — so the\n * default is OFF and arming it is the operator's explicit call (set e.g.\n * \"cacheKeepaliveSecs\": 60).\n */\nexport const DEFAULT_CACHE_KEEPALIVE_SECS = 0;\n\n/**\n * The default MCP sets every config starts from. `desktop` names the clickr\n * server so `--mcp desktop` hands a worker the machine controls (read-only\n * tools always; actuating ones after the operator hands the controls over,\n * see `pai worker controls`). A user's mcpSets section is merged over this,\n * so `desktop: []` removes the set deliberately.\n */\nexport const DEFAULT_MCP_SETS: Record<string, string[]> = {\n desktop: [\"clickr\"],\n};\n\nexport function defaultWorkersConfig(): WorkersConfig {\n return {\n enabled: false,\n active: null,\n providers: {},\n classes: {},\n mcpSets: { ...DEFAULT_MCP_SETS },\n capabilities: {},\n pane: { ...DEFAULT_PANE },\n logDir: DEFAULT_LOG_DIR,\n routing: { ...DEFAULT_ROUTING, order: [] },\n tree: { ...DEFAULT_TREE },\n cacheKeepaliveSecs: DEFAULT_CACHE_KEEPALIVE_SECS,\n caveman: false,\n fallback: null,\n nativeModels: { ...NATIVE_ANTHROPIC_MODELS },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport class WorkersConfigError extends Error {}\n\nfunction bad(path: string, why: string): never {\n throw new WorkersConfigError(`workers${path}: ${why}`);\n}\n\nfunction str(v: unknown): string {\n return typeof v === \"string\" ? v : \"\";\n}\n\n/**\n * Parse a `models` block (capability → model id, \"default\" required). Shared\n * by parseProvider and the YAML loader's builtin-anthropic override, which\n * has no other provider fields to validate.\n */\nexport function parseModelsBlock(pathPrefix: string, modelsRaw: unknown): WorkerProvider[\"models\"] {\n const raw = modelsRaw === undefined ? {} : modelsRaw;\n if (typeof raw !== \"object\" || raw === null) bad(pathPrefix, \"must be an object\");\n const m = raw as Record<string, unknown>;\n const defaultModel = str(m.default);\n if (!defaultModel) bad(`${pathPrefix}.default`, \"is required\");\n const models: WorkerProvider[\"models\"] = { default: defaultModel };\n for (const key of Object.keys(m)) {\n if (key === \"default\") continue;\n if (!isModelCapability(key)) {\n bad(\n `${pathPrefix}.${key}`,\n `\"${key}\" is not a valid capability name (must match ^[a-z][a-z0-9-]*$; well-known: ${MODEL_CAPABILITIES.join(\", \")}, but any name in that shape is accepted)`\n );\n }\n const id = str(m[key]);\n if (!id) bad(`${pathPrefix}.${key}`, \"must be a non-empty model id\");\n models[key] = id;\n }\n return models;\n}\n\n/** Parse and validate one provider entry (shared by JSON and YAML loading). */\nexport function parseProvider(name: string, raw: unknown): WorkerProvider {\n if (name === ANTHROPIC_NATIVE) {\n bad(\n `.providers.${name}`,\n `\"${ANTHROPIC_NATIVE}\" is reserved for plain Anthropic (Claude Code's own OAuth/Max-plan login) and cannot be configured here — remove this entry; use --provider ${ANTHROPIC_NATIVE} or \"pai worker providers use ${ANTHROPIC_NATIVE}\" instead`\n );\n }\n if (typeof raw !== \"object\" || raw === null) bad(`.providers.${name}`, \"must be an object\");\n const p = raw as Record<string, unknown>;\n\n const protocol = p.protocol === undefined ? \"anthropic\" : str(p.protocol);\n if (protocol !== \"anthropic\" && protocol !== \"openai\") {\n bad(`.providers.${name}.protocol`, `\"${str(p.protocol)}\" is neither \"anthropic\" nor \"openai\"`);\n }\n const engine = p.engine === undefined ? \"claude\" : str(p.engine);\n if (engine !== \"claude\" && engine !== \"codex\" && engine !== \"image\") {\n bad(`.providers.${name}.engine`, `\"${str(p.engine)}\" is none of \"claude\", \"codex\", \"image\"`);\n }\n\n const baseUrl = str(p.baseUrl);\n // openai providers reach the model through the PAI proxy; their baseUrl is\n // the proxy URL, filled in by the runner — only anthropic needs one here.\n if (!baseUrl && protocol !== \"openai\") bad(`.providers.${name}.baseUrl`, \"is required\");\n\n const keyFile =\n p.keyFile === undefined || p.keyFile === null || str(p.keyFile) === \"\"\n ? null\n : str(p.keyFile);\n const key = str(p.key) || undefined;\n\n const models = parseModelsBlock(`.providers.${name}.models`, p.models);\n\n let modelTiers: Record<string, ModelTier> | undefined;\n if (p.modelTiers !== undefined) {\n if (typeof p.modelTiers !== \"object\" || p.modelTiers === null || Array.isArray(p.modelTiers)) {\n bad(`.providers.${name}.modelTiers`, \"must be an object of model id → haiku | sonnet | opus\");\n }\n modelTiers = {};\n for (const [id, tier] of Object.entries(p.modelTiers as Record<string, unknown>)) {\n if (typeof tier !== \"string\" || !MODEL_TIERS.includes(tier as ModelTier)) {\n bad(\n `.providers.${name}.modelTiers.${id}`,\n `must be \"haiku\", \"sonnet\" or \"opus\" (got ${JSON.stringify(tier)})`\n );\n }\n modelTiers[id] = tier as ModelTier;\n }\n }\n\n const env: Record<string, string> = {};\n if (p.env !== undefined) {\n if (typeof p.env !== \"object\" || p.env === null || Array.isArray(p.env)) {\n bad(`.providers.${name}.env`, \"must be an object of string values\");\n }\n for (const [k, v] of Object.entries(p.env as Record<string, unknown>)) {\n if (typeof v !== \"string\") bad(`.providers.${name}.env.${k}`, \"must be a string\");\n env[k] = v;\n }\n }\n\n const quotaSkipAt = p.quotaSkipAt === undefined ? undefined : p.quotaSkipAt;\n if (quotaSkipAt !== undefined) {\n if (typeof quotaSkipAt !== \"number\" || quotaSkipAt < 0 || quotaSkipAt > 100) {\n bad(`.providers.${name}.quotaSkipAt`, \"must be a number between 0 and 100\");\n }\n }\n\n const contextWindow = p.contextWindow === undefined ? undefined : p.contextWindow;\n if (contextWindow !== undefined) {\n if (typeof contextWindow !== \"number\" || contextWindow <= 0) {\n bad(`.providers.${name}.contextWindow`, \"must be a positive number of tokens\");\n }\n }\n\n const upstreamUrl = str(p.upstreamUrl);\n if (protocol === \"openai\" && !upstreamUrl) {\n bad(`.providers.${name}.upstreamUrl`, `is required for protocol \"openai\" (the Chat Completions base, e.g. \"https://api.openai.com/v1\")`);\n }\n\n const costTier = p.costTier === undefined ? undefined : p.costTier;\n if (costTier !== undefined) {\n if (typeof costTier !== \"number\" || !Number.isInteger(costTier) || costTier < 1 || costTier > 5) {\n bad(`.providers.${name}.costTier`, \"must be an integer 1 (cheapest) … 5 (most expensive)\");\n }\n }\n\n let tags: ProviderTag[] | undefined;\n if (p.tags !== undefined) {\n if (!Array.isArray(p.tags) || p.tags.some((x) => typeof x !== \"string\")) {\n bad(`.providers.${name}.tags`, `must be an array of tags from: ${PROVIDER_TAGS.join(\", \")}`);\n }\n for (const t of p.tags as string[]) {\n if (!(PROVIDER_TAGS as readonly string[]).includes(t)) {\n bad(`.providers.${name}.tags`, `\"${t}\" is not a tag (from: ${PROVIDER_TAGS.join(\", \")})`);\n }\n }\n tags = p.tags as ProviderTag[];\n }\n\n let usage: ProviderUsage | undefined;\n if (p.usage !== undefined) {\n if (typeof p.usage !== \"object\" || p.usage === null || Array.isArray(p.usage)) {\n bad(`.providers.${name}.usage`, \"must be an object\");\n }\n const u = p.usage as Record<string, unknown>;\n const usageUrl = str(u.url);\n if (!usageUrl) bad(`.providers.${name}.usage.url`, \"is required\");\n if (!Array.isArray(u.windows) || u.windows.length === 0) {\n bad(`.providers.${name}.usage.windows`, \"must be a non-empty array\");\n }\n const windows: UsageWindow[] = [];\n for (const [i, wRaw] of (u.windows as unknown[]).entries()) {\n const wpath = `.providers.${name}.usage.windows[${i}]`;\n if (typeof wRaw !== \"object\" || wRaw === null || Array.isArray(wRaw)) {\n bad(wpath, \"must be an object\");\n }\n const w = wRaw as Record<string, unknown>;\n const wname = str(w.name);\n if (!wname) bad(`${wpath}.name`, \"is required\");\n const percent = str(w.percent);\n if (!percent) bad(`${wpath}.percent`, \"is required (a jq expression yielding 0–100)\");\n const resetUnit = w.resetUnit === undefined ? undefined : str(w.resetUnit);\n if (resetUnit !== undefined && resetUnit !== \"ms\" && resetUnit !== \"s\" && resetUnit !== \"iso\") {\n bad(`${wpath}.resetUnit`, `must be \"ms\", \"s\" or \"iso\"`);\n }\n windows.push({\n name: wname,\n percent,\n ...(str(w.resetAt) ? { resetAt: str(w.resetAt) } : {}),\n ...(resetUnit ? { resetUnit } : {}),\n });\n }\n const ttlSeconds = u.ttlSeconds === undefined ? undefined : u.ttlSeconds;\n if (ttlSeconds !== undefined && (typeof ttlSeconds !== \"number\" || ttlSeconds <= 0)) {\n bad(`.providers.${name}.usage.ttlSeconds`, \"must be a positive number of seconds\");\n }\n usage = {\n url: usageUrl,\n ...(str(u.authHeader) ? { authHeader: str(u.authHeader) } : {}),\n ...(str(u.label) ? { label: str(u.label) } : {}),\n windows,\n ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),\n };\n }\n\n return {\n enabled: p.enabled === undefined ? true : p.enabled === true,\n protocol,\n baseUrl,\n keyFile,\n ...(key ? { key } : {}),\n models,\n ...(modelTiers ? { modelTiers } : {}),\n env,\n ...(str(p.note) ? { note: str(p.note) } : {}),\n ...(upstreamUrl ? { upstreamUrl } : {}),\n ...(engine !== \"claude\" ? { engine } : {}),\n ...(str(p.quotaProbe) ? { quotaProbe: str(p.quotaProbe) } : {}),\n ...(quotaSkipAt !== undefined ? { quotaSkipAt } : {}),\n ...(contextWindow !== undefined ? { contextWindow } : {}),\n ...(costTier !== undefined ? { costTier } : {}),\n ...(tags ? { tags } : {}),\n ...(usage ? { usage } : {}),\n };\n}\n\n/**\n * Parse a `classes` (or legacy `roles`) value shared by JSON and YAML\n * loading. `badPathPrefix` names the field in error messages, e.g. \".classes\".\n */\nexport function parseClassesValue(\n classesRaw: unknown,\n badPathPrefix: string\n): Record<string, ClassTarget> {\n const classes: Record<string, ClassTarget> = {};\n if (classesRaw === undefined) return classes;\n if (typeof classesRaw !== \"object\" || classesRaw === null || Array.isArray(classesRaw)) {\n bad(badPathPrefix, \"must be an object of class → provider[/alias] or {provider, mcp, maxCostTier, requireTags, order}\");\n }\n for (const [cls, target] of Object.entries(classesRaw as Record<string, unknown>)) {\n if (typeof target === \"object\" && target !== null && !Array.isArray(target)) {\n const o = target as Record<string, unknown>;\n const provider = str(o.provider);\n if (o.provider !== undefined && (!provider || provider.includes(\" \"))) {\n bad(`${badPathPrefix}.${cls}.provider`, `invalid provider \"${provider}\"`);\n }\n let mcp: string[] | undefined;\n if (o.mcp !== undefined) {\n if (!Array.isArray(o.mcp) || o.mcp.some((x) => typeof x !== \"string\")) {\n bad(`${badPathPrefix}.${cls}.mcp`, \"must be an array of MCP server or set names\");\n }\n mcp = o.mcp as string[];\n }\n let maxCostTier: number | undefined;\n if (o.maxCostTier !== undefined) {\n if (\n typeof o.maxCostTier !== \"number\" ||\n !Number.isInteger(o.maxCostTier) ||\n o.maxCostTier < 1 ||\n o.maxCostTier > 5\n ) {\n bad(`${badPathPrefix}.${cls}.maxCostTier`, \"must be an integer 1 … 5\");\n }\n maxCostTier = o.maxCostTier;\n }\n let requireTags: string[] | undefined;\n if (o.requireTags !== undefined) {\n if (!Array.isArray(o.requireTags) || o.requireTags.some((x) => typeof x !== \"string\")) {\n bad(`${badPathPrefix}.${cls}.requireTags`, `must be an array of tags from: ${PROVIDER_TAGS.join(\", \")}`);\n }\n for (const t of o.requireTags as string[]) {\n if (!(PROVIDER_TAGS as readonly string[]).includes(t)) {\n bad(`${badPathPrefix}.${cls}.requireTags`, `\"${t}\" is not a tag (from: ${PROVIDER_TAGS.join(\", \")})`);\n }\n }\n requireTags = o.requireTags as string[];\n }\n let order: string[] | undefined;\n if (o.order !== undefined) {\n if (!Array.isArray(o.order) || o.order.some((x) => typeof x !== \"string\")) {\n bad(`${badPathPrefix}.${cls}.order`, \"must be an array of provider names\");\n }\n order = o.order as string[];\n }\n const obj: ClassTarget = {\n ...(provider ? { provider } : {}),\n ...(mcp ? { mcp } : {}),\n ...(maxCostTier !== undefined ? { maxCostTier } : {}),\n ...(requireTags ? { requireTags } : {}),\n ...(order ? { order } : {}),\n };\n classes[cls] = Object.keys(obj).length ? obj : {};\n } else {\n const t = str(target);\n if (!t || t.includes(\" \")) bad(`${badPathPrefix}.${cls}`, `invalid target \"${t}\"`);\n classes[cls] = t;\n }\n }\n return classes;\n}\n\n/**\n * Parse an `mcpSets` (or `mcp_sets`) value shared by JSON and YAML loading.\n * Always merged over DEFAULT_MCP_SETS, so an omitted `desktop` key keeps the\n * built-in clickr set (see DEFAULT_MCP_SETS).\n */\nexport function parseMcpSetsValue(raw: unknown, badPathPrefix: string): Record<string, string[]> {\n const mcpSets: Record<string, string[]> = { ...DEFAULT_MCP_SETS };\n if (raw === undefined) return mcpSets;\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n bad(badPathPrefix, \"must be an object of set name → [server names]\");\n }\n for (const [setName, servers] of Object.entries(raw as Record<string, unknown>)) {\n if (!Array.isArray(servers) || servers.some((x) => typeof x !== \"string\")) {\n bad(`${badPathPrefix}.${setName}`, \"must be an array of MCP server names\");\n }\n mcpSets[setName] = servers as string[];\n }\n return mcpSets;\n}\n\n/**\n * Parse a `capabilities` value shared by JSON and YAML loading: capability\n * name (open set, see isModelCapability) → provider names in preference\n * order. Provider names are not cross-checked here — a name that stops\n * existing is simply skipped by resolveCapability at resolve time, the same\n * way routing.order tolerates a removed provider.\n */\nexport function parseCapabilitiesValue(raw: unknown, badPathPrefix: string): Record<string, string[]> {\n const capabilities: Record<string, string[]> = {};\n if (raw === undefined) return capabilities;\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n bad(badPathPrefix, \"must be an object of capability name → [provider names]\");\n }\n for (const [name, order] of Object.entries(raw as Record<string, unknown>)) {\n if (!isModelCapability(name)) {\n bad(`${badPathPrefix}.${name}`, `\"${name}\" is not a valid capability name (must match ^[a-z][a-z0-9-]*$)`);\n }\n if (!Array.isArray(order) || order.length === 0 || order.some((x) => typeof x !== \"string\" || !x)) {\n bad(`${badPathPrefix}.${name}`, \"must be a non-empty array of provider names\");\n }\n capabilities[name] = order as string[];\n }\n return capabilities;\n}\n\n/**\n * Parse and validate a raw `workers` value. Missing section → defaults.\n * Unknown-but-typed garbage → WorkersConfigError naming the offending field.\n */\nexport function parseWorkersConfig(raw: unknown): WorkersConfig {\n const d = defaultWorkersConfig();\n if (raw === undefined || raw === null) return d;\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n bad(\"\", \"section must be an object\");\n }\n const w = raw as Record<string, unknown>;\n\n const providers: Record<string, WorkerProvider> = {};\n if (w.providers !== undefined) {\n if (typeof w.providers !== \"object\" || w.providers === null || Array.isArray(w.providers)) {\n bad(\".providers\", \"must be an object keyed by provider name\");\n }\n for (const [name, p] of Object.entries(w.providers)) {\n providers[name] = parseProvider(name, p);\n }\n }\n\n // classes is canonical; a config that still carries the pre-classes `roles`\n // key is migrated by reading it here — the next write stores only `classes`.\n const classesRaw = w.classes !== undefined ? w.classes : w.roles;\n const classes = parseClassesValue(classesRaw, w.classes !== undefined ? \".classes\" : \".roles\");\n\n const mcpSets = parseMcpSetsValue(w.mcpSets, \".mcpSets\");\n const capabilities = parseCapabilitiesValue(w.capabilities, \".capabilities\");\n\n let pane = { ...DEFAULT_PANE };\n if (w.pane !== undefined) {\n if (typeof w.pane !== \"object\" || w.pane === null) bad(\".pane\", \"must be an object\");\n const pc = w.pane as Record<string, unknown>;\n if (pc.enabled !== undefined && typeof pc.enabled !== \"boolean\") bad(\".pane.enabled\", \"must be boolean\");\n if (pc.fontSize !== undefined && (typeof pc.fontSize !== \"number\" || pc.fontSize <= 0)) {\n bad(\".pane.fontSize\", \"must be a positive number of points\");\n }\n if (pc.autoExitSecs !== undefined && typeof pc.autoExitSecs !== \"number\") {\n bad(\".pane.autoExitSecs\", \"must be a number\");\n }\n // legacy fontScale (a relative scale, superseded by fontSize) is tolerated and ignored\n pane = {\n enabled: pc.enabled === undefined ? DEFAULT_PANE.enabled : pc.enabled === true,\n fontSize: pc.fontSize === undefined ? DEFAULT_PANE.fontSize : pc.fontSize,\n autoExitSecs: pc.autoExitSecs === undefined ? DEFAULT_PANE.autoExitSecs : pc.autoExitSecs,\n };\n }\n\n let routing = { ...DEFAULT_ROUTING, order: [] as string[] };\n if (w.routing !== undefined) {\n if (typeof w.routing !== \"object\" || w.routing === null) bad(\".routing\", \"must be an object\");\n const r = w.routing as Record<string, unknown>;\n if (r.order !== undefined) {\n if (!Array.isArray(r.order) || r.order.some((x) => typeof x !== \"string\")) {\n bad(\".routing.order\", \"must be an array of provider names\");\n }\n routing.order = r.order as string[];\n }\n if (r.cooldownMinutes !== undefined && typeof r.cooldownMinutes !== \"number\") {\n bad(\".routing.cooldownMinutes\", \"must be a number\");\n }\n if (r.retryOnQuota !== undefined && typeof r.retryOnQuota !== \"boolean\") {\n bad(\".routing.retryOnQuota\", \"must be boolean\");\n }\n routing = {\n order: routing.order,\n cooldownMinutes: r.cooldownMinutes === undefined ? DEFAULT_ROUTING.cooldownMinutes : r.cooldownMinutes,\n retryOnQuota: r.retryOnQuota === undefined ? DEFAULT_ROUTING.retryOnQuota : r.retryOnQuota === true,\n };\n }\n\n let tree = { ...DEFAULT_TREE };\n if (w.tree !== undefined) {\n if (typeof w.tree !== \"object\" || w.tree === null || Array.isArray(w.tree)) {\n bad(\".tree\", \"must be an object\");\n }\n const t = w.tree as Record<string, unknown>;\n if (t.maxDepth !== undefined) {\n if (typeof t.maxDepth !== \"number\" || !Number.isInteger(t.maxDepth) || t.maxDepth < 0) {\n bad(\".tree.maxDepth\", \"must be a non-negative integer\");\n }\n }\n if (t.maxChildren !== undefined) {\n if (typeof t.maxChildren !== \"number\" || !Number.isInteger(t.maxChildren) || t.maxChildren < 1) {\n bad(\".tree.maxChildren\", \"must be a positive integer\");\n }\n }\n tree = {\n maxDepth: t.maxDepth === undefined ? DEFAULT_TREE.maxDepth : t.maxDepth,\n maxChildren: t.maxChildren === undefined ? DEFAULT_TREE.maxChildren : t.maxChildren,\n };\n }\n\n let cacheKeepaliveSecs = DEFAULT_CACHE_KEEPALIVE_SECS;\n if (w.cacheKeepaliveSecs !== undefined) {\n if (\n typeof w.cacheKeepaliveSecs !== \"number\" ||\n !Number.isInteger(w.cacheKeepaliveSecs) ||\n w.cacheKeepaliveSecs < 0\n ) {\n bad(\".cacheKeepaliveSecs\", \"must be a non-negative integer (seconds, 0 = off)\");\n }\n cacheKeepaliveSecs = w.cacheKeepaliveSecs;\n }\n\n if (w.caveman !== undefined && typeof w.caveman !== \"boolean\") {\n bad(\".caveman\", \"must be true or false\");\n }\n const caveman = w.caveman === true;\n\n const active = w.active === undefined || w.active === null ? null : str(w.active);\n if (active !== null && active !== \"auto\" && !(active in providers)) {\n // Tolerated at parse time (a provider may have been removed while active\n // still names it) but every consumer resolves it to a clear error.\n }\n\n let fallback: WorkersFallback | null = null;\n if (w.fallback !== undefined && w.fallback !== null) {\n if (typeof w.fallback !== \"object\" || Array.isArray(w.fallback)) {\n bad(\".fallback\", \"must be an object (written by `pai worker fallback on`)\");\n }\n const f = w.fallback as Record<string, unknown>;\n const provider = str(f.provider);\n if (!provider) bad(\".fallback.provider\", \"is required\");\n const savedRaw = f.saved;\n if (typeof savedRaw !== \"object\" || savedRaw === null || Array.isArray(savedRaw)) {\n bad(\".fallback.saved\", \"must be an object\");\n }\n const s = savedRaw as Record<string, unknown>;\n if (typeof s.env !== \"object\" || s.env === null || Array.isArray(s.env)) {\n bad(\".fallback.saved.env\", \"must be an object of env key → previous value or null\");\n }\n const env: Record<string, string | null> = {};\n for (const [k, v] of Object.entries(s.env as Record<string, unknown>)) {\n env[k] = v === null || typeof v === \"string\" ? (v as string | null) : null;\n }\n if (s.model !== null && s.model !== undefined && typeof s.model !== \"string\") {\n bad(\".fallback.saved.model\", \"must be a string or null\");\n }\n fallback = {\n provider,\n saved: {\n env,\n model: typeof s.model === \"string\" ? s.model : null,\n envExisted: s.envExisted === true,\n },\n on: str(f.on) || new Date(0).toISOString(),\n };\n }\n\n return {\n enabled: w.enabled === undefined ? d.enabled : w.enabled === true,\n active,\n providers,\n classes,\n mcpSets,\n capabilities,\n pane,\n logDir: str(w.logDir) || d.logDir,\n routing,\n tree,\n cacheKeepaliveSecs,\n caveman,\n fallback,\n nativeModels: { ...NATIVE_ANTHROPIC_MODELS },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Read / write\n// ---------------------------------------------------------------------------\n\nfunction workersYamlDataOf(workers: WorkersConfig): WorkersYamlData {\n return {\n active: workers.active,\n providers: workers.providers,\n classes: workers.classes,\n mcpSets: workers.mcpSets,\n capabilities: workers.capabilities,\n nativeModels: workers.nativeModels,\n };\n}\n\n/**\n * Read the whole config file and return (raw, workers) — the raw record so\n * callers can rewrite it preserving every other section, the parsed+validated\n * workers section. Unreadable config throws, missing is fine. `path`\n * overrides the config location (tests, CLAUDE_SETTINGS_PATH-style dry runs);\n * default CONFIG_FILE (see paiConfigFilePath). Reads via readMainConfigRaw,\n * so a config.yaml next to `path` is preferred over JSON, same as every\n * other main-config reader.\n *\n * Providers, classes, mcpSets and active load from workers.yaml (next to\n * `path`) when it exists; otherwise they fall back to the JSON `workers`\n * section, and then to built-in defaults — nothing breaks before migration\n * (`pai worker config migrate`). Everything else (pane, routing, tree,\n * cacheKeepaliveSecs, fallback, enabled, logDir) always comes from the main\n * config (JSON or YAML).\n */\nexport function readWorkersSection(path: string = CONFIG_FILE): {\n raw: Record<string, unknown>;\n workers: WorkersConfig;\n} {\n const raw = readMainConfigRaw(path);\n const workers = parseWorkersConfig(raw.workers);\n const yaml = readWorkersYaml(workersYamlPath());\n if (yaml) {\n workers.active = yaml.data.active;\n workers.providers = yaml.data.providers;\n workers.classes = yaml.data.classes;\n workers.mcpSets = yaml.data.mcpSets;\n workers.capabilities = yaml.data.capabilities;\n workers.nativeModels = yaml.data.nativeModels;\n }\n return { raw, workers };\n}\n\n/**\n * Write the workers section back, atomically. When workers.yaml exists, its\n * providers/classes/mcpSets/active are synced there (comment-preserving,\n * only the entries that changed are touched) and stripped from the JSON\n * `workers` section; everything else still writes to JSON as before.\n */\nexport function writeWorkersSection(\n raw: Record<string, unknown>,\n workers: WorkersConfig,\n path: string = CONFIG_FILE\n): void {\n const yamlPath = workersYamlPath();\n const usingYaml = existsSync(yamlPath);\n if (usingYaml) {\n writeWorkersYaml(yamlPath, workersYamlDataOf(workers));\n }\n const jsonWorkers = usingYaml\n ? {\n enabled: workers.enabled,\n pane: workers.pane,\n logDir: workers.logDir,\n routing: workers.routing,\n tree: workers.tree,\n cacheKeepaliveSecs: workers.cacheKeepaliveSecs,\n caveman: workers.caveman,\n ...(workers.fallback ? { fallback: workers.fallback } : {}),\n }\n : workers.fallback\n ? workers\n : { ...workers, fallback: undefined };\n raw.workers = jsonWorkers;\n writeMainConfigRaw(raw, path);\n}\n\n/** Expand a leading ~ (config values are written with `~` to stay portable). */\nexport function expandHome(p: string): string {\n if (p === \"~\" || p.startsWith(\"~/\")) return join(homedir(), p.slice(1));\n return p;\n}\n\n// ---------------------------------------------------------------------------\n// Runnability checks (proxy / codex providers included)\n// ---------------------------------------------------------------------------\n\nexport function assertProviderRunnable(name: string, p: WorkerProvider): void {\n if (p.protocol === \"openai\" && !p.upstreamUrl) {\n throw new WorkersConfigError(\n `provider \"${name}\" uses protocol \"openai\" but has no upstreamUrl — ` +\n `set its Chat Completions base (e.g. \"https://api.openai.com/v1\") ` +\n `so the PAI proxy knows where to translate to.`\n );\n }\n}\n\n/** Where a provider's key file lives, or null. Shared by run + test + add. */\nexport function providerKeyPath(p: WorkerProvider): string | null {\n return p.keyFile ? expandHome(p.keyFile) : null;\n}\n\n/**\n * The provider's auth token: inline `key` wins when set, else `key_file`\n * read and trimmed, else null (native/local providers use the \"local\"\n * placeholder). The one place a provider's key value is resolved — every\n * spawn path (buildRunEnv, the codex runner, the openai proxy, the\n * machine-wide fallback) reads through this instead of its own\n * readFileSync, so inline keys work everywhere a key file already did.\n */\nexport function resolveProviderKey(p: WorkerProvider): string | null {\n if (p.key) return p.key;\n const keyPath = providerKeyPath(p);\n if (!keyPath) return null;\n let content: string;\n try {\n content = readFileSync(keyPath, \"utf8\");\n } catch {\n throw new WorkersConfigError(`key file not readable: ${keyPath}`);\n }\n const token = content.trim();\n if (!token) throw new WorkersConfigError(`key file is empty: ${keyPath}`);\n return token;\n}\n\n/** `key: ****` + last 4 chars — never the full value. Used everywhere a\n * provider's key would otherwise be echoed (`providers`, `config check`). */\nexport function maskKey(key: string): string {\n return `****${key.slice(-4)}`;\n}\n\nexport { DEFAULT_CONTEXT_WINDOW } from \"../utils/model-window.js\";\n\n/** Cost tier of a provider for class filtering (unset = 3, the middle). */\nexport function providerCostTier(p: WorkerProvider): number {\n return p.costTier ?? DEFAULT_COST_TIER;\n}\n\n/**\n * The model id for a capability: the provider's preference for it, else its\n * default model — the one resolution rule every consumer (image class, fast\n * tier spawns, env pins) goes through.\n */\nexport function resolveModelCapability(p: WorkerProvider, capability: ModelCapability): string {\n return p.models[capability] ?? p.models.default;\n}\n\n/** Runner behind a provider, defaulting to the Claude Code harness. */\nfunction providerEngine(p: WorkerProvider): WorkerEngine {\n return p.engine ?? \"claude\";\n}\n\n/** Does this provider name a model for the capability (\"default\" always counts)? */\nfunction providerDeclaresCapability(p: WorkerProvider, capability: string): boolean {\n return capability === \"default\" || p.models[capability] !== undefined;\n}\n\n/** A provider usable for this capability: declares it, enabled, and passes assertProviderRunnable. */\nfunction providerUsableForCapability(p: WorkerProvider | undefined, capability: string): p is WorkerProvider {\n if (!p || !p.enabled || !providerDeclaresCapability(p, capability)) return false;\n try {\n assertProviderRunnable(\"\", p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface ResolvedCapability {\n /** Provider name the capability resolved to (\"anthropic\" for the built-in). */\n provider: string;\n model: string;\n engine: WorkerEngine;\n /**\n * True when nothing declared this capability anywhere and the result is\n * just the active provider's default model — a caller should treat this as\n * \"no real image/vision/… provider is configured\", not a genuine match.\n */\n fellBack: boolean;\n}\n\n/**\n * Cross-provider capability resolution (`workers.yaml`'s `capabilities:`\n * map): which provider+model serves a named capability (e.g. \"image\"),\n * independent of any one provider's own `models` table.\n *\n * Resolution order:\n * 1. `capabilities.<name>` (explicit preference list) — first provider\n * that declares the capability, is enabled, and passes\n * assertProviderRunnable.\n * 2. No preference list: the active provider, if it declares the\n * capability.\n * 3. Still nothing: any enabled provider that declares the capability\n * (stable order — provider names sorted, \"anthropic\" included).\n * 4. Nothing anywhere: the active provider's default model, `fellBack: true`.\n */\nexport function resolveCapability(\n workers: Pick<WorkersConfig, \"providers\" | \"active\" | \"capabilities\" | \"nativeModels\">,\n capability: string\n): ResolvedCapability {\n const order = workers.capabilities[capability];\n if (order?.length) {\n for (const name of order) {\n const p = getProviderOrNative(workers, name);\n if (providerUsableForCapability(p, capability)) {\n return { provider: name, model: resolveModelCapability(p, capability), engine: providerEngine(p), fellBack: false };\n }\n }\n throw new WorkersConfigError(\n `no configured provider for capability \"${capability}\" is usable right now ` +\n `(checked, in order: ${order.join(\", \")}) — set one with: pai worker capability ${capability} <provider>`\n );\n }\n\n const activeName = workers.active && workers.active !== \"auto\" ? workers.active : null;\n if (activeName) {\n const p = getProviderOrNative(workers, activeName);\n if (providerUsableForCapability(p, capability)) {\n return { provider: activeName, model: resolveModelCapability(p, capability), engine: providerEngine(p), fellBack: false };\n }\n }\n\n const candidates: Record<string, WorkerProvider> = {\n [ANTHROPIC_NATIVE]: nativeAnthropicProvider(workers.nativeModels),\n ...workers.providers,\n };\n for (const name of Object.keys(candidates).sort()) {\n const p = candidates[name];\n if (providerUsableForCapability(p, capability)) {\n return { provider: name, model: resolveModelCapability(p, capability), engine: providerEngine(p), fellBack: false };\n }\n }\n\n const fallbackName = activeName ?? ANTHROPIC_NATIVE;\n const fallback = getProviderOrNative(workers, fallbackName) ?? nativeAnthropicProvider(workers.nativeModels);\n return {\n provider: fallbackName,\n model: fallback.models.default,\n engine: providerEngine(fallback),\n fellBack: true,\n };\n}\n\n/**\n * Context window used by the meter when the run reports none: an explicit\n * `contextWindow` first, then whatever the default model's id declares\n * (\"[1m]\" → 1,000,000), then the last-resort default.\n */\nexport function providerContextWindow(p: WorkerProvider): number {\n return (\n p.contextWindow ??\n contextWindowFromModelId(p.models.default) ??\n DEFAULT_CONTEXT_WINDOW\n );\n}\n\n/** Directory under which inline keys (MCP `key` field) are stored, 0600. */\nexport function keysDir(): string {\n return paiHomePath(\"keys\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWA,MAAa,yBAAyB;;;;AAKtC,SAAgB,kBAAkB,OAAuB;AAEvD,QADiB,MAAM,QAAQ,kBAAkB,GAAG,CAAC,MAAM,IACxC;;;;;;;;AASrB,SAAgB,yBAAyB,OAAiD;AACxF,KAAI,OAAO,UAAU,YAAY,UAAU,GAAI,QAAO;CACtD,MAAM,IAAI,eAAe,KAAK,MAAM,MAAM,CAAC;AAC3C,KAAI,CAAC,EAAG,QAAO;CACf,MAAM,WAAW,OAAO,EAAE,GAAG;AAC7B,KAAI,CAAC,OAAO,SAAS,SAAS,IAAI,WAAW,EAAG,QAAO;AACvD,QAAO,WAAW;;;;;;;;;;;;;;;;;;;;;ACOpB,MAAa,wBAAwB;;;;;;AAOrC,SAAS,yBAAiC;AACxC,QAAO,YAAY,sBAAsB;;;;AAK3C,SAAS,qBAA6B;AACpC,QAAO,KAAK,SAAS,EAAE,WAAW,sBAAsB;;;;AAK1D,SAAS,wBAAgC;AACvC,QAAO,KAAK,SAAS,EAAE,WAAW,OAAO,sBAAsB;;;;;;;;AASjE,SAAgB,kBAA0B;CACxC,MAAM,WAAW,QAAQ,IAAI;AAC7B,KAAI,SAAU,QAAO;AACrB,QAAO,eACL,wBAAwB,EACxB,CAAC,oBAAoB,EAAE,uBAAuB,CAAC,EAC/C,4BACD;;;;;AAMH,SAAS,6BAAqC;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Z;AACD,MAAK,MAAM,QAAQ,OAAO,KAAK,WAAW,CAAC,MAAM,EAAE;EACjD,MAAM,IAAI,WAAW;AACrB,MAAI,4BAA4B,GAAG,WAAW,CAC5C,QAAO;GAAE,UAAU;GAAM,OAAO,uBAAuB,GAAG,WAAW;GAAE,QAAQ,eAAe,EAAE;GAAE,UAAU;GAAO;;CAIvH,MAAM,eAAe,cAAc;CACnC,MAAM,WAAW,oBAAoB,SAAS,aAAa,IAAI,wBAAwB,QAAQ,aAAa;AAC5G,QAAO;EACL,UAAU;EACV,OAAO,SAAS,OAAO;EACvB,QAAQ,eAAe,SAAS;EAChC,UAAU;EACX;;;AAiBH,SAAgB,UAAkB;AAChC,QAAO,YAAY,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-Caxrq2iQ.mjs","names":["getQueueStats"],"sources":["../src/notifications/config.ts","../src/workers/keepalive.ts","../src/workers/supervision.ts","../src/daemon/daemon/scheduler.ts","../src/daemon/daemon/dispatcher.ts","../src/daemon/daemon/handler.ts","../src/daemon/daemon/server.ts"],"sourcesContent":["/**\n * config.ts — Notification config persistence helpers\n *\n * Reads and writes the `notifications` section of CONFIG_FILE (see\n * src/daemon/config.ts's paiConfigFilePath).\n * Deep-merges with defaults so partial configs work fine.\n *\n * This module is intentionally separate from the daemon's config loader\n * so it can be used standalone (e.g. from CLI commands).\n */\n\nimport { expandHome, readMainConfigRaw, writeMainConfigRaw } from \"../daemon/config.js\";\nimport type {\n NotificationConfig,\n ChannelConfigs,\n RoutingTable,\n NotificationMode,\n} from \"./types.js\";\nimport {\n DEFAULT_NOTIFICATION_CONFIG,\n DEFAULT_CHANNELS,\n DEFAULT_ROUTING,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Deep merge helper (same approach as daemon/config.ts)\n// ---------------------------------------------------------------------------\n\nfunction deepMerge<T extends object>(\n target: T,\n source: Record<string, unknown>\n): T {\n const result = { ...target };\n for (const key of Object.keys(source)) {\n const srcVal = source[key];\n if (srcVal === undefined || srcVal === null) continue;\n const tgtVal = (target as Record<string, unknown>)[key];\n if (\n typeof srcVal === \"object\" &&\n !Array.isArray(srcVal) &&\n typeof tgtVal === \"object\" &&\n tgtVal !== null &&\n !Array.isArray(tgtVal)\n ) {\n (result as Record<string, unknown>)[key] = deepMerge(\n tgtVal as object,\n srcVal as Record<string, unknown>\n );\n } else {\n (result as Record<string, unknown>)[key] = srcVal;\n }\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Load\n// ---------------------------------------------------------------------------\n\n/**\n * Load the notification config from the PAI config file.\n * Returns defaults merged with any stored values.\n */\nexport function loadNotificationConfig(): NotificationConfig {\n let parsed: Record<string, unknown>;\n try {\n parsed = readMainConfigRaw();\n } catch {\n return { ...DEFAULT_NOTIFICATION_CONFIG };\n }\n\n const stored = parsed[\"notifications\"];\n if (!stored || typeof stored !== \"object\") {\n return { ...DEFAULT_NOTIFICATION_CONFIG };\n }\n\n return deepMerge(\n DEFAULT_NOTIFICATION_CONFIG,\n stored as Record<string, unknown>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Save\n// ---------------------------------------------------------------------------\n\n/**\n * Persist the notification config by merging it into the existing\n * CONFIG_FILE. Creates the file if it does not exist.\n */\nexport function saveNotificationConfig(config: NotificationConfig): void {\n let full: Record<string, unknown> = {};\n try {\n full = readMainConfigRaw();\n } catch {\n // Start fresh if the file is unreadable\n }\n\n // Replace the notifications section\n full[\"notifications\"] = config;\n\n writeMainConfigRaw(full);\n}\n\n// ---------------------------------------------------------------------------\n// Patch helpers (used by the set command)\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a partial update to the current notification config and persist it.\n * Returns the new merged config.\n */\nexport function patchNotificationConfig(patch: {\n mode?: NotificationMode;\n channels?: Partial<Partial<ChannelConfigs>>;\n routing?: Partial<RoutingTable>;\n}): NotificationConfig {\n const current = loadNotificationConfig();\n\n if (patch.mode !== undefined) {\n current.mode = patch.mode;\n }\n\n if (patch.channels) {\n current.channels = deepMerge(\n current.channels,\n patch.channels as Record<string, unknown>\n );\n }\n\n if (patch.routing) {\n current.routing = deepMerge(\n current.routing,\n patch.routing as Record<string, unknown>\n );\n }\n\n saveNotificationConfig(current);\n return current;\n}\n\n// Re-export defaults for convenience\nexport { DEFAULT_NOTIFICATION_CONFIG, DEFAULT_CHANNELS, DEFAULT_ROUTING };\nexport { expandHome };\n","/**\n * keepalive.ts — one cache-keepalive beat, shared by the daemon scheduler and\n * the probe script.\n *\n * The provider (GLM anthropic-compat endpoint) caches the worker prefix\n * implicitly — no cache_control blocks — so a trivial single-turn worker spawn\n * through the very same runWorker path re-arms that cache for the next real\n * worker: identical env, identical tool grants, identical WORKER_CONTRACT_PROMPT\n * by construction, because it IS a worker spawn.\n *\n * Measured 2026-09-18 (docs/cache-keepalive.md): the implicit cache only\n * serves spawns within seconds of the previous identical request and never\n * survived a 60 s beat cadence in the armed proof — hence the knob defaults\n * to off and arming it is the operator's explicit call.\n *\n * Deliberately NOT a hand-built claude invocation: duplicated prefix\n * construction is how this repo has shipped real breakage before (probeResume\n * x3, archiver x2). Everything flows through runWorker.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { runWorker, type StreamEvent } from \"./run.js\";\nimport { readWorkersSection } from \"./config.js\";\nimport { appendLedger } from \"./ledger.js\";\nimport { eventsPath, ledgerPath, workersLogDir } from \"./paths.js\";\nimport { loadStatus } from \"./status.js\";\n\n/**\n * The trivial prompt every cache beat (and probe) carries. Kept in one place\n * so the heartbeat arms exactly the prefix a verifying probe measures.\n */\nexport const HEARTBEAT_PROMPT = \"Reply with exactly one word: pong.\";\n\n/** The worker class a beat runs as — the cheapest spawn the config defines. */\nexport const KEEPALIVE_CLASS = \"simple\";\n\n/** Worker label of every beat, so `pai worker ps` can tell them apart. */\nexport const KEEPALIVE_LABEL = \"cache-keepalive\";\n\n/** Cadence a keepalive runs at for this config; 0 keeps it off. */\nexport function keepaliveSecs(workers: { enabled: boolean; cacheKeepaliveSecs: number }): number {\n return workers.enabled ? workers.cacheKeepaliveSecs : 0;\n}\n\n// ---------------------------------------------------------------------------\n// Transcript parsing — the only real usage on this endpoint is the final\n// result event (per-turn assistant usage is zeroed), so a beat and a probe\n// both read exactly that line.\n// ---------------------------------------------------------------------------\n\n/**\n * The LAST `type:\"result\"` event of a worker transcript, or null when the\n * file is missing, unreadable, or carries no result line (a failed run can\n * end without one).\n */\nexport function parseLastResultEvent(path: string): StreamEvent | null {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n let found: StreamEvent | null = null;\n for (const line of text.split(\"\\n\")) {\n if (!line.startsWith(\"{\")) continue;\n let e: StreamEvent;\n try {\n e = JSON.parse(line) as StreamEvent;\n } catch {\n continue;\n }\n if (e.type === \"result\") found = e;\n }\n return found;\n}\n\n/** One worker's cache metrics, as reported by its final result event. */\nexport interface BeatMetrics {\n id: string;\n ok: boolean;\n rc: number | null;\n provider: string | null;\n model: string | null;\n input_tokens: number | null;\n output_tokens: number | null;\n cache_read_input_tokens: number | null;\n cache_creation_input_tokens: number | null;\n duration_api_ms: number | null;\n duration_ms: number | null;\n num_turns: number | null;\n}\n\n/**\n * Metrics of one run from its final result event. Single-turn runs make the\n * cumulative result usage identical to first-turn usage, so a warm cache\n * shows up directly as cache_read_input_tokens > 0.\n */\nexport function extractBeatMetrics(\n m: Omit<BeatMetrics, \"input_tokens\" | \"output_tokens\" | \"cache_read_input_tokens\" | \"cache_creation_input_tokens\" | \"duration_api_ms\" | \"duration_ms\" | \"num_turns\">,\n ev: StreamEvent | null\n): BeatMetrics {\n const u = ev?.usage;\n return {\n ...m,\n input_tokens: u?.input_tokens ?? null,\n output_tokens: u?.output_tokens ?? null,\n cache_read_input_tokens: u?.cache_read_input_tokens ?? null,\n cache_creation_input_tokens: u?.cache_creation_input_tokens ?? null,\n duration_api_ms: ev?.duration_api_ms ?? null,\n duration_ms: ev?.duration_ms ?? null,\n num_turns: ev?.num_turns ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The beat\n// ---------------------------------------------------------------------------\n\nexport interface BeatOptions {\n /** Config path override (tests never touch the live config). */\n configPath?: string;\n /** Preset worker id (tests); a fresh stamp when omitted. */\n id?: string;\n}\n\n/** True while a beat's worker is still running — the overlap guard reads it. */\nlet beatInFlight = false;\n\nexport function beatBusy(): boolean {\n return beatInFlight;\n}\n\n/** `keepalive-<YYYYMMDD-HHMMSS>` — beats are minutes apart, seconds suffice. */\nexport function beatId(d: Date = new Date()): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return (\n `keepalive-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}` +\n `-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`\n );\n}\n\n/**\n * One heartbeat: a single-turn trivial worker through the exact worker spawn\n * path, its result metrics parsed from the transcript, one WORKER-KEEPALIVE\n * ledger line. Returns null when another beat is still running (overlap\n * guard) — a skipped beat is free, a queue of them is not.\n *\n * The beat runs in the workers logDir: no session renders its status line\n * there, so the spawn adopts no spawnerSession and no iTerm identity, and\n * worker supervision has no owner to notify — heartbeats are infrastructure,\n * not somebody's workers.\n */\nexport async function runKeepaliveBeat(opts: BeatOptions = {}): Promise<BeatMetrics | null> {\n if (beatInFlight) return null;\n beatInFlight = true;\n try {\n const { workers: config } = readWorkersSection(opts.configPath);\n const logDir = workersLogDir(config);\n const id = opts.id ?? beatId();\n const rc = await runWorker({\n claudeArgs: [\"-p\", HEARTBEAT_PROMPT],\n className: KEEPALIVE_CLASS,\n label: KEEPALIVE_LABEL,\n noPane: true,\n quiet: true,\n worktreeFlag: false,\n id,\n cwd: logDir,\n });\n const status = loadStatus(logDir, id);\n const metrics = extractBeatMetrics(\n {\n id,\n ok: rc === 0,\n rc,\n provider: status?.provider ?? null,\n model: status?.model ?? null,\n },\n parseLastResultEvent(eventsPath(logDir, id))\n );\n appendLedger(ledgerPath(logDir), \"WORKER-KEEPALIVE\", {\n id,\n provider: metrics.provider,\n model: metrics.model,\n input_tokens: metrics.input_tokens,\n cache_read_input_tokens: metrics.cache_read_input_tokens,\n cache_creation_input_tokens: metrics.cache_creation_input_tokens,\n duration_api_ms: metrics.duration_api_ms,\n });\n return metrics;\n } finally {\n beatInFlight = false;\n }\n}\n","/**\n * supervision.ts — daemon-side worker supervision, event push not polling.\n *\n * An orchestrating session must keep an eye on its workers without sleeping\n * (the Worker skill forbids busy-waiting), the same way the AIBroker daemon\n * keeps an eye on sessions. The PAI daemon already runs all day; this module\n * gives it a tick that watches every worker's status file and pushes one-line\n * events to the owning session when something happens:\n *\n * finished — the run ended clean (state done, rc 0)\n * failed — the run ended badly (state failed/killed/lost, or rc != 0,\n * or the runner pid vanished while state was still running)\n * stalled — state running, runner alive, but no new turn for longer than\n * the stall threshold (PAI_WORKER_STALL_MINUTES, default 10)\n * thrashing — state running, runner alive, turning, but the last N tool\n * executions all failed (PAI_WORKER_THRASH_FAILS, default 5) —\n * a worker that keeps failing every command never goes quiet,\n * so the stall detector alone cannot see it\n * sleeping — state running, one Bash command sleeping N >= 60s — under the\n * stall threshold for runs like `sleep 500` (8.3m), which would\n * otherwise be invisible until they cross it\n *\n * The interactive chat pane (origin \"chat\") is never supervised: it is the\n * operator's own session, not a task worker. Its status file flips to done\n * when the session ends, and reporting that as \"worker finished\" to whoever\n * next opens the same tab is noise, not an outcome.\n *\n * Delivery, in order of preference, never both counted as required:\n * 1. AIBroker `send_to_session` into the orchestrator's terminal — the\n * one-line Agentish-style notification, arriving as a user turn without\n * the orchestrator asking for it. Needs the iTerm identity of the owner,\n * which the status line bridges into the session map (see scope.ts).\n * 2. An append-only event file, <logDir>/supervision/<owner>.events, one\n * JSON line per event. The UserPromptSubmit hook\n * (src/hooks/ts/user-prompt/worker-supervision.ts) surfaces undelivered\n * lines into the session that owns them, so the events reach the model\n * on its next turn even with AIBroker absent.\n *\n * Exactly-once: every event carries a deterministic id and the set of\n * delivered ids per worker is persisted (<logDir>/supervision/state.json), so\n * a daemon restart replays nothing. A first run with no state adopts every\n * already-terminal worker as delivered — supervision reports transitions it\n * observes, not history. Chain stages are separate workers with their own\n * status files and are supervised individually.\n *\n * No model is ever called from here — this is daemon code, and it must stay\n * that way: supervision that bills tokens to watch tokens is a bug.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { alive, isChatPane, loadStatuses, nowStamp, type WorkerStatus } from \"./status.js\";\nimport { itermForClaudeSession } from \"./scope.js\";\n\n// ---------------------------------------------------------------------------\n// Events\n// ---------------------------------------------------------------------------\n\nexport type SupervisionKind = \"finished\" | \"failed\" | \"stalled\" | \"thrashing\" | \"sleeping\";\n\n/** The kinds that fire mid-run and re-arm on turn progress (see eventId). */\nconst MID_RUN_KINDS: readonly SupervisionKind[] = [\"stalled\", \"thrashing\", \"sleeping\"];\n\nexport interface SupervisionEvent {\n /** Deterministic dedup key — see eventId(). */\n id: string;\n /** nowStamp() at detection. */\n ts: string;\n kind: SupervisionKind;\n worker: string;\n label: string;\n /** Owning session key: the spawner's claude session id, or the iTerm uuid. */\n session: string;\n /** Exit code when the run reported one, else null. */\n rc: number | null;\n /** Minutes without a turn, for stalled events; else null. */\n stalledMin: number | null;\n /** Consecutive failed commands, for thrashing events; else null. */\n consecFails?: number | null;\n /** Seconds of the one sleeping command, for sleeping events; else null. */\n sleepSec?: number | null;\n /** The one-liner that reaches the orchestrator. */\n text: string;\n}\n\n/**\n * The owning session of a worker, or null when nobody claims it (and so\n * nothing to notify): the spawner's claude session id first — that is what\n * the hook knows a session by — else the AIBroker iTerm uuid.\n */\nexport function ownershipKey(s: WorkerStatus): string | null {\n if (s.spawnerSession) return s.spawnerSession;\n if (s.session?.id) return s.session.id;\n return null;\n}\n\nconst TERMINAL: readonly WorkerStatus[\"state\"][] = [\"done\", \"failed\", \"killed\", \"lost\"];\n\nfunction isTerminal(s: WorkerStatus): boolean {\n return TERMINAL.includes(s.state);\n}\n\n/** Age of a \"YYYY-MM-DD HH:MM:SS\" stamp in ms, NaN-safe (unparsable → 0). */\nfunction ageMs(ts: string, now: Date): number {\n const t = Date.parse(ts.replace(\" \", \"T\"));\n if (Number.isNaN(t)) return 0;\n return Math.max(0, now.getTime() - t);\n}\n\n/**\n * The stall threshold in minutes from PAI_WORKER_STALL_MINUTES (default 10).\n * Anything unparsible or non-positive falls back to the default — a broken\n * value must not turn supervision off or make it fire every tick.\n */\nexport const DEFAULT_STALL_MINUTES = 10;\n\nexport function stallMinutesFromEnv(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.PAI_WORKER_STALL_MINUTES;\n if (raw === undefined || raw === \"\") return DEFAULT_STALL_MINUTES;\n const n = Number(raw);\n return Number.isFinite(n) && n > 0 ? n : DEFAULT_STALL_MINUTES;\n}\n\n/**\n * The consecutive-failure threshold from PAI_WORKER_THRASH_FAILS (default 5),\n * with the same broken-value tolerance as stallMinutesFromEnv.\n */\nexport const DEFAULT_THRASH_FAILS = 5;\n\nexport function thrashFailsFromEnv(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.PAI_WORKER_THRASH_FAILS;\n if (raw === undefined || raw === \"\") return DEFAULT_THRASH_FAILS;\n const n = Number(raw);\n return Number.isFinite(n) && n > 0 ? n : DEFAULT_THRASH_FAILS;\n}\n\n/**\n * Event id: `<worker>#<kind>` for the once-per-run terminal kinds, and\n * `<worker>#<kind>@<turns>` for the mid-run kinds (stalled, thrashing,\n * sleeping) — the turn count re-arms the id, so a worker that resumes and\n * hits the same condition again gets a second event while a restart cannot\n * replay the first.\n */\nexport function eventId(worker: string, kind: SupervisionKind, turns = 0): string {\n return MID_RUN_KINDS.includes(kind) ? `${worker}#${kind}@${turns}` : `${worker}#${kind}`;\n}\n\nexport interface DetectOptions {\n /** How long a running worker may go without a turn before \"stalled\". */\n stallMs: number;\n now: Date;\n /** Consecutive failed tool executions before \"thrashing\" (default 5). */\n thrashFails?: number;\n /** pid liveness — injected so tests need no real processes. */\n isAlive?: (pid: number) => boolean;\n /**\n * How stale `updated` must be before a dead pid counts as killed rather\n * than as a status write racing the tick.\n */\n deadGraceMs?: number;\n}\n\n/** One event's one-liner — the exact line the orchestrator reads. */\nfunction eventText(kind: SupervisionKind, s: WorkerStatus, rc: number | null, stalledMin: number | null): string {\n const tail = `- see pai worker replay ${s.id}`;\n if (kind === \"finished\") return `worker ${s.id} ${s.label} finished rc=0 ${tail}`;\n if (kind === \"stalled\") return `worker ${s.id} ${s.label} stalled ${stalledMin}m no turns ${tail}`;\n if (kind === \"thrashing\")\n return `worker ${s.id} ${s.label} thrashing: ${s.consecFails} consecutive failed commands ${tail}`;\n if (kind === \"sleeping\") return `worker ${s.id} ${s.label} sleeping ${s.sleepSec}s in one command ${tail}`;\n const why = rc === null ? \"runner gone\" : `rc=${rc}`;\n return `worker ${s.id} ${s.label} failed ${why} ${tail}`;\n}\n\n/**\n * Detect conditions across a ledger snapshot. Pure: statuses in, events out;\n * dedup against delivered ids is the caller's job (see filterUndelivered).\n * Workers without an owning session are skipped — nobody to notify.\n */\nexport function detectSupervisionEvents(\n statuses: WorkerStatus[],\n opts: DetectOptions\n): SupervisionEvent[] {\n const isAlive = opts.isAlive ?? alive;\n const deadGraceMs = opts.deadGraceMs ?? 15_000;\n const out: SupervisionEvent[] = [];\n for (const s of statuses) {\n const session = ownershipKey(s);\n if (!session) continue;\n // the operator's own pane: ending it is not a worker outcome, idling is\n // not a stall — nothing here is worth a push into anybody's terminal\n if (isChatPane(s)) continue;\n let kind: SupervisionKind | null = null;\n let rc: number | null = null;\n let stalledMin: number | null = null;\n if (isTerminal(s)) {\n // a finished run is state done with rc 0; every other terminal shape\n // (failed, killed, lost, done with a non-zero rc) is a failure\n if (s.state === \"done\" && (s.rc ?? 0) === 0) {\n kind = \"finished\";\n rc = 0;\n } else {\n kind = \"failed\";\n rc = s.state === \"lost\" ? null : s.rc;\n }\n } else if (!isAlive(s.pid) && ageMs(s.updated, opts.now) > deadGraceMs) {\n // state says running but the runner is gone (SIGKILL, crash) — the\n // status will never get its rc, so supervision is the only witness\n kind = \"failed\";\n rc = null;\n } else if (ageMs(s.updated, opts.now) > opts.stallMs) {\n kind = \"stalled\";\n stalledMin = Math.floor(ageMs(s.updated, opts.now) / 60_000);\n } else if ((s.consecFails ?? 0) >= (opts.thrashFails ?? DEFAULT_THRASH_FAILS)) {\n kind = \"thrashing\";\n } else if (s.sleepSec != null) {\n kind = \"sleeping\";\n }\n if (!kind) continue;\n out.push({\n id: eventId(s.id, kind, s.turns),\n ts: nowStamp(opts.now),\n kind,\n worker: s.id,\n label: s.label,\n session,\n rc,\n stalledMin,\n ...(kind === \"thrashing\" ? { consecFails: s.consecFails ?? 0 } : {}),\n ...(kind === \"sleeping\" ? { sleepSec: s.sleepSec ?? 0 } : {}),\n text: eventText(kind, s, rc, stalledMin),\n });\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Delivered-id persistence — the restart guard\n// ---------------------------------------------------------------------------\n\nexport interface SupervisionState {\n /** worker id → event ids already written to that owner's event file. */\n delivered: Record<string, string[]>;\n}\n\n/** Cap on remembered workers: terminal and delivered is history, not state. */\nconst MAX_REMEMBERED_WORKERS = 500;\n\nexport function supervisionDirPath(logDir: string): string {\n return join(logDir, \"supervision\");\n}\n\nexport function supervisionStatePath(logDir: string): string {\n return join(supervisionDirPath(logDir), \"state.json\");\n}\n\nexport function supervisionEventsPath(logDir: string, session: string): string {\n return join(supervisionDirPath(logDir), `${session}.events`);\n}\n\n/** Receipts of events already pushed into a terminal, one event id per line. */\nexport function supervisionPushedPath(logDir: string, session: string): string {\n return join(supervisionDirPath(logDir), `${session}.pushed`);\n}\n\nexport function loadSupervisionState(path: string): { state: SupervisionState; fresh: boolean } {\n if (!existsSync(path)) return { state: { delivered: {} }, fresh: true };\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as SupervisionState;\n if (parsed && typeof parsed === \"object\" && typeof parsed.delivered === \"object\") {\n return { state: parsed, fresh: false };\n }\n } catch {\n // a damaged state file replays at most one round of terminal events;\n // rewriting it is the recovery, not the problem\n }\n return { state: { delivered: {} }, fresh: true };\n}\n\nexport function saveSupervisionState(path: string, state: SupervisionState): void {\n const dir = dirname(path);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, JSON.stringify(state), \"utf8\");\n renameSync(tmp, path);\n}\n\n/**\n * Drop workers the ledger no longer lists and cap the rest (newest ids last —\n * worker ids sort chronologically), so the persisted state stays bounded.\n */\nexport function pruneState(state: SupervisionState, statuses: WorkerStatus[]): SupervisionState {\n const present = new Set(statuses.map((s) => s.id));\n const kept = Object.entries(state.delivered)\n .filter(([id]) => present.has(id))\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .slice(-MAX_REMEMBERED_WORKERS);\n return { delivered: Object.fromEntries(kept) };\n}\n\n/**\n * First run: adopt every already-terminal worker as delivered. Supervision\n * reports the transitions it observes from now on, never a replay of every\n * worker that ever finished before it started.\n */\nexport function baselineState(statuses: WorkerStatus[]): SupervisionState {\n const delivered: Record<string, string[]> = {};\n for (const s of statuses) {\n if (!isTerminal(s) || !ownershipKey(s)) continue;\n delivered[s.id] = [eventId(s.id, \"finished\"), eventId(s.id, \"failed\")];\n }\n return { delivered };\n}\n\n/** The events whose ids the state has not seen yet. */\nexport function filterUndelivered(events: SupervisionEvent[], state: SupervisionState): SupervisionEvent[] {\n return events.filter((e) => !(state.delivered[e.worker] ?? []).includes(e.id));\n}\n\nexport function markDelivered(state: SupervisionState, events: SupervisionEvent[]): void {\n for (const e of events) {\n const ids = state.delivered[e.worker] ?? [];\n if (!ids.includes(e.id)) ids.push(e.id);\n state.delivered[e.worker] = ids;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Delivery\n// ---------------------------------------------------------------------------\n\n/** Where an event's push goes, resolved from the worker's own identities. */\nexport interface PushTarget {\n claudeSession: string | null;\n iterm: string | null;\n}\n\nexport type PushFn = (logDir: string, target: PushTarget, ev: SupervisionEvent) => Promise<boolean>;\n\n/**\n * Default push: AIBroker `send_to_session` into the orchestrator's terminal,\n * using the iTerm uuid the worker recorded (`session.id`) or the one the\n * session map bridges for the spawner's claude session. A timeout still\n * delivered (see aibroker-client) counts as delivered; every failure is\n * reported as not-delivered so only the event file carries the event.\n */\nexport const aibrokerPush: PushFn = async (logDir, target, ev) => {\n const iterm =\n target.iterm ?? (target.claudeSession ? itermForClaudeSession(logDir, target.claudeSession) : null);\n if (!iterm) return false;\n try {\n const { sendToSession } = await import(\"../cli/lib/aibroker-client.js\");\n const r = await sendToSession(iterm, ev.text);\n return r.ok || r.timedOut === true;\n } catch {\n return false;\n }\n};\n\n/**\n * Whether an event should be relayed into the owner's terminal. The mid-run\n * kinds (stalled, thrashing, sleeping) ALWAYS relay: a json/stream-json\n * caller knows the run's result at exit but has no other way to hear\n * mid-run trouble. Only the terminal kinds (finished/failed) skip the relay\n * for those callers — they read the run's result itself, and the harness\n * already notifies them on process exit, so the one-liner would cost a full\n * extra turn for information they already have. Interactive/pane launches\n * and the default text format are never skipped.\n */\nexport function shouldRelay(\n kind: SupervisionKind,\n outputFormat: WorkerStatus[\"outputFormat\"] | undefined\n): boolean {\n if (MID_RUN_KINDS.includes(kind)) return true;\n return outputFormat !== \"json\" && outputFormat !== \"stream-json\";\n}\n\nfunction appendEventFile(logDir: string, ev: SupervisionEvent): void {\n const path = supervisionEventsPath(logDir, ev.session);\n const dir = supervisionDirPath(logDir);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n appendFileSync(path, JSON.stringify(ev) + \"\\n\", \"utf8\");\n}\n\n/** Record that an event reached its owner's terminal — the hook then skips it. */\nfunction appendPushReceipt(logDir: string, ev: SupervisionEvent): void {\n try {\n appendFileSync(supervisionPushedPath(logDir, ev.session), `${ev.id}\\n`, \"utf8\");\n } catch {\n // a missing receipt only means the hook may repeat the line\n }\n}\n\nexport interface TickOptions {\n now?: Date;\n stallMs?: number;\n /** Consecutive-failure threshold for thrashing (default: PAI_WORKER_THRASH_FAILS). */\n thrashFails?: number;\n isAlive?: (pid: number) => boolean;\n /** Injectable for tests; production pushes through AIBroker. */\n push?: PushFn;\n /** Preloaded map, so a test (or a batch of ticks) can share one read. */\n statuses?: WorkerStatus[];\n}\n\nexport interface TickResult {\n events: SupervisionEvent[];\n /** Events that also reached a terminal through the push channel. */\n pushed: SupervisionEvent[];\n}\n\n/**\n * One supervision pass over the ledger: detect, append each new event to its\n * owner's event file, push it best effort, persist the delivered ids. The\n * event file is the durable record — an event is marked delivered only after\n * its line landed there, so a failed tick retries, a repeated one replays\n * nothing.\n */\nexport async function runSupervisionTick(logDir: string, opts: TickOptions = {}): Promise<TickResult> {\n const now = opts.now ?? new Date();\n const statuses = opts.statuses ?? loadStatuses(logDir);\n const statePath = supervisionStatePath(logDir);\n const loaded = loadSupervisionState(statePath);\n let state = loaded.state;\n if (loaded.fresh) state = baselineState(statuses);\n\n const pending = filterUndelivered(\n detectSupervisionEvents(statuses, {\n stallMs: opts.stallMs ?? DEFAULT_STALL_MINUTES * 60_000,\n thrashFails: opts.thrashFails ?? thrashFailsFromEnv(),\n now,\n ...(opts.isAlive ? { isAlive: opts.isAlive } : {}),\n }),\n state\n );\n\n const written: SupervisionEvent[] = [];\n for (const ev of pending) {\n appendEventFile(logDir, ev);\n written.push(ev);\n }\n\n const push = opts.push ?? aibrokerPush;\n const pushed: SupervisionEvent[] = [];\n for (const ev of written) {\n // the owner's iTerm identity is in its worker status, not the event\n const owner = statuses.find((s) => s.id === ev.worker);\n if (!shouldRelay(ev.kind, owner?.outputFormat)) continue; // caller reads its own JSON result\n const target: PushTarget = {\n claudeSession: owner?.spawnerSession ?? null,\n iterm: owner?.session?.id ?? null,\n };\n let ok = false;\n try {\n ok = await push(logDir, target, ev);\n } catch {\n ok = false;\n }\n if (ok) {\n pushed.push(ev);\n appendPushReceipt(logDir, ev);\n }\n }\n\n markDelivered(state, written);\n saveSupervisionState(statePath, pruneState(state, statuses));\n return { events: written, pushed };\n}\n","/**\n * Index, embed, vault index, and registry scan schedulers for the PAI daemon.\n * Exports run* functions (also called on-demand by the IPC handler)\n * and the start* functions invoked once at daemon startup.\n */\n\nimport { readWorkersSection } from \"../../workers/config.js\";\nimport { keepaliveSecs, runKeepaliveBeat, type BeatMetrics } from \"../../workers/keepalive.js\";\nimport { workersLogDir } from \"../../workers/paths.js\";\nimport { runSupervisionTick, stallMinutesFromEnv, thrashFailsFromEnv } from \"../../workers/supervision.js\";\nimport { runSessionKeepaliveTick } from \"../session-keepalive.js\";\nimport {\n registryBackend,\n storageBackend,\n daemonConfig,\n indexInProgress,\n embedInProgress,\n vaultIndexInProgress,\n shutdownRequested,\n setIndexInProgress,\n setLastIndexTime,\n setIndexSchedulerTimer,\n setEmbedInProgress,\n setLastEmbedTime,\n setEmbedSchedulerTimer,\n setVaultIndexInProgress,\n setLastVaultIndexTime,\n setCacheKeepaliveTimer,\n} from \"./state.js\";\n\n// ---------------------------------------------------------------------------\n// Index scheduler\n// ---------------------------------------------------------------------------\n\n/** Minimum interval between vault index runs (30 minutes). */\nconst VAULT_INDEX_MIN_INTERVAL_MS = 30 * 60 * 1000;\n\n/**\n * Run a full index pass. Guards against overlapping runs with indexInProgress.\n * Called both by the scheduler and by the index_now IPC method.\n */\nexport async function runIndex(): Promise<void> {\n if (indexInProgress) {\n process.stderr.write(\"[pai-daemon] Index already in progress, skipping.\\n\");\n return;\n }\n\n if (embedInProgress) {\n process.stderr.write(\"[pai-daemon] Embed in progress, deferring index run.\\n\");\n return;\n }\n\n setIndexInProgress(true);\n const t0 = Date.now();\n\n try {\n process.stderr.write(\"[pai-daemon] Starting scheduled index run...\\n\");\n\n const { projects, result } = await storageBackend.indexAll(registryBackend);\n const elapsed = Date.now() - t0;\n setLastIndexTime(Date.now());\n process.stderr.write(\n `[pai-daemon] Index complete: ${projects} projects, ` +\n `${result.filesProcessed} files, ${result.chunksCreated} chunks ` +\n `(${elapsed}ms)\\n`\n );\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(`[pai-daemon] Index error: ${msg}\\n`);\n } finally {\n setIndexInProgress(false);\n }\n}\n\n/**\n * Run a vault index pass. Guards against overlapping runs with vaultIndexInProgress.\n * Skips if no vaultPath is configured, or if project index/embed is in progress.\n */\nexport async function runVaultIndex(): Promise<void> {\n if (!daemonConfig.vaultPath) return;\n\n if (vaultIndexInProgress) {\n process.stderr.write(\"[pai-daemon] Vault index already in progress, skipping.\\n\");\n return;\n }\n\n if (indexInProgress || embedInProgress) {\n process.stderr.write(\"[pai-daemon] Index/embed in progress, deferring vault index.\\n\");\n return;\n }\n\n // Import lastVaultIndexTime from state (re-read each call since it may change)\n const { lastVaultIndexTime } = await import(\"./state.js\");\n if (lastVaultIndexTime > 0 && Date.now() - lastVaultIndexTime < VAULT_INDEX_MIN_INTERVAL_MS) {\n return;\n }\n\n let vaultProjectId = daemonConfig.vaultProjectId;\n if (!vaultProjectId) {\n const row = await registryBackend.getProjectByRootPath(daemonConfig.vaultPath!);\n vaultProjectId = row?.id ?? 999;\n if (!row) {\n process.stderr.write(\"[pai-daemon] Vault not in project registry — using synthetic project ID 999.\\n\");\n }\n }\n\n setVaultIndexInProgress(true);\n const t0 = Date.now();\n\n process.stderr.write(\"[pai-daemon] Starting vault index run...\\n\");\n\n try {\n const { indexVault } = await import(\"../../memory/vault-indexer.js\");\n const r = await indexVault(storageBackend, vaultProjectId, daemonConfig.vaultPath!);\n const elapsed = Date.now() - t0;\n setLastVaultIndexTime(Date.now());\n process.stderr.write(\n `[pai-daemon] Vault index complete: ${r.filesIndexed} files, ` +\n `${r.linksExtracted} links, ${r.deadLinksFound} dead, ` +\n `${r.orphansFound} orphans (${elapsed}ms)\\n`\n );\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(`[pai-daemon] Vault index error: ${msg}\\n`);\n } finally {\n setVaultIndexInProgress(false);\n }\n}\n\n/**\n * Start the periodic index scheduler. Runs an initial pass 2 seconds after startup.\n */\nexport function startIndexScheduler(): void {\n const intervalMs = daemonConfig.indexIntervalSecs * 1_000;\n\n process.stderr.write(\n `[pai-daemon] Index scheduler: every ${daemonConfig.indexIntervalSecs}s\\n`\n );\n\n // Indexing and embedding are mutually exclusive (each defers to the other),\n // and an index pass regularly outlasts the index interval. Left to two\n // independent timers, the embed tick therefore lands while indexing is in\n // progress and is dropped — observed live on 2026-08-01 as six consecutive\n // index passes with no embed pass at all, and a 143k-chunk embedding backlog.\n // Chaining embed onto the end of every index pass makes the alternation\n // guaranteed rather than a race: index, then vault, then embed, every cycle.\n const cycle = (label: string, withEmbed: boolean) =>\n runIndex()\n .then(() => runVaultIndex())\n .then(() => (withEmbed ? runEmbed() : undefined))\n .catch((e) => {\n process.stderr.write(`[pai-daemon] ${label} index error: ${e}\\n`);\n });\n\n // The startup pass indexes but must NOT embed unless embedOnStartup says so.\n // startEmbedScheduler already refuses a startup embed for exactly that reason;\n // chaining runEmbed onto this pass reinstated the same CPU storm through the\n // back door. Seen live after a reboot: \"Startup embed pass skipped\n // (embedOnStartup=false)\" in the log, and minutes later the same boot running\n // a 5000-chunk pass at ~450% CPU. A guard one scheduler honours and another\n // walks around is not a guard.\n // With a maintenance hour configured there is no startup pass at all. Every\n // restart otherwise buys itself a full index run, so on a machine that is\n // rebooted or has the daemon reloaded during the day the \"maintenance runs at\n // night\" guarantee is worth nothing: the heavy work simply follows the\n // restarts around. Indexing waits for the window like everything else.\n if (daemonConfig.maintenanceHour === undefined) {\n setTimeout(() => void cycle(\"Startup\", daemonConfig.embedOnStartup), 2_000);\n } else {\n process.stderr.write(\n \"[pai-daemon] Startup index pass skipped (maintenanceHour is set).\\n\"\n );\n }\n\n // Anchor the recurring cycle to a wall-clock hour when one is configured.\n // setInterval alone counts from daemon start, so a machine rebooted at noon\n // gets its \"daily\" maintenance at noon every day thereafter — the interval\n // says how often, never when. Without an anchor there is no such thing as a\n // night-only pass, however long the interval.\n const firstDelayMs = msUntilNextAnchor(daemonConfig.maintenanceHour, intervalMs);\n if (daemonConfig.maintenanceHour !== undefined) {\n process.stderr.write(\n `[pai-daemon] Index scheduler anchored to ${String(daemonConfig.maintenanceHour).padStart(2, \"0\")}:00 local ` +\n `(next pass in ${Math.round(firstDelayMs / 60_000)} min)\\n`\n );\n }\n\n let timer: ReturnType<typeof setInterval>;\n const startTimer = () => {\n timer = setInterval(() => void cycle(\"Scheduled\", true), intervalMs);\n if (timer.unref) timer.unref();\n setIndexSchedulerTimer(timer);\n };\n\n const first = setTimeout(() => {\n void cycle(\"Scheduled\", true);\n startTimer();\n }, firstDelayMs);\n if (first.unref) first.unref();\n}\n\n/**\n * Milliseconds until the next occurrence of `hour`:00 local time.\n * Falls back to the plain interval when no anchor hour is configured.\n */\nfunction msUntilNextAnchor(hour: number | undefined, intervalMs: number): number {\n if (hour === undefined || !Number.isInteger(hour) || hour < 0 || hour > 23) {\n return intervalMs;\n }\n const now = new Date();\n const next = new Date(now);\n next.setHours(hour, 0, 0, 0);\n if (next <= now) next.setDate(next.getDate() + 1);\n return next.getTime() - now.getTime();\n}\n\n// ---------------------------------------------------------------------------\n// Embed scheduler\n// ---------------------------------------------------------------------------\n\n/**\n * Run an embedding pass for all unembedded chunks (Postgres backend only).\n */\nexport async function runEmbed(): Promise<void> {\n if (embedInProgress) {\n process.stderr.write(\"[pai-daemon] Embed already in progress, skipping.\\n\");\n return;\n }\n\n if (indexInProgress) {\n process.stderr.write(\"[pai-daemon] Index in progress, deferring embed pass.\\n\");\n return;\n }\n\n if (!storageBackend.supportsPostgresFeatures) {\n return;\n }\n\n setEmbedInProgress(true);\n const t0 = Date.now();\n\n try {\n process.stderr.write(\"[pai-daemon] Starting scheduled embed pass...\\n\");\n\n const projectNames = new Map<number, string>();\n try {\n const rows = await registryBackend.listProjects({ status: \"active\" });\n for (const r of rows) projectNames.set(r.id, r.slug);\n } catch { /* registry unavailable — IDs will be used instead */ }\n\n const { embedChunksWithBackend } = await import(\"../../memory/indexer-backend.js\");\n // Explicit budgets so one embed phase can never outlast an index cycle.\n // Backlogs drain across passes, not within one.\n const count = await embedChunksWithBackend(\n storageBackend,\n () => shutdownRequested,\n projectNames,\n // Indexing settles to a few chunks per pass once caught up, so the daemon\n // is idle most of the cycle and the embed budget is what actually sets\n // drain rate. Measured 450 chunks per 90s against real (long) chunks, so\n // a backlog only clears at roughly the budget's share of the cycle. What\n // broke the starvation was bounding the pass at all, not this number —\n // it can be raised freely as long as it stays finite.\n { maxMillis: 240_000 },\n );\n\n // Vault chunks (project 999) are indexed through the same storageBackend\n // as everything else (indexVault() writes via backend.insertChunks()), so\n // the embedChunksWithBackend() call above already embeds them. A vault-only\n // SQLite pass here would open a stray federation database even under Postgres.\n\n const elapsed = Date.now() - t0;\n setLastEmbedTime(Date.now());\n process.stderr.write(\n `[pai-daemon] Embed pass complete: ${count} chunks embedded (${elapsed}ms)\\n`\n );\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(`[pai-daemon] Embed error: ${msg}\\n`);\n } finally {\n setEmbedInProgress(false);\n }\n}\n\n/**\n * Start the periodic embed scheduler. Initial run is 60 seconds after startup.\n */\nexport function startEmbedScheduler(): void {\n const intervalMs = daemonConfig.embedIntervalSecs * 1_000;\n\n process.stderr.write(\n `[pai-daemon] Embed scheduler: every ${daemonConfig.embedIntervalSecs}s\\n`\n );\n\n // Startup embed pass — OFF unless explicitly enabled.\n //\n // This used to run unconditionally 60s after every start, ignoring\n // embedIntervalSecs entirely. With a large backlog that makes every restart a\n // CPU storm: the interval was set to a day to stop the machine being bogged\n // down, the daemon was restarted, and it immediately began a 240-second pass\n // anyway. Throttling the recurring timer while leaving this armed means the\n // throttle silently does nothing for anyone who restarts.\n //\n // Measured backlog when this was found: 1,868,098 unembedded chunks at ~5.7\n // chunks/s — about 91 days of work that a restart would resume unbidden.\n if (daemonConfig.embedOnStartup) {\n setTimeout(() => {\n runEmbed().catch((e) => {\n process.stderr.write(`[pai-daemon] Startup embed error: ${e}\\n`);\n });\n }, 60_000);\n } else {\n process.stderr.write(\n \"[pai-daemon] Startup embed pass skipped (embedOnStartup=false).\\n\"\n );\n }\n\n // With a maintenance hour configured the index cycle already chains an embed\n // pass onto every anchored run, so this timer would only add a second pass\n // that counts from daemon start — observed as \"every 86400s\" armed at a\n // 20:08 boot, i.e. a daily daytime pass on a machine configured for 03:00.\n // The interval says how often, never when; without an anchor it cannot\n // deliver a night-only pass, so it is not armed at all.\n if (daemonConfig.maintenanceHour !== undefined) {\n process.stderr.write(\n \"[pai-daemon] Standalone embed timer not armed (maintenanceHour is set; \" +\n \"embed runs at the end of each anchored index cycle).\\n\"\n );\n return;\n }\n\n const timer = setInterval(() => {\n runEmbed().catch((e) => {\n process.stderr.write(`[pai-daemon] Scheduled embed error: ${e}\\n`);\n });\n }, intervalMs);\n\n if (timer.unref) timer.unref();\n setEmbedSchedulerTimer(timer);\n}\n\n// ---------------------------------------------------------------------------\n// Registry scan scheduler\n// ---------------------------------------------------------------------------\n\nconst REGISTRY_SCAN_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes\nconst REGISTRY_SCAN_STARTUP_DELAY_MS = 10_000; // 10 seconds after daemon start\n\n/**\n * Start the periodic registry scan scheduler.\n * First scan runs 10 seconds after startup (enough time for IPC to stabilise).\n * Subsequent scans run every 30 minutes.\n * Uses the work-queue so the scan runs on the worker thread without blocking IPC.\n */\nexport function startRegistryScanScheduler(): void {\n process.stderr.write(\n \"[pai-daemon] Registry scan scheduler: every 30min (first in 10s)\\n\"\n );\n\n setTimeout(() => {\n import(\"../../daemon/work-queue-worker.js\")\n .then(({ enqueueRegistryScan }) => enqueueRegistryScan())\n .catch((e) => {\n process.stderr.write(`[pai-daemon] Startup registry scan error: ${e}\\n`);\n });\n }, REGISTRY_SCAN_STARTUP_DELAY_MS);\n\n const timer = setInterval(() => {\n import(\"../../daemon/work-queue-worker.js\")\n .then(({ enqueueRegistryScan }) => enqueueRegistryScan())\n .catch((e) => {\n process.stderr.write(`[pai-daemon] Scheduled registry scan error: ${e}\\n`);\n });\n }, REGISTRY_SCAN_INTERVAL_MS);\n\n if (timer.unref) timer.unref();\n}\n\n// ---------------------------------------------------------------------------\n// Worker supervision scheduler\n// ---------------------------------------------------------------------------\n\n/** How often the daemon looks at the worker ledger for supervision events. */\nconst SUPERVISION_TICK_MS = 30_000;\n\n/** First supervision pass waits for the first statuses to exist at all. */\nconst SUPERVISION_STARTUP_DELAY_MS = 15_000;\n\n/**\n * Start the worker supervisor: one tick every 30 s over the workers ledger\n * (src/workers/supervision.ts) that pushes finished/failed/stalled events to\n * the owning session — the daemon-side replacement for orchestrator polling.\n * Daemon code only: no model call has any business being here, and none is\n * made. Disabled workers disable the supervisor with it.\n */\nexport function startWorkerSupervisor(): void {\n let enabled = false;\n try {\n enabled = readWorkersSection().workers.enabled;\n } catch (e) {\n process.stderr.write(\n `[pai-daemon] Worker supervisor: not started (${e instanceof Error ? e.message : String(e)})\\n`\n );\n return;\n }\n if (!enabled) {\n process.stderr.write(\"[pai-daemon] Worker supervisor: disabled (workers are off)\\n\");\n return;\n }\n\n const tick = () => {\n runSupervisionTick(workersLogDir(readWorkersSection().workers), {\n stallMs: stallMinutesFromEnv() * 60_000,\n thrashFails: thrashFailsFromEnv(),\n })\n .then((r) => {\n for (const ev of r.events) {\n process.stderr.write(`[pai-daemon] Supervision: ${ev.text}\\n`);\n }\n })\n .catch((e) => {\n // a broken tick must never take the daemon down with it\n process.stderr.write(\n `[pai-daemon] Supervision tick error: ${e instanceof Error ? e.message : String(e)}\\n`\n );\n });\n };\n\n const first = setTimeout(tick, SUPERVISION_STARTUP_DELAY_MS);\n if (first.unref) first.unref();\n const timer = setInterval(tick, SUPERVISION_TICK_MS);\n if (timer.unref) timer.unref();\n process.stderr.write(\n `[pai-daemon] Worker supervisor: every ${Math.round(SUPERVISION_TICK_MS / 1000)}s\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Worker prompt-cache keepalive scheduler\n// ---------------------------------------------------------------------------\n\n/** First beat waits a while after boot; the daemon start is itself a warm request. */\nconst KEEPALIVE_STARTUP_DELAY_MS = 60_000;\n\n/**\n * Start the cache keepalive: every workers.cacheKeepaliveSecs one trivial\n * single-turn worker (src/workers/keepalive.ts) re-arms the provider's\n * implicit prompt cache so real worker spawns start warm. Needs no storage\n * backend — it starts with the IPC server, not after the federation connect.\n * 0 (or workers off) keeps it off. A failed beat is logged and swallowed.\n */\nexport function startCacheKeepalive(opts: {\n configPath?: string;\n beat?: () => Promise<BeatMetrics | null>;\n} = {}): void {\n let workers: ReturnType<typeof readWorkersSection>[\"workers\"];\n try {\n workers = readWorkersSection(opts.configPath).workers;\n } catch (e) {\n process.stderr.write(\n `[pai-daemon] Cache keepalive: not started (${e instanceof Error ? e.message : String(e)})\\n`\n );\n return;\n }\n if (!workers.enabled) {\n process.stderr.write(\"[pai-daemon] Cache keepalive: disabled (workers are off)\\n\");\n return;\n }\n const secs = keepaliveSecs(workers);\n if (!secs) {\n process.stderr.write(\"[pai-daemon] Cache keepalive: disabled (cacheKeepaliveSecs is 0)\\n\");\n return;\n }\n\n let notedNoPostgres = false;\n const supportsObservations = () => {\n if (storageBackend?.supportsPostgresFeatures) return true;\n if (!notedNoPostgres) {\n notedNoPostgres = true;\n process.stderr.write(\n \"[pai-daemon] Cache keepalive: observation rows need Postgres — ledger line only\\n\"\n );\n }\n return false;\n };\n\n const beat = async (): Promise<void> => {\n const m = await (opts.beat ?? runKeepaliveBeat)();\n if (!m) return; // overlap guard: previous beat still running\n if (!supportsObservations()) return; // ledger line already written by the beat itself\n try {\n await storageBackend.storeObservationWithProject(registryBackend, {\n session_id: m.id,\n type: \"change\",\n title: `cache keepalive ${m.ok ? \"ok\" : \"failed\"} (cache_read=${m.cache_read_input_tokens}, api_ms=${m.duration_api_ms})`,\n tool_name: \"cache-keepalive\",\n narrative: `beat ${m.id}: input=${m.input_tokens} cache_read=${m.cache_read_input_tokens} cache_creation=${m.cache_creation_input_tokens} duration_api_ms=${m.duration_api_ms}`,\n tool_input_summary: undefined,\n files_read: [],\n files_modified: [],\n concepts: [],\n });\n } catch (e) {\n // a failed observation must never fail the beat\n process.stderr.write(\n `[pai-daemon] Cache keepalive observation error: ${e instanceof Error ? e.message : String(e)}\\n`\n );\n }\n };\n\n const first = setTimeout(() => {\n beat().catch((e) => {\n process.stderr.write(\n `[pai-daemon] Cache keepalive beat error: ${e instanceof Error ? e.message : String(e)}\\n`\n );\n });\n }, KEEPALIVE_STARTUP_DELAY_MS);\n if (first.unref) first.unref();\n\n const timer = setInterval(() => {\n beat().catch((e) => {\n process.stderr.write(\n `[pai-daemon] Cache keepalive beat error: ${e instanceof Error ? e.message : String(e)}\\n`\n );\n });\n }, secs * 1000);\n if (timer.unref) timer.unref();\n setCacheKeepaliveTimer(timer);\n process.stderr.write(`[pai-daemon] Cache keepalive: every ${secs}s\\n`);\n}\n\n// ---------------------------------------------------------------------------\n// Interactive-session prompt-cache keepalive scheduler\n// ---------------------------------------------------------------------------\n\n/** Tick cadence: coarse enough to be cheap, fine enough that a session\n * crossing idleMinutes gets beaten within a minute of becoming eligible. */\nconst SESSION_KEEPALIVE_TICK_MS = 60_000;\n\n/**\n * Start the interactive-session cache keepalive: every 60s, beat every live\n * session that has gone idle past `sessions.cacheKeepalive.idleMinutes`\n * (src/daemon/session-keepalive.ts). Off unless\n * `sessions.cacheKeepalive.enabled` is true — no hot-reload, matching\n * startCacheKeepalive above: config changes need a daemon restart.\n */\nexport function startSessionKeepalive(): void {\n const config = daemonConfig.sessions.cacheKeepalive;\n if (!config.enabled) {\n process.stderr.write(\"[pai-daemon] Session keepalive: disabled (sessions.cacheKeepalive.enabled is false)\\n\");\n return;\n }\n\n const tick = () => {\n runSessionKeepaliveTick(config).catch((e) => {\n process.stderr.write(\n `[pai-daemon] Session keepalive tick error: ${e instanceof Error ? e.message : String(e)}\\n`\n );\n });\n };\n\n const timer = setInterval(tick, SESSION_KEEPALIVE_TICK_MS);\n if (timer.unref) timer.unref();\n process.stderr.write(\n `[pai-daemon] Session keepalive: every ${SESSION_KEEPALIVE_TICK_MS / 1000}s ` +\n `(idle >= ${config.idleMinutes}min, hours ${config.activeHours}, max ${config.maxBeats} beats/stretch)\\n`\n );\n}\n","/**\n * Tool dispatcher — maps IPC method names to PAI tool functions.\n */\n\nimport {\n toolMemorySearch,\n toolMemoryGet,\n toolProjectInfo,\n toolProjectList,\n toolSessionList,\n toolRegistrySearch,\n toolProjectDetect,\n toolProjectHealth,\n toolProjectTodo,\n toolSessionRoute,\n toolMemoryWakeup,\n toolMemoryTaxonomy,\n toolMemoryFeedback,\n toolMemoryKgSearch,\n} from \"../../mcp/tools.js\";\nimport { detectTopicShift } from \"../../topics/detector.js\";\nimport { registryBackend, storageBackend, daemonConfig } from \"./state.js\";\n\n/**\n * Dispatch an IPC tool call to the appropriate tool function.\n * Returns the tool result or throws on unknown/failed methods.\n */\nexport async function dispatchTool(\n method: string,\n params: Record<string, unknown>\n): Promise<unknown> {\n // Cast through unknown to satisfy TypeScript's strict overlap check on\n // Record<string, unknown> → specific param types. Runtime validation is\n // the responsibility of each tool function (they surface errors gracefully).\n const p = params as unknown;\n\n switch (method) {\n case \"memory_search\":\n return toolMemorySearch(registryBackend, storageBackend, p as Parameters<typeof toolMemorySearch>[2]);\n\n case \"memory_get\":\n return toolMemoryGet(registryBackend, p as Parameters<typeof toolMemoryGet>[1]);\n\n case \"project_info\":\n return toolProjectInfo(registryBackend, p as Parameters<typeof toolProjectInfo>[1]);\n\n case \"project_list\":\n return toolProjectList(registryBackend, p as Parameters<typeof toolProjectList>[1]);\n\n case \"session_list\":\n return toolSessionList(registryBackend, p as Parameters<typeof toolSessionList>[1]);\n\n case \"registry_search\":\n return toolRegistrySearch(registryBackend, p as Parameters<typeof toolRegistrySearch>[1]);\n\n case \"project_detect\":\n return toolProjectDetect(p as Parameters<typeof toolProjectDetect>[0]);\n\n case \"project_health\":\n return toolProjectHealth(registryBackend, p as Parameters<typeof toolProjectHealth>[1]);\n\n case \"project_todo\":\n return toolProjectTodo(registryBackend, p as Parameters<typeof toolProjectTodo>[1]);\n\n case \"memory_wakeup\":\n return toolMemoryWakeup(registryBackend, p as Parameters<typeof toolMemoryWakeup>[1]);\n\n case \"memory_taxonomy\":\n return toolMemoryTaxonomy(registryBackend, storageBackend, p as Parameters<typeof toolMemoryTaxonomy>[2]);\n\n case \"topic_check\":\n return detectTopicShift(\n registryBackend,\n storageBackend,\n p as Parameters<typeof detectTopicShift>[2]\n );\n\n case \"session_auto_route\":\n return toolSessionRoute(\n registryBackend,\n storageBackend,\n p as Parameters<typeof toolSessionRoute>[2]\n );\n\n case \"zettel_explore\":\n case \"zettel_health\":\n case \"zettel_surprise\":\n case \"zettel_suggest\":\n case \"zettel_converse\":\n case \"zettel_themes\":\n case \"zettel_god_notes\":\n case \"zettel_communities\": {\n const { toolZettelExplore, toolZettelHealth, toolZettelSurprise, toolZettelSuggest, toolZettelConverse, toolZettelThemes, toolZettelGodNotes, toolZettelCommunities } = await import(\"../../mcp/tools.js\");\n\n switch (method) {\n case \"zettel_explore\": return toolZettelExplore(storageBackend, p as Parameters<typeof toolZettelExplore>[1]);\n case \"zettel_health\": return toolZettelHealth(storageBackend, p as Parameters<typeof toolZettelHealth>[1]);\n case \"zettel_surprise\": return toolZettelSurprise(storageBackend, p as Parameters<typeof toolZettelSurprise>[1]);\n case \"zettel_suggest\": return toolZettelSuggest(storageBackend, p as Parameters<typeof toolZettelSuggest>[1]);\n case \"zettel_converse\": return toolZettelConverse(storageBackend, p as Parameters<typeof toolZettelConverse>[1]);\n case \"zettel_themes\": return toolZettelThemes(storageBackend, p as Parameters<typeof toolZettelThemes>[1]);\n case \"zettel_god_notes\": return toolZettelGodNotes(storageBackend, p as Parameters<typeof toolZettelGodNotes>[1]);\n case \"zettel_communities\": return toolZettelCommunities(storageBackend, p as Parameters<typeof toolZettelCommunities>[1]);\n }\n break;\n }\n\n case \"graph_clusters\": {\n const { handleGraphClusters } = await import(\"../../graph/clusters.js\");\n return handleGraphClusters(storageBackend, p as Parameters<typeof handleGraphClusters>[1]);\n }\n\n case \"graph_neighborhood\": {\n const { handleGraphNeighborhood } = await import(\"../../graph/neighborhood.js\");\n return handleGraphNeighborhood(storageBackend, p as Parameters<typeof handleGraphNeighborhood>[1]);\n }\n\n case \"graph_note_context\": {\n const { handleGraphNoteContext } = await import(\"../../graph/note-context.js\");\n return handleGraphNoteContext(storageBackend, p as Parameters<typeof handleGraphNoteContext>[1]);\n }\n\n case \"graph_trace\": {\n const { handleGraphTrace } = await import(\"../../graph/trace.js\");\n return handleGraphTrace(storageBackend, p as Parameters<typeof handleGraphTrace>[1]);\n }\n\n case \"graph_latent_ideas\": {\n const { handleGraphLatentIdeas } = await import(\"../../graph/latent-ideas.js\");\n return handleGraphLatentIdeas(storageBackend, p as Parameters<typeof handleGraphLatentIdeas>[1]);\n }\n\n case \"idea_materialize\": {\n const { handleIdeaMaterialize } = await import(\"../../graph/latent-ideas.js\");\n if (!daemonConfig.vaultPath) {\n throw new Error(\"idea_materialize requires vaultPath to be configured in the daemon config\");\n }\n return handleIdeaMaterialize(\n p as Parameters<typeof handleIdeaMaterialize>[0],\n daemonConfig.vaultPath\n );\n }\n\n case \"kg_add\":\n case \"kg_query\":\n case \"kg_invalidate\":\n case \"kg_contradictions\": {\n const { toolKgAdd, toolKgQuery, toolKgInvalidate, toolKgContradictions } = await import(\"../../mcp/tools.js\");\n if (!storageBackend.supportsPostgresFeatures) {\n throw new Error(`${method} requires a Postgres storage backend`);\n }\n switch (method) {\n case \"kg_add\": return toolKgAdd(storageBackend, p as Parameters<typeof toolKgAdd>[1]);\n case \"kg_query\": return toolKgQuery(storageBackend, p as Parameters<typeof toolKgQuery>[1]);\n case \"kg_invalidate\": return toolKgInvalidate(storageBackend, p as Parameters<typeof toolKgInvalidate>[1]);\n case \"kg_contradictions\": return toolKgContradictions(storageBackend, p as Parameters<typeof toolKgContradictions>[1]);\n }\n break;\n }\n\n case \"memory_tunnels\": {\n const { toolMemoryTunnels } = await import(\"../../mcp/tools.js\");\n return toolMemoryTunnels(registryBackend, storageBackend, p as Parameters<typeof toolMemoryTunnels>[2]);\n }\n\n case \"memory_feedback\": {\n // MR2: feedback weight loop — relevance_score/feedback_weight go through\n // the StorageBackend, so this works on either backend.\n return await toolMemoryFeedback(storageBackend, p as Parameters<typeof toolMemoryFeedback>[1]);\n }\n\n case \"memory_kg_search\": {\n // MR1: graph-completion retrieval — active storage backend for KG triple expansion\n if (!storageBackend.supportsPostgresFeatures) {\n throw new Error(\"memory_kg_search requires a Postgres storage backend for KG triple expansion\");\n }\n return await toolMemoryKgSearch(storageBackend, p as Parameters<typeof toolMemoryKgSearch>[1]);\n }\n\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n}\n","/**\n * IPC request handler — processes all inbound IPC methods and sends responses.\n */\n\nimport type { Socket } from \"node:net\";\nimport type { IpcRequest, IpcResponse } from \"./types.js\";\nimport type { NotificationMode } from \"../../notifications/types.js\";\nimport {\n patchNotificationConfig,\n} from \"../../notifications/config.js\";\nimport { routeNotification } from \"../../notifications/router.js\";\nimport {\n registryBackend,\n storageBackend,\n daemonConfig,\n startTime,\n indexInProgress,\n lastIndexTime,\n embedInProgress,\n lastEmbedTime,\n vaultIndexInProgress,\n lastVaultIndexTime,\n notificationConfig,\n setNotificationConfig,\n} from \"./state.js\";\nimport { runIndex, runVaultIndex } from \"./scheduler.js\";\nimport { dispatchTool } from \"./dispatcher.js\";\nimport { enqueue, getStats as getQueueStats } from \"../../daemon/work-queue.js\";\nimport { notifyNewWork } from \"../../daemon/work-queue-worker.js\";\nimport { getBackendOutage } from \"../../storage/outage.js\";\n\n// ---------------------------------------------------------------------------\n// Helper\n// ---------------------------------------------------------------------------\n\nexport function sendResponse(socket: Socket, response: IpcResponse): void {\n try {\n socket.write(JSON.stringify(response) + \"\\n\");\n } catch {\n // Socket may already be closed\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single IPC request.\n */\nexport async function handleRequest(\n request: IpcRequest,\n socket: Socket\n): Promise<void> {\n const { id, method, params } = request;\n\n // Special: status\n if (method === \"status\") {\n const dbStats = await (async () => {\n try {\n if (!storageBackend) return null;\n const fedStats = await storageBackend.getStats();\n const projects = await registryBackend.countProjects();\n return { files: fedStats.files, chunks: fedStats.chunks, projects };\n } catch {\n return null;\n }\n })();\n\n sendResponse(socket, {\n id,\n ok: true,\n result: {\n uptime: Math.floor((Date.now() - startTime) / 1000),\n indexInProgress,\n lastIndexTime: lastIndexTime ? new Date(lastIndexTime).toISOString() : null,\n indexIntervalSecs: daemonConfig.indexIntervalSecs,\n embedInProgress,\n lastEmbedTime: lastEmbedTime ? new Date(lastEmbedTime).toISOString() : null,\n embedIntervalSecs: daemonConfig.embedIntervalSecs,\n socketPath: daemonConfig.socketPath,\n storageBackend: storageBackend?.backendType ?? \"initializing\",\n db: dbStats,\n vaultIndexInProgress,\n lastVaultIndexTime: lastVaultIndexTime ? new Date(lastVaultIndexTime).toISOString() : null,\n vaultPath: daemonConfig.vaultPath ?? null,\n workQueue: getQueueStats(),\n // Null when the backend is answering. Present, this is the reason\n // everything else in this payload is stalled — and the reason status\n // used to report \"idle\" for two days while nothing progressed.\n backendOutage: getBackendOutage(),\n },\n });\n socket.end();\n return;\n }\n\n // Special: index_now — trigger immediate index (non-blocking response)\n if (method === \"index_now\") {\n runIndex().catch((e) => {\n process.stderr.write(`[pai-daemon] index_now error: ${e}\\n`);\n });\n sendResponse(socket, { id, ok: true, result: { triggered: true } });\n socket.end();\n return;\n }\n\n // Special: vault_index_now — trigger immediate vault index (non-blocking response)\n if (method === \"vault_index_now\") {\n runVaultIndex().catch((e) => {\n process.stderr.write(`[pai-daemon] vault_index_now error: ${e}\\n`);\n });\n sendResponse(socket, { id, ok: true, result: { triggered: true } });\n socket.end();\n return;\n }\n\n // Special: notification_get_config\n if (method === \"notification_get_config\") {\n sendResponse(socket, {\n id,\n ok: true,\n result: {\n config: notificationConfig,\n activeChannels: Object.entries(notificationConfig.channels)\n .filter(([ch, cfg]) => ch !== \"voice\" && (cfg as { enabled: boolean }).enabled)\n .map(([ch]) => ch),\n },\n });\n socket.end();\n return;\n }\n\n // Special: notification_set_config\n if (method === \"notification_set_config\") {\n try {\n const p = params as {\n mode?: NotificationMode;\n channels?: Record<string, unknown>;\n routing?: Record<string, unknown>;\n };\n const updated = patchNotificationConfig({\n mode: p.mode,\n channels: p.channels as Parameters<typeof patchNotificationConfig>[0][\"channels\"],\n routing: p.routing as Parameters<typeof patchNotificationConfig>[0][\"routing\"],\n });\n setNotificationConfig(updated);\n sendResponse(socket, { id, ok: true, result: { config: updated } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // Special: notification_send\n if (method === \"notification_send\") {\n const p = params as {\n event?: string;\n message?: string;\n title?: string;\n };\n\n if (!p.message) {\n sendResponse(socket, { id, ok: false, error: \"notification_send: message is required\" });\n socket.end();\n return;\n }\n\n const event = (p.event as Parameters<typeof routeNotification>[0][\"event\"]) ?? \"info\";\n\n routeNotification(\n { event, message: p.message, title: p.title },\n notificationConfig\n ).then((result) => {\n sendResponse(socket, { id, ok: true, result });\n socket.end();\n }).catch((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n socket.end();\n });\n return;\n }\n\n // ---- Observation methods (Postgres only) --------------------------------\n\n if (method === \"observation_store\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Observations require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as {\n session_id: string;\n type: string;\n title: string;\n narrative?: string;\n tool_name: string;\n tool_input_summary?: string;\n files_read?: string[];\n files_modified?: string[];\n concepts?: string[];\n content_hash?: string;\n cwd?: string;\n };\n\n const insertedId = await storageBackend.storeObservationWithProject(registryBackend, {\n session_id: p.session_id,\n type: p.type as \"decision\" | \"bugfix\" | \"feature\" | \"refactor\" | \"discovery\" | \"change\",\n title: p.title,\n narrative: p.narrative ?? null,\n tool_name: p.tool_name,\n tool_input_summary: p.tool_input_summary ?? undefined,\n files_read: p.files_read ?? [],\n files_modified: p.files_modified ?? [],\n concepts: p.concepts ?? [],\n cwd: p.cwd,\n });\n\n sendResponse(socket, { id, ok: true, result: { ok: true, id: insertedId } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // ---- Skill telemetry (Postgres only) ------------------------------------\n\n if (method === \"skill_telemetry_record\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Skill telemetry requires Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as {\n skill_name: string;\n source?: string;\n scope?: string;\n cwd?: string;\n };\n\n let project_slug: string | null = null;\n if (p.cwd) {\n const row = await registryBackend.findProjectByCwdPrefix(p.cwd);\n if (row) project_slug = row.slug;\n }\n\n await storageBackend.recordSkillInvocation({\n skill_name: p.skill_name,\n source: p.source,\n scope: p.scope,\n project_slug,\n });\n\n sendResponse(socket, { id, ok: true, result: { ok: true } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n if (method === \"skill_telemetry_query\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Skill telemetry requires Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as { scope?: string; status?: string; limit?: number };\n const rows = await storageBackend.querySkillTelemetry({\n scope: p.scope,\n status: p.status,\n limit: p.limit,\n });\n sendResponse(socket, { id, ok: true, result: rows });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n if (method === \"observation_query\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Observations require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as {\n project_id?: number;\n session_id?: string;\n type?: string;\n limit?: number;\n offset?: number;\n };\n\n const rows = await storageBackend.queryObservations({\n projectId: p.project_id,\n sessionId: p.session_id,\n type: p.type,\n limit: p.limit,\n offset: p.offset,\n });\n sendResponse(socket, { id, ok: true, result: rows });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n if (method === \"observation_recent\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Observations require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as { project_id?: number; cwd?: string; limit?: number };\n const limit = p.limit ?? 20;\n\n let resolvedProjectId = p.project_id;\n let resolvedProjectSlug: string | undefined;\n if (resolvedProjectId === undefined && p.cwd) {\n const row = await registryBackend.findProjectByCwdPrefix(p.cwd);\n if (row) {\n resolvedProjectId = row.id;\n resolvedProjectSlug = row.slug;\n }\n }\n\n let rows;\n if (resolvedProjectId !== undefined) {\n rows = await storageBackend.queryRecentObservations(resolvedProjectId, limit);\n } else {\n rows = await storageBackend.queryObservations({ limit });\n }\n sendResponse(socket, { id, ok: true, result: { rows, project_slug: resolvedProjectSlug } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // observation_list — alias for observation_query with project slug resolution\n if (method === \"observation_list\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Observations require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as {\n project_slug?: string;\n session_id?: string;\n type?: string;\n limit?: number;\n offset?: number;\n };\n\n let projectId: number | undefined;\n if (p.project_slug) {\n const row = await registryBackend.getProjectBySlug(p.project_slug);\n projectId = row?.id;\n }\n\n const rows = await storageBackend.queryObservations({\n projectId,\n sessionId: p.session_id,\n type: p.type,\n limit: p.limit ?? 20,\n offset: p.offset ?? 0,\n });\n sendResponse(socket, { id, ok: true, result: rows });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // observation_stats — aggregate statistics\n if (method === \"observation_stats\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Observations require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const stats = await storageBackend.getObservationStats();\n sendResponse(socket, { id, ok: true, result: stats });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n if (method === \"session_summary_store\") {\n if (!storageBackend?.supportsPostgresFeatures) {\n sendResponse(socket, { id, ok: false, error: \"Session summaries require Postgres backend\" });\n socket.end();\n return;\n }\n try {\n const p = params as {\n session_id: string;\n project_id?: number;\n project_slug?: string;\n cwd?: string;\n request?: string;\n investigated?: string;\n learned?: string;\n completed?: string;\n next_steps?: string;\n observation_count?: number;\n };\n\n let resolvedProjectId = p.project_id ?? null;\n let resolvedProjectSlug = p.project_slug ?? null;\n if (resolvedProjectId === null && p.cwd) {\n const row = await registryBackend.findProjectByCwdPrefix(p.cwd);\n if (row) {\n resolvedProjectId = row.id;\n resolvedProjectSlug = row.slug;\n }\n }\n\n await storageBackend.storeSessionSummary({\n session_id: p.session_id,\n project_id: resolvedProjectId,\n project_slug: resolvedProjectSlug,\n request: p.request ?? null,\n investigated: p.investigated ?? null,\n learned: p.learned ?? null,\n completed: p.completed ?? null,\n next_steps: p.next_steps ?? null,\n observation_count: p.observation_count ?? 0,\n });\n\n sendResponse(socket, { id, ok: true, result: { ok: true } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // work_queue_enqueue — hooks push work items here instead of doing heavy work inline\n if (method === \"work_queue_enqueue\") {\n try {\n const p = params as {\n type?: string;\n priority?: number;\n payload?: Record<string, unknown>;\n maxAttempts?: number;\n };\n\n if (!p.type) {\n sendResponse(socket, { id, ok: false, error: \"work_queue_enqueue: type is required\" });\n socket.end();\n return;\n }\n\n const item = enqueue({\n type: p.type as import(\"../../daemon/work-queue.js\").WorkItemType,\n priority: p.priority,\n payload: p.payload ?? {},\n maxAttempts: p.maxAttempts,\n });\n\n notifyNewWork();\n\n sendResponse(socket, { id, ok: true, result: { id: item.id, status: item.status } });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n return;\n }\n\n // work_queue_stats — return current queue statistics\n if (method === \"work_queue_stats\") {\n sendResponse(socket, { id, ok: true, result: getQueueStats() });\n socket.end();\n return;\n }\n\n // All other methods: PAI tool dispatch\n try {\n const result = await dispatchTool(method, params);\n sendResponse(socket, { id, ok: true, result });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id, ok: false, error: msg });\n }\n socket.end();\n}\n","/**\n * IPC server and daemon entry point.\n * Owns: isSocketLive, startIpcServer, serve (exported).\n */\n\nimport { existsSync, unlinkSync } from \"node:fs\";\nimport { createServer, connect, Socket, Server } from \"node:net\";\nimport { setPriority } from \"node:os\";\nimport { createStorageBackend, createRegistryBackend } from \"../../storage/factory.js\";\nimport { configureEmbeddingModel } from \"../../memory/embeddings.js\";\nimport { loadNotificationConfig } from \"../../notifications/config.js\";\nimport type { PaiDaemonConfig } from \"../config.js\";\nimport type { IpcRequest } from \"./types.js\";\nimport {\n setRegistryBackend,\n setStorageBackend,\n setDaemonConfig,\n setStartTime,\n setNotificationConfig,\n setShutdownRequested,\n indexInProgress,\n embedInProgress,\n indexSchedulerTimer,\n embedSchedulerTimer,\n cacheKeepaliveTimer,\n storageBackend,\n} from \"./state.js\";\nimport { startIndexScheduler, startEmbedScheduler, startRegistryScanScheduler, startWorkerSupervisor, startCacheKeepalive, startSessionKeepalive } from \"./scheduler.js\";\nimport { handleRequest, sendResponse } from \"./handler.js\";\nimport { loadQueue } from \"../../daemon/work-queue.js\";\nimport { startWorker, stopWorker } from \"../../daemon/work-queue-worker.js\";\n\n// ---------------------------------------------------------------------------\n// IPC helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether an existing socket file is actually being served by a live process.\n */\nfunction isSocketLive(path: string): Promise<boolean> {\n return new Promise((resolve) => {\n const client = connect(path);\n const timer = setTimeout(() => { client.destroy(); resolve(false); }, 500);\n client.on(\"connect\", () => { clearTimeout(timer); client.end(); resolve(true); });\n client.on(\"error\", () => { clearTimeout(timer); resolve(false); });\n });\n}\n\n/**\n * Start the Unix Domain Socket IPC server.\n */\nasync function startIpcServer(socketPath: string): Promise<Server> {\n if (existsSync(socketPath)) {\n const live = await isSocketLive(socketPath);\n if (live) {\n throw new Error(\"Another daemon is already running — socket is live. Aborting startup.\");\n }\n try {\n unlinkSync(socketPath);\n process.stderr.write(\"[pai-daemon] Removed stale socket file.\\n\");\n } catch {\n // If we can't remove it, bind will fail with a clear error\n }\n }\n\n const server = createServer((socket: Socket) => {\n let buffer = \"\";\n\n socket.on(\"data\", (chunk: Buffer) => {\n buffer += chunk.toString();\n let nl: number;\n while ((nl = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, nl);\n buffer = buffer.slice(nl + 1);\n\n if (line.trim() === \"\") continue;\n\n let request: IpcRequest;\n try {\n request = JSON.parse(line) as IpcRequest;\n } catch {\n sendResponse(socket, { id: \"?\", ok: false, error: \"Invalid JSON\" });\n socket.destroy();\n return;\n }\n\n handleRequest(request, socket).catch((e: unknown) => {\n const msg = e instanceof Error ? e.message : String(e);\n sendResponse(socket, { id: request.id, ok: false, error: msg });\n socket.destroy();\n });\n }\n });\n\n socket.on(\"error\", () => {\n // Client disconnected — nothing to do\n });\n });\n\n server.on(\"error\", (e) => {\n process.stderr.write(`[pai-daemon] IPC server error: ${e}\\n`);\n });\n\n server.listen(socketPath, () => {\n process.stderr.write(\n `[pai-daemon] IPC server listening on ${socketPath}\\n`\n );\n });\n\n return server;\n}\n\n// ---------------------------------------------------------------------------\n// Main daemon entry point\n// ---------------------------------------------------------------------------\n\nexport async function serve(config: PaiDaemonConfig): Promise<void> {\n setDaemonConfig(config);\n setStartTime(Date.now());\n\n setNotificationConfig(loadNotificationConfig());\n\n process.stderr.write(\"[pai-daemon] Starting daemon...\\n\");\n process.stderr.write(`[pai-daemon] Socket: ${config.socketPath}\\n`);\n process.stderr.write(`[pai-daemon] Storage backend: ${config.storageBackend}\\n`);\n const { notificationConfig } = await import(\"./state.js\");\n process.stderr.write(\n `[pai-daemon] Notification mode: ${notificationConfig.mode}\\n`\n );\n\n // Lower scheduling priority so the daemon yields CPU to interactive sessions\n try { setPriority(process.pid, 10); } catch { /* non-fatal */ }\n\n configureEmbeddingModel(config.embeddingModel);\n\n // Connect the registry backend in the background — non-blocking, since it\n // may take a few retries under Postgres (waitForPostgres: true never\n // silently falls back to SQLite, matching the federation backend below).\n // Callers that need it before it resolves (status, observation IPC methods)\n // already tolerate an unready backend via their own try/catch.\n void createRegistryBackend(config, { waitForPostgres: true })\n .then((backend) => {\n setRegistryBackend(backend);\n process.stderr.write(`[pai-daemon] Registry backend: ${backend.backendType}\\n`);\n })\n .catch((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(`[pai-daemon] Fatal: Could not open registry: ${msg}\\n`);\n process.exit(1);\n });\n\n // Start the IPC server immediately so `pai daemon status` answers even while\n // we are still waiting for the federation backend (e.g. Postgres coming up\n // after a reboot). The status handler tolerates a not-yet-ready backend.\n const server = await startIpcServer(config.socketPath);\n\n // Registry scan scheduler only needs the registry DB — safe to start now.\n startRegistryScanScheduler();\n\n // Worker supervision reads the workers ledger off disk and pushes events to\n // owning sessions — no backend dependency, so it starts with the IPC server.\n startWorkerSupervisor();\n\n // Cache keepalive spawns trivial workers on the workers config — also no\n // backend dependency (observations store opportunistically when Postgres\n // is up), so it starts with the IPC server too.\n startCacheKeepalive();\n\n // Interactive-session cache keepalive: also no backend dependency (reads\n // AIBroker + transcript files, writes the workers ledger + its own state\n // file), so it starts with the IPC server too.\n startSessionKeepalive();\n\n // Connect the federation backend in the background. When storageBackend is\n // \"postgres\" this retries forever (never silently falls back to SQLite), so\n // the boot race with Docker/Postgres resolves itself once Postgres is up.\n // Only then do we start the federation-dependent schedulers and work queue —\n // this also keeps the first index run from firing against an unready backend.\n void createStorageBackend(config, { waitForPostgres: true })\n .then((backend) => {\n setStorageBackend(backend);\n process.stderr.write(\n `[pai-daemon] Federation backend: ${backend.backendType}\\n`\n );\n\n startIndexScheduler();\n\n if (backend.supportsPostgresFeatures) {\n startEmbedScheduler();\n } else {\n process.stderr.write(\n \"[pai-daemon] Embed scheduler: disabled (SQLite backend)\\n\"\n );\n }\n\n // Work queue — load persisted items and start worker loop\n loadQueue();\n startWorker();\n })\n .catch((e) => {\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(\n `[pai-daemon] Fatal: Could not open federation storage: ${msg}\\n`\n );\n process.exit(1);\n });\n\n const shutdown = async (signal: string): Promise<void> => {\n process.stderr.write(`\\n[pai-daemon] ${signal} received. Stopping.\\n`);\n\n setShutdownRequested(true);\n\n if (indexSchedulerTimer) clearInterval(indexSchedulerTimer);\n if (embedSchedulerTimer) clearInterval(embedSchedulerTimer);\n if (cacheKeepaliveTimer) clearInterval(cacheKeepaliveTimer);\n\n stopWorker();\n\n server.close();\n\n const SHUTDOWN_TIMEOUT_MS = 10_000;\n const POLL_INTERVAL_MS = 100;\n const deadline = Date.now() + SHUTDOWN_TIMEOUT_MS;\n\n if (indexInProgress || embedInProgress) {\n process.stderr.write(\n `[pai-daemon] Waiting for in-progress operations to finish ` +\n `(index=${indexInProgress}, embed=${embedInProgress})...\\n`\n );\n\n while ((indexInProgress || embedInProgress) && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n if (indexInProgress || embedInProgress) {\n process.stderr.write(\"[pai-daemon] Shutdown timeout reached — forcing exit.\\n\");\n } else {\n process.stderr.write(\"[pai-daemon] In-progress operations finished.\\n\");\n }\n }\n\n try {\n await storageBackend.close();\n } catch {\n // ignore\n }\n\n try {\n unlinkSync(config.socketPath);\n } catch {\n // ignore\n }\n\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => { shutdown(\"SIGINT\").catch(() => process.exit(0)); });\n process.on(\"SIGTERM\", () => { shutdown(\"SIGTERM\").catch(() => process.exit(0)); });\n\n // Keep process alive\n await new Promise(() => {});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,UACP,QACA,QACG;CACH,MAAM,SAAS,EAAE,GAAG,QAAQ;AAC5B,MAAK,MAAM,OAAO,OAAO,KAAK,OAAO,EAAE;EACrC,MAAM,SAAS,OAAO;AACtB,MAAI,WAAW,UAAa,WAAW,KAAM;EAC7C,MAAM,SAAU,OAAmC;AACnD,MACE,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,OAAO,IACtB,OAAO,WAAW,YAClB,WAAW,QACX,CAAC,MAAM,QAAQ,OAAO,CAEtB,CAAC,OAAmC,OAAO,UACzC,QACA,OACD;MAED,CAAC,OAAmC,OAAO;;AAG/C,QAAO;;;;;;AAWT,SAAgB,yBAA6C;CAC3D,IAAI;AACJ,KAAI;AACF,WAAS,mBAAmB;SACtB;AACN,SAAO,EAAE,GAAG,6BAA6B;;CAG3C,MAAM,SAAS,OAAO;AACtB,KAAI,CAAC,UAAU,OAAO,WAAW,SAC/B,QAAO,EAAE,GAAG,6BAA6B;AAG3C,QAAO,UACL,6BACA,OACD;;;;;;AAWH,SAAgB,uBAAuB,QAAkC;CACvE,IAAI,OAAgC,EAAE;AACtC,KAAI;AACF,SAAO,mBAAmB;SACpB;AAKR,MAAK,mBAAmB;AAExB,oBAAmB,KAAK;;;;;;AAW1B,SAAgB,wBAAwB,OAIjB;CACrB,MAAM,UAAU,wBAAwB;AAExC,KAAI,MA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