{"version":3,"file":"server.mjs","names":["ignore","Type.String","Type.Object","Type.Array","Type.Union","Type.Literal","Type.Optional","Type.Integer","Type.Object","HELP_WHEN"],"sources":["../../../../../../core/po-core/dist/src/schemas/pluginContributions.mjs","../../../../../../core/po-core/dist/src/services/pluginLifecycle/index.mjs","../../../../../../core/po-core/dist/src/extensions/serverPlugin.mjs","../../../../../../core/po-core/dist/src/services/loginFlow/index.mjs","../../../../../../core/po-core/dist/src/services/providerAuth/index.mjs","../../../../../../core/po-core/dist/machineApi.mjs","../../../../../../core/po-core/dist/remoteApi.mjs","../../../../../../../node_modules/.pnpm/ignore@7.0.12/node_modules/ignore/index.js","../../../../../../core/po-core/dist/sessionFilesApi.mjs","../../../../../../core/po-core/dist/src/schemas/help.mjs","../../../../../../cli/po/src/cli/commands/sync/presenter.ts","../../../../../../cli/po/src/cli/commands/sync/index.ts","../../../../../../cli/po/src/cli/commands/doctor/index.ts","../../../../../../cli/po/src/extensions/setupDiagnostics.ts","../../../../../../cli/po/src/extensions/server.ts"],"sourcesContent":["//#region src/schemas/pluginContributions.ts\n/** Preserve schema inference at the declaration, before heterogeneous composition. */\nfunction defineTool(tool) {\n\treturn {\n\t\t...tool,\n\t\tkind: \"tool\"\n\t};\n}\nfunction defineCommand(command) {\n\treturn {\n\t\t...command,\n\t\tkind: \"command\"\n\t};\n}\n//#endregion\nexport { defineCommand, defineTool };\n\n//# sourceMappingURL=pluginContributions.mjs.map","//#region src/services/pluginLifecycle/index.ts\n/** Runs ordered cleanup steps to completion before reporting their failures. */\nasync function runCleanups(steps, message) {\n\tconst errors = [];\n\tfor (const step of steps) {\n\t\tif (!step) continue;\n\t\ttry {\n\t\t\tawait step();\n\t\t} catch (error) {\n\t\t\terrors.push(error);\n\t\t}\n\t}\n\tif (errors.length) throw new AggregateError(errors, message);\n}\n/** Owns one mounted plugin, independently of the host supplying its context. */\nfunction createPluginLifecycle(makeContext) {\n\tconst controller = new AbortController();\n\tconst context = makeContext(controller.signal);\n\tconst cleanups = [];\n\tlet hooks;\n\tlet startup;\n\tlet disposal;\n\tlet started = false;\n\tlet draining = false;\n\tconst dispose = () => {\n\t\tif (disposal) return disposal;\n\t\tdisposal = Promise.resolve().then(async () => {\n\t\t\tawait startup?.catch(() => void 0);\n\t\t\tdraining = true;\n\t\t\tconst onStop = hooks?.onStop;\n\t\t\tconst onDispose = hooks?.onDispose;\n\t\t\tawait runCleanups([\n\t\t\t\tstarted && onStop ? () => onStop(context) : void 0,\n\t\t\t\t...cleanups.splice(0).reverse(),\n\t\t\t\tonDispose ? () => onDispose(context) : void 0\n\t\t\t], \"Plugin cleanup failed.\");\n\t\t});\n\t\tcontroller.abort();\n\t\treturn disposal;\n\t};\n\treturn {\n\t\tcontext,\n\t\town(cleanup) {\n\t\t\tif (draining) throw new Error(\"Cannot own a registration after plugin cleanup begins.\");\n\t\t\tcleanups.push(cleanup);\n\t\t},\n\t\tmount(definition, register) {\n\t\t\tif (startup || disposal) return Promise.reject(/* @__PURE__ */ new Error(\"A plugin lifecycle can only mount once.\"));\n\t\t\tstartup = Promise.resolve().then(async () => {\n\t\t\t\tcontroller.signal.throwIfAborted();\n\t\t\t\tconst resolved = typeof definition === \"function\" ? await definition() : definition;\n\t\t\t\thooks = resolved;\n\t\t\t\tcontroller.signal.throwIfAborted();\n\t\t\t\tawait register(resolved);\n\t\t\t\tcontroller.signal.throwIfAborted();\n\t\t\t\tstarted = true;\n\t\t\t\tif (resolved.onStart) await resolved.onStart(context);\n\t\t\t\tcontroller.signal.throwIfAborted();\n\t\t\t});\n\t\t\treturn startup.catch(async (error) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait dispose();\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tconst errors = cleanupError instanceof AggregateError ? cleanupError.errors : [cleanupError];\n\t\t\t\t\tthrow new AggregateError([error, ...errors], error instanceof Error ? error.message : String(error), { cause: error });\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t},\n\t\tdispose\n\t};\n}\n//#endregion\nexport { createPluginLifecycle, runCleanups };\n\n//# sourceMappingURL=index.mjs.map","import { PO_SERVER_SCOPE_LEVELS, PO_SERVER_SCOPE_SERVICE, requirePoServerScope } from \"../schemas/serverScope.mjs\";\nimport { createPluginLifecycle, runCleanups } from \"../services/pluginLifecycle/index.mjs\";\nimport { readPoHeadlessHost } from \"../schemas/headless.mjs\";\nimport { PO_SERVER_HOST_SERVICE, requirePoServerHost } from \"../schemas/serverPlugin.mjs\";\n//#region src/extensions/serverPlugin.ts\n/**\n* Holds a built root's teardown for the levels that reuse it.\n*\n* The building level keeps the root's hooks in its own lifecycle, but each one runs only when no\n* inner level still holds a lease. Otherwise the last lease to be released runs what the building\n* level held back. So a reload of the building level installs the new build for itself and for every\n* level that mounts from then on, while a session already running keeps the root it mounted with\n* until it closes.\n*/\nfunction holdRoot(built) {\n\tlet leases = 0;\n\tlet owed = {\n\t\tstop: false,\n\t\tdispose: false\n\t};\n\tlet stopped = false;\n\tlet disposed = false;\n\tconst stop = async (context) => {\n\t\tif (stopped) return;\n\t\tstopped = true;\n\t\tawait built.onStop?.(context);\n\t};\n\tconst dispose = async (context) => {\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\tawait built.onDispose?.(context);\n\t};\n\treturn {\n\t\theld: {\n\t\t\tvalue: built.value,\n\t\t\t...built.activities === void 0 ? {} : { activities: built.activities },\n\t\t\tacquire() {\n\t\t\t\tleases += 1;\n\t\t\t\tlet released = false;\n\t\t\t\treturn async () => {\n\t\t\t\t\tif (released) return;\n\t\t\t\t\treleased = true;\n\t\t\t\t\tleases -= 1;\n\t\t\t\t\tif (leases > 0 || owed.context === void 0) return;\n\t\t\t\t\tconst context = owed.context;\n\t\t\t\t\tawait runCleanups([owed.stop ? () => stop(context) : void 0, owed.dispose ? () => dispose(context) : void 0], \"Shared root cleanup failed.\");\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t\tdeclaration: {\n\t\t\t...built,\n\t\t\tonStop: async (context) => {\n\t\t\t\towed = {\n\t\t\t\t\t...owed,\n\t\t\t\t\tstop: true,\n\t\t\t\t\tcontext\n\t\t\t\t};\n\t\t\t\tif (leases === 0) await stop(context);\n\t\t\t},\n\t\t\tonDispose: async (context) => {\n\t\t\t\towed = {\n\t\t\t\t\t...owed,\n\t\t\t\t\tdispose: true,\n\t\t\t\t\tcontext\n\t\t\t\t};\n\t\t\t\tif (leases === 0) await dispose(context);\n\t\t\t}\n\t\t}\n\t};\n}\nconst depth = (level) => PO_SERVER_SCOPE_LEVELS.indexOf(level);\n/** Throws for a contract listed where it cannot work, so a bad declaration fails at load, not at mount. */\nfunction checkContracts(plugin) {\n\tfor (const level of PO_SERVER_SCOPE_LEVELS) {\n\t\tconst provided = plugin.provides?.[level] ?? [];\n\t\tif (provided.length > 0 && plugin[level] === void 0) throw new Error(`Server plugin '${plugin.name}' provides contracts at the ${level} level but declares nothing there.`);\n\t\tconst names = /* @__PURE__ */ new Set();\n\t\tfor (const contract of provided) {\n\t\t\tif (contract.scope !== level) throw new Error(`Server plugin '${plugin.name}' lists the ${contract.scope} contract '${contract.name}' as provided at the ${level} level.`);\n\t\t\tif (names.has(contract.name)) throw new Error(`Server plugin '${plugin.name}' provides contract '${contract.name}' twice.`);\n\t\t\tnames.add(contract.name);\n\t\t}\n\t\tfor (const contract of plugin.injects?.[level] ?? []) if (depth(contract.scope) > depth(level)) throw new Error(`Server plugin '${plugin.name}' cannot inject the ${contract.scope} contract '${contract.name}' at the ${level} level.`);\n\t}\n}\nfunction defineServerPlugin(plugin) {\n\tcheckContracts(plugin);\n\treturn {\n\t\tname: plugin.name,\n\t\t...plugin.providerOverrides ? { providerOverrides: plugin.providerOverrides } : {},\n\t\t...plugin.provides ? { provides: plugin.provides } : {},\n\t\t...plugin.injects ? { injects: plugin.injects } : {},\n\t\tinject: [.../* @__PURE__ */ new Set([\n\t\t\tPO_SERVER_HOST_SERVICE,\n\t\t\tPO_SERVER_SCOPE_SERVICE,\n\t\t\t...plugin.inject ?? []\n\t\t])],\n\t\tasync apply(context) {\n\t\t\tconst level = requirePoServerHost(context).scope;\n\t\t\tconst declaration = plugin[level];\n\t\t\tif (!declaration) return void 0;\n\t\t\tconst required = (plugin.injects?.[level] ?? []).map((contract) => contract.name);\n\t\t\tif (required.length === 0) return mount(plugin, declaration, context);\n\t\t\tawait context.inject(required, (inner) => mount(plugin, declaration, inner));\n\t\t}\n\t};\n}\nasync function mount(owner, declaration, context) {\n\tconst host = requirePoServerHost(context);\n\tconst level = host.scope;\n\tconst agent = level === \"session\" ? readPoHeadlessHost(context) : void 0;\n\tconst share = requirePoServerScope(context).plugin(owner);\n\t/** Every root this level holds, built here or reused, for the levels inside it. */\n\tconst roots = {};\n\t/** What this level holds of the build's shared values and outer roots, released once it has unwound. */\n\tconst leases = [];\n\tlet withdraw;\n\tconst lifecycle = createPluginLifecycle((signal) => ({\n\t\tcontext,\n\t\thost,\n\t\tagent,\n\t\tsignal,\n\t\tresources: { async acquire(key, create, dispose) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst lease = await share.acquire(key, create, dispose);\n\t\t\tif (signal.aborted) {\n\t\t\t\tawait lease.release();\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t}\n\t\t\tleases.push(() => lease.release());\n\t\t\treturn lease.value;\n\t\t} },\n\t\tasync scopeRoot(rootLevel, root, rootContext) {\n\t\t\tconst reused = share.outer(rootLevel).map((held) => held[rootLevel]).find((candidate) => candidate !== void 0);\n\t\t\tif (reused !== void 0) {\n\t\t\t\tleases.push(reused.acquire());\n\t\t\t\troots[rootLevel] = reused;\n\t\t\t\treturn {\n\t\t\t\t\tvalue: reused.value,\n\t\t\t\t\t...reused.activities === void 0 ? {} : { activities: reused.activities }\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst { held, declaration: owned } = holdRoot(await root(rootContext));\n\t\t\troots[rootLevel] = held;\n\t\t\treturn owned;\n\t\t},\n\t\thosted: (from) => share.outer(from).length > 0\n\t}));\n\tcontext.effect(() => async () => {\n\t\twithdraw?.();\n\t\ttry {\n\t\t\tawait lifecycle.dispose();\n\t\t} finally {\n\t\t\tfor (const release of leases.splice(0).reverse()) try {\n\t\t\t\tawait release();\n\t\t\t} catch (error) {\n\t\t\t\thost.context.onNotice(`server plugin '${owner.name}' could not release a shared value (${error instanceof Error ? error.message : String(error)})`);\n\t\t\t}\n\t\t}\n\t});\n\tconst own = (registration) => {\n\t\tlifecycle.own(() => registration.dispose());\n\t\tif (\"mounted\" in registration && registration.mounted === false) throw new Error(\"Server plugin registration was refused.\");\n\t};\n\tawait lifecycle.mount(() => typeof declaration === \"function\" ? declaration(lifecycle.context) : declaration, async (scope) => {\n\t\tfor (const service of scope.services ?? []) {\n\t\t\tconst fiber = context.plugin(service);\n\t\t\tlifecycle.own(() => fiber.dispose());\n\t\t\tawait fiber;\n\t\t}\n\t\tfor (const channel of scope.channels ?? []) own(host.registerChannel(channel()));\n\t\tfor (const api of scope.api ?? []) own(host.registerApi(api));\n\t\tfor (const method of scope.methods ?? []) own(method.register(host));\n\t\tif (!agent) return;\n\t\tconst session = scope;\n\t\tfor (const restriction of session.toolRestrictions ?? []) {\n\t\t\tif (!(\"restrict\" in restriction)) {\n\t\t\t\town(agent.registerToolRestriction(restriction));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet registration;\n\t\t\tlifecycle.own(() => {\n\t\t\t\tconst current = registration;\n\t\t\t\tregistration = void 0;\n\t\t\t\treturn current?.dispose();\n\t\t\t});\n\t\t\tconst refresh = () => {\n\t\t\t\tif (lifecycle.context.signal.aborted) return;\n\t\t\t\tconst previous = registration;\n\t\t\t\tregistration = void 0;\n\t\t\t\tprevious?.dispose();\n\t\t\t\tregistration = agent.registerToolRestriction(restriction.restrict());\n\t\t\t\tif (\"mounted\" in registration && registration.mounted === false) throw new Error(`Server tool restriction ${restriction.source} was refused.`);\n\t\t\t};\n\t\t\trefresh();\n\t\t\tconst unsubscribe = restriction.subscribe?.(refresh);\n\t\t\tif (unsubscribe) lifecycle.own(unsubscribe);\n\t\t}\n\t\tfor (const resource of session.resources ?? []) if (resource !== void 0) own(agent.registerResource(resource));\n\t\tfor (const tool of session.tools ?? []) if (\"kind\" in tool) own(agent.registerTool({\n\t\t\t...tool,\n\t\t\tasync execute(toolCallId, input, signal, update, execution) {\n\t\t\t\tconst invocationSignal = signal ? AbortSignal.any([signal, lifecycle.context.signal]) : lifecycle.context.signal;\n\t\t\t\tinvocationSignal.throwIfAborted();\n\t\t\t\ttry {\n\t\t\t\t\treturn await tool.execute(input, {\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\tsignal: invocationSignal,\n\t\t\t\t\t\tcwd: execution.cwd,\n\t\t\t\t\t\tupdate: (result) => update?.(result),\n\t\t\t\t\t\tnotify: (request) => execution.client.notify(request)\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: error instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t}],\n\t\t\t\t\t\tisError: true\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n\t\telse own(agent.registerTool(tool));\n\t\tfor (const command of session.commands ?? []) if (\"kind\" in command) own(agent.registerCommand({\n\t\t\t...command,\n\t\t\texecute: (args, execution) => {\n\t\t\t\tlifecycle.context.signal.throwIfAborted();\n\t\t\t\treturn command.execute(args, {\n\t\t\t\t\tcwd: execution.cwd,\n\t\t\t\t\tsignal: lifecycle.context.signal,\n\t\t\t\t\tnotify: (request) => execution.client.notify(request)\n\t\t\t\t});\n\t\t\t}\n\t\t}));\n\t\telse own(agent.registerCommand(command));\n\t\tfor (const hook of session.hooks ?? []) own(agent.registerHook(hook));\n\t\tfor (const activity of session.activities ?? []) own(agent.registerActivity(activity));\n\t});\n\tif (level !== \"session\") withdraw = share.run(roots);\n\treturn () => lifecycle.dispose();\n}\n//#endregion\nexport { defineServerPlugin };\n\n//# sourceMappingURL=serverPlugin.mjs.map","//#region src/services/loginFlow/index.ts\n/** The message Pi's own login dialog uses; a provider flow may match on it. */\nconst CANCELLED_MESSAGE = \"Login cancelled\";\nconst SUPERSEDED_MESSAGE = \"Superseded by a newer prompt\";\n/**\n* Option ids Pi's providers use for their redirect-free login.\n*\n* The spelling is not consistent across providers: openai-codex offers\n* `device_code` and radius offers `device-code`, so both are matched rather\n* than assuming one canonical form.\n*/\nconst DEVICE_CODE_OPTION_IDS = /* @__PURE__ */ new Set([\"device_code\", \"device-code\"]);\n/**\n* The redirect-free option a remote login should take, when the provider\n* offers one.\n*\n* Pi asks browser-or-device-code as an ordinary select. A remote browser\n* cannot receive a loopback redirect, so answering it for the user turns a\n* dead end into the one method that works, rather than showing a choice whose\n* default is broken.\n*/\nfunction deviceCodeOption(prompt) {\n\tif (prompt.type !== \"select\") return void 0;\n\treturn prompt.options.find((option) => DEVICE_CODE_OPTION_IDS.has(option.id))?.id;\n}\nfunction promptView(id, prompt) {\n\tconst view = {\n\t\tid,\n\t\ttype: prompt.type,\n\t\tmessage: prompt.message\n\t};\n\tif (prompt.type === \"select\") view.options = prompt.options.map((option) => ({ ...option }));\n\telse if (prompt.placeholder !== void 0) view.placeholder = prompt.placeholder;\n\treturn view;\n}\n/**\n* The state machine between a provider login and a browser that can only\n* poll and post.\n*\n* A provider asks one question at a time and may withdraw it (a manual-code\n* prompt raced against a callback server aborts when the callback wins), so\n* the flow holds at most one pending prompt, rejects it when its signal\n* fires, and supersedes it if the provider asks again.\n*/\nfunction createLoginFlow(input) {\n\tconst controller = new AbortController();\n\tconst events = [];\n\tlet status = \"running\";\n\tlet error;\n\tlet pending;\n\tlet promptSeq = 0;\n\tconst failPending = (reason) => {\n\t\tconst current = pending;\n\t\tif (!current) return;\n\t\tpending = void 0;\n\t\tcurrent.detach();\n\t\tcurrent.reject(reason);\n\t};\n\tconst interaction = {\n\t\tsignal: controller.signal,\n\t\tprompt(prompt) {\n\t\t\tif (controller.signal.aborted || prompt.signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(CANCELLED_MESSAGE));\n\t\t\tfailPending(/* @__PURE__ */ new Error(SUPERSEDED_MESSAGE));\n\t\t\tif (input.remote) {\n\t\t\t\tconst deviceCode = deviceCodeOption(prompt);\n\t\t\t\tif (deviceCode !== void 0) return Promise.resolve(deviceCode);\n\t\t\t}\n\t\t\tpromptSeq += 1;\n\t\t\tconst view = promptView(String(promptSeq), prompt);\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tconst onAbort = () => failPending(/* @__PURE__ */ new Error(CANCELLED_MESSAGE));\n\t\t\t\tprompt.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tpending = {\n\t\t\t\t\tview,\n\t\t\t\t\tresolve,\n\t\t\t\t\treject,\n\t\t\t\t\tdetach: () => prompt.signal?.removeEventListener(\"abort\", onAbort)\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tnotify(event) {\n\t\t\tevents.push(event);\n\t\t}\n\t};\n\treturn {\n\t\tid: input.id,\n\t\tproviderId: input.providerId,\n\t\tinteraction,\n\t\tsnapshot() {\n\t\t\tconst snapshot = {\n\t\t\t\tid: input.id,\n\t\t\t\tproviderId: input.providerId,\n\t\t\t\tproviderName: input.providerName,\n\t\t\t\ttype: input.type,\n\t\t\t\tstatus,\n\t\t\t\tevents: [...events]\n\t\t\t};\n\t\t\tif (pending) snapshot.prompt = pending.view;\n\t\t\tif (input.remote) snapshot.remote = true;\n\t\t\tif (error !== void 0) snapshot.error = error;\n\t\t\treturn snapshot;\n\t\t},\n\t\tanswer(promptId, value) {\n\t\t\tconst current = pending;\n\t\t\tif (!current || current.view.id !== promptId) return false;\n\t\t\tpending = void 0;\n\t\t\tcurrent.detach();\n\t\t\tcurrent.resolve(value);\n\t\t\treturn true;\n\t\t},\n\t\tcancel() {\n\t\t\tif (status !== \"running\") return;\n\t\t\tstatus = \"cancelled\";\n\t\t\tcontroller.abort();\n\t\t\tfailPending(/* @__PURE__ */ new Error(CANCELLED_MESSAGE));\n\t\t},\n\t\tsettle(outcome) {\n\t\t\tif (status !== \"running\") return;\n\t\t\tif (outcome.ok) status = \"succeeded\";\n\t\t\telse {\n\t\t\t\tstatus = \"failed\";\n\t\t\t\terror = outcome.error;\n\t\t\t}\n\t\t\tfailPending(/* @__PURE__ */ new Error(CANCELLED_MESSAGE));\n\t\t}\n\t};\n}\n//#endregion\nexport { createLoginFlow };\n\n//# sourceMappingURL=index.mjs.map","import \"../chatgptAuth/index.mjs\";\nimport { createLoginFlow } from \"../loginFlow/index.mjs\";\nimport crypto from \"node:crypto\";\n//#region src/services/providerAuth/index.ts\n/** Matches the timeout Pi's own /logout gives the credential store. */\nconst LOGOUT_TIMEOUT_MS = 15e3;\nfunction describe(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n/** The methods a page can start, in the order the TUI's selector lists them. */\nfunction methodsOf(provider) {\n\tconst methods = [];\n\tconst { oauth, apiKey } = provider.auth;\n\tif (oauth) methods.push({\n\t\ttype: \"oauth\",\n\t\tlabel: oauth.loginLabel ?? oauth.name\n\t});\n\tif (apiKey?.login) methods.push({\n\t\ttype: \"api_key\",\n\t\tlabel: apiKey.name\n\t});\n\treturn methods;\n}\n/** Mirrors the status the TUI's login selector shows beside each provider. */\nfunction summarize(runtime, provider) {\n\tconst summary = {\n\t\tid: provider.id,\n\t\tname: provider.name,\n\t\tmethods: methodsOf(provider)\n\t};\n\tif (provider.id === \"po-chatgpt\") summary.kind = \"po-feature\";\n\tconst status = runtime.getProviderAuthStatus(provider.id);\n\tif (status.configured) summary.authenticated = {\n\t\ttype: runtime.isUsingOAuth(provider.id) ? \"oauth\" : \"api_key\",\n\t\tsource: status.label ?? status.source\n\t};\n\treturn summary;\n}\nfunction createProviderAuth(options) {\n\tconst notice = options.onNotice ?? (() => {});\n\tconst load = options.runtime;\n\tconst flows = /* @__PURE__ */ new Map();\n\tlet loading;\n\tconst runtime = () => {\n\t\tloading ??= load().catch((error) => {\n\t\t\tloading = void 0;\n\t\t\tthrow error;\n\t\t});\n\t\treturn loading;\n\t};\n\tconst findProvider = (current, providerId) => current.getProviders().find((provider) => provider.id === providerId);\n\tconst runningFor = (providerId) => [...flows.values()].find((flow) => flow.providerId === providerId && flow.snapshot().status === \"running\");\n\tconst refreshed = async () => {\n\t\tconst current = await runtime();\n\t\ttry {\n\t\t\tawait current.refresh({ allowNetwork: false });\n\t\t} catch (error) {\n\t\t\tnotice(`provider auth refresh failed: ${describe(error)}`);\n\t\t}\n\t\treturn current;\n\t};\n\treturn {\n\t\tasync listProviders() {\n\t\t\tconst current = await refreshed();\n\t\t\treturn current.getProviders().map((provider) => summarize(current, provider)).sort((left, right) => left.name.localeCompare(right.name));\n\t\t},\n\t\tasync startLogin(providerId, type, remote) {\n\t\t\tconst current = await runtime();\n\t\t\tconst provider = findProvider(current, providerId);\n\t\t\tif (!provider) return {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"unknown_provider\",\n\t\t\t\terror: `Unknown provider: ${providerId}`\n\t\t\t};\n\t\t\tif (!methodsOf(provider).some((method) => method.type === type)) return {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"unsupported_method\",\n\t\t\t\terror: `${provider.name} has no ${type} login.`\n\t\t\t};\n\t\t\tif (runningFor(providerId)) return {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"busy\",\n\t\t\t\terror: `A login for ${provider.name} is already in progress.`\n\t\t\t};\n\t\t\tfor (const [id, flow] of flows) if (flow.snapshot().status !== \"running\") flows.delete(id);\n\t\t\tconst flow = createLoginFlow({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tproviderId,\n\t\t\t\tproviderName: provider.name,\n\t\t\t\ttype,\n\t\t\t\t...remote === true ? { remote: true } : {}\n\t\t\t});\n\t\t\tflows.set(flow.id, flow);\n\t\t\tcurrent.login(providerId, type, flow.interaction).then(() => {\n\t\t\t\tflow.settle({ ok: true });\n\t\t\t\tnotice(`signed in to ${provider.name} (${type})`);\n\t\t\t}, (error) => {\n\t\t\t\tflow.settle({\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: describe(error)\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tflow: flow.snapshot()\n\t\t\t};\n\t\t},\n\t\tgetLogin(flowId) {\n\t\t\treturn flows.get(flowId)?.snapshot();\n\t\t},\n\t\tanswerLogin(flowId, promptId, value) {\n\t\t\tconst flow = flows.get(flowId);\n\t\t\tif (!flow) return \"unknown_flow\";\n\t\t\treturn flow.answer(promptId, value) ? \"answered\" : \"not_waiting\";\n\t\t},\n\t\tcancelLogin(flowId) {\n\t\t\tconst flow = flows.get(flowId);\n\t\t\tif (!flow) return void 0;\n\t\t\tflow.cancel();\n\t\t\treturn flow.snapshot();\n\t\t},\n\t\tasync logout(providerId) {\n\t\t\tconst current = await runtime();\n\t\t\tconst provider = findProvider(current, providerId);\n\t\t\tif (!provider) return {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"unknown_provider\",\n\t\t\t\terror: `Unknown provider: ${providerId}`\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tawait current.logout(providerId, { signal: AbortSignal.timeout(LOGOUT_TIMEOUT_MS) });\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tcode: \"runtime\",\n\t\t\t\t\terror: describe(error)\n\t\t\t\t};\n\t\t\t}\n\t\t\tnotice(`signed out of ${provider.name}`);\n\t\t\treturn { ok: true };\n\t\t},\n\t\tasync listModels() {\n\t\t\tconst current = await refreshed();\n\t\t\tconst providers = new Map(current.getProviders().map((provider) => [provider.id, provider.name]));\n\t\t\treturn current.getAvailableSnapshot().filter((model) => current.hasConfiguredAuth(model.provider)).map((model) => ({\n\t\t\t\tvalue: `${model.provider}/${model.id}`,\n\t\t\t\tlabel: model.id,\n\t\t\t\tgroup: providers.get(model.provider) ?? model.provider\n\t\t\t}));\n\t\t},\n\t\tclose() {\n\t\t\tfor (const flow of flows.values()) flow.cancel();\n\t\t\tflows.clear();\n\t\t}\n\t};\n}\n//#endregion\nexport { createProviderAuth };\n\n//# sourceMappingURL=index.mjs.map","import { nodeHost } from \"./src/services/nodeHost/index.mjs\";\nimport { piAgentDirectory } from \"./src/services/piSettings/core.mjs\";\nimport { modelConfigDirectory } from \"./src/services/piSettings/sync.mjs\";\nimport \"./runtimePiSettings.mjs\";\nimport { registerChatgptAuthProvider } from \"./src/services/chatgptLogin/index.mjs\";\nimport { preloadPiExtensions, resolvePiSettingsPackageEntries } from \"./src/services/piExtensionHost/index.mjs\";\nimport { createProviderAuth } from \"./src/services/providerAuth/index.mjs\";\nimport path from \"node:path\";\nimport { ModelRuntime, SettingsManager } from \"@earendil-works/pi-coding-agent\";\n//#region src/server/machineApi.ts\nfunction record(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n/** Machine-owned provider credentials and model catalog, available without a session. */\nfunction createMachineApi(_options) {\n\treturn {\n\t\tbasePath: \"po\",\n\t\tstart(context) {\n\t\t\tif (context.scope !== \"global\") throw new Error(\"Provider authentication requires the global mount.\");\n\t\t\tconst auth = createProviderAuth({\n\t\t\t\tonNotice: (message) => context.onNotice(message),\n\t\t\t\truntime: async () => {\n\t\t\t\t\tconst directory = piAgentDirectory(context.environment, context.homeDirectory);\n\t\t\t\t\tconst modelDir = modelConfigDirectory(directory, context.homeDirectory);\n\t\t\t\t\tconst runtime = await ModelRuntime.create({\n\t\t\t\t\t\tauthPath: path.join(modelDir, \"auth.json\"),\n\t\t\t\t\t\tmodelsPath: path.join(modelDir, \"models.json\")\n\t\t\t\t\t});\n\t\t\t\t\tregisterChatgptAuthProvider(runtime);\n\t\t\t\t\tconst onNotice = (message) => context.onNotice(message);\n\t\t\t\t\tconst cwd = context.homeDirectory ?? nodeHost.homeDirectory();\n\t\t\t\t\tconst settings = SettingsManager.create(cwd, directory);\n\t\t\t\t\tawait preloadPiExtensions({\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tagentDir: directory,\n\t\t\t\t\t\tmodels: runtime,\n\t\t\t\t\t\textensionPaths: await resolvePiSettingsPackageEntries({\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tagentDir: directory,\n\t\t\t\t\t\t\tsettings,\n\t\t\t\t\t\t\thomeDirectory: context.homeDirectory,\n\t\t\t\t\t\t\tonNotice\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tonNotice\n\t\t\t\t\t});\n\t\t\t\t\treturn runtime;\n\t\t\t\t}\n\t\t\t});\n\t\t\tlet closed = false;\n\t\t\treturn {\n\t\t\t\tasync fetch(request) {\n\t\t\t\t\tif (closed) return Response.json({ error: \"Provider mount is closed.\" }, { status: 503 });\n\t\t\t\t\tconst url = new URL(request.url);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (url.pathname === \"/providers\" && request.method === \"GET\") return Response.json({ providers: await auth.listProviders() });\n\t\t\t\t\t\tif (url.pathname === \"/models\" && request.method === \"GET\") return Response.json({ models: await auth.listModels() });\n\t\t\t\t\t\tconst provider = /^\\/providers\\/([^/]+)$/u.exec(url.pathname);\n\t\t\t\t\t\tif (provider && request.method === \"DELETE\") {\n\t\t\t\t\t\t\tconst result = await auth.logout(decodeURIComponent(provider[1]));\n\t\t\t\t\t\t\treturn result.ok ? Response.json({ ok: true }) : Response.json({ error: result.error }, { status: result.code === \"unknown_provider\" ? 404 : 502 });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (url.pathname === \"/logins\" && request.method === \"POST\") {\n\t\t\t\t\t\t\tconst body = await request.json();\n\t\t\t\t\t\t\tif (!record(body) || typeof body.providerId !== \"string\" || body.type !== \"oauth\" && body.type !== \"api_key\") return Response.json({ error: \"A provider and supported login method are required.\" }, { status: 400 });\n\t\t\t\t\t\t\tconst result = await auth.startLogin(body.providerId, body.type);\n\t\t\t\t\t\t\treturn result.ok ? Response.json({ flow: result.flow }, { status: 201 }) : Response.json({ error: result.error }, { status: result.code === \"unknown_provider\" ? 404 : result.code === \"busy\" ? 409 : 400 });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst flow = /^\\/logins\\/([^/]+)(\\/answer)?$/u.exec(url.pathname);\n\t\t\t\t\t\tif (flow) {\n\t\t\t\t\t\t\tconst id = decodeURIComponent(flow[1]);\n\t\t\t\t\t\t\tif (!auth.getLogin(id)) return Response.json({ error: \"Login flow not found.\" }, { status: 404 });\n\t\t\t\t\t\t\tif (flow[2] && request.method === \"POST\") {\n\t\t\t\t\t\t\t\tconst body = await request.json();\n\t\t\t\t\t\t\t\tif (!record(body) || typeof body.promptId !== \"string\" || typeof body.value !== \"string\") return Response.json({ error: \"A prompt ID and answer are required.\" }, { status: 400 });\n\t\t\t\t\t\t\t\treturn auth.answerLogin(id, body.promptId, body.value) === \"answered\" ? Response.json({ flow: auth.getLogin(id) }) : Response.json({ error: \"Login is no longer waiting for this answer.\" }, { status: 409 });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!flow[2] && request.method === \"GET\") return Response.json({ flow: auth.getLogin(id) });\n\t\t\t\t\t\t\tif (!flow[2] && request.method === \"DELETE\") return Response.json({ flow: auth.cancelLogin(id) });\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Response.json({ error: \"Provider route not found.\" }, { status: 404 });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treturn Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: error instanceof SyntaxError ? 400 : 502 });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclose() {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tauth.close();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\nexport { createMachineApi };\n\n//# sourceMappingURL=machineApi.mjs.map","import \"./src/schemas/packageApi.mjs\";\nimport \"./packageApi.mjs\";\n//#region src/server/remoteApi.ts\n/** Global package mount for the machine's Remote Control service. */\nconst remoteApi = {\n\tbasePath: \"remote\",\n\tstart(context) {\n\t\tif (context.scope !== \"global\" || !context.remoteControl) throw new Error(\"Remote Control requires the global headless host.\");\n\t\tconst control = context.remoteControl;\n\t\tlet closed = false;\n\t\treturn {\n\t\t\tfetch(request) {\n\t\t\t\tif (closed) return Response.json({ error: \"Remote Control is closed.\" }, { status: 503 });\n\t\t\t\tif (request.headers.get(\"x-po-api-caller-locality\") === \"remote\") return Response.json({ error: \"Remote Control is local only.\" }, { status: 403 });\n\t\t\t\tconst origin = request.headers.get(\"origin\");\n\t\t\t\tif (origin !== null) {\n\t\t\t\t\tlet allowed = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = new URL(origin);\n\t\t\t\t\t\tallowed = parsed.protocol === \"http:\" && [\n\t\t\t\t\t\t\t\"127.0.0.1\",\n\t\t\t\t\t\t\t\"localhost\",\n\t\t\t\t\t\t\t\"[::1]\"\n\t\t\t\t\t\t].includes(parsed.hostname);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tallowed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!allowed) return Response.json({ error: \"That origin may not control this cockpit.\" }, { status: 403 });\n\t\t\t\t}\n\t\t\t\tconst from = new URL(request.url);\n\t\t\t\tconst suffix = from.pathname === \"/\" ? \"\" : from.pathname;\n\t\t\t\tconst target = new URL(`/api/remote${suffix}${from.search}`, \"http://po.local\");\n\t\t\t\treturn control.fetch(new Request(target, request));\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tclosed = true;\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\nexport { remoteApi };\n\n//# sourceMappingURL=remoteApi.mjs.map","// A simple implementation of make-array\nfunction makeArray (subject) {\n  return Array.isArray(subject)\n    ? subject\n    : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\n\n// The characters that carry a meaning of their own inside a regular\n//   expression, so a literal one has to be escaped before it is emitted.\nconst REGEX_LITERAL_SPECIAL = /[.*+?()[\\]{}^$|\\\\/]/\nconst BOM = '\\uFEFF'\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst DOUBLE_SLASH = '//'\nconst SLASH_CODE = 47\nconst DOT_CODE = 46\n\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n  TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n  Object.defineProperty(object, key, {value})\n  return value\n}\n\nconst RETURN_FALSE = () => false\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n  const {length} = slashes\n  return slashes.slice(0, length - length % 2)\n}\n\n// > The range notation, e.g. [a-zA-Z],\n// > can be used to match one of the characters in a range.\n//\n// gitignore(5) defers to fnmatch(3) for this, and git implements it in\n//   `wildmatch.c`.  A bracket expression has a sub-grammar of its own, which\n//   is neither the surrounding pattern grammar nor the JavaScript one:\n//\n//   - a `]` right after `[` or `[!` is a literal member, not the terminator\n//   - `[:alpha:]` names one of twelve POSIX classes\n//   - `\\` escapes the next member, `]` included\n//   - `*`, `?` and `.` are plain literal members\n//   - an unterminated expression makes the whole pattern match nothing\n//\n// which means the expression can not be located -- let alone translated -- by\n//   a regular expression.  It is scanned out of the pattern before the\n//   replacers below run, and put back once they are done, so that neither the\n//   metacharacter escaper nor the `?` / `*` replacers ever see its body.\n\n// git classifies with its own ASCII-only ctype macros (`wildmatch.c`), never\n//   with the C library ones, so these must not be mapped onto `\\d` / `\\w` /\n//   `\\s`, which are wider.  `/` is left out of every expansion, because a\n//   bracket expression never matches a path separator.\nconst POSIX_CLASSES = {\n  alnum: '0-9A-Za-z',\n  alpha: 'A-Za-z',\n  blank: ' \\\\t',\n  cntrl: '\\\\x00-\\\\x1f\\\\x7f',\n  digit: '0-9',\n  graph: '!-.0-~',\n  lower: 'a-z',\n  print: ' -.0-~',\n  punct: '!-.:-@\\\\[-`{-~',\n  // git's `sane-ctype.h` classifies \\v and \\f as control, not space,\n  //   unlike C's `isspace`\n  space: ' \\\\t\\\\n\\\\r',\n  upper: 'A-Z',\n  xdigit: '0-9A-Fa-f'\n}\n\nconst CLASS_MEMBERS_TO_ESCAPE = '\\\\]^-['\n\nconst escapeMember = char => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0\n  ? char\n  : ESCAPE + char\n\n// > if (matched == negated || ((flags & WM_PATHNAME) && text_ch == '/'))\n// >   return WM_ABORT_TO_STARSTAR;                     (git, `wildmatch.c`)\n// A bracket expression never matches a path separator, whatever its members\n//   say, so a negated class gets `/` as one more excluded character, while a\n//   plain one -- where a literal member or a range could still let `/` in --\n//   is guarded with a lookahead, `/` being impossible to subtract from a\n//   JavaScript character class.\nconst NON_SLASH = '(?!\\\\/)'\n\nconst classSource = (negated, body) => {\n  if (negated) {\n    return `[^\\\\/${body}]`\n  }\n\n  const source = `[${body}]`\n\n  return new RegExp(source).test('/')\n    ? NON_SLASH + source\n    : source\n}\n\n// Scan the bracket expression that starts at `pattern[start] === '['`,\n//   mirroring the member loop of git's `wildmatch.c`.\n// @returns {{end: number, source: string} | null} `null` if the expression is\n//   never terminated, which makes the whole pattern match nothing.\nconst scanBracket = (pattern, start) => {\n  const {length} = pattern\n  let index = start + 1\n  let negated = EMPTY\n\n  const lead = pattern[index]\n  if (lead === '!' || lead === '^') {\n    negated = '^'\n    index ++\n  }\n\n  let body = EMPTY\n\n  // The member a `-` could start a range from, or EMPTY when the previous\n  //   member can not open one (start of the body, or a range / POSIX class\n  //   that has just closed)\n  let prev = EMPTY\n\n  // git scans the members with a do-while, so the first one is consumed\n  //   unconditionally.  That is the whole reason a leading `]` is a member\n  //   and not the terminator.\n  for (;;) {\n    const char = pattern[index]\n\n    if (char === UNDEFINED) {\n      return null\n    }\n\n    if (char === ESCAPE) {\n      const escaped = pattern[index + 1]\n      if (escaped === UNDEFINED) {\n        return null\n      }\n      body += escapeMember(escaped)\n      prev = escaped\n      index ++\n    } else if (\n      char === '-'\n      && prev\n      && index + 1 < length\n      && pattern[index + 1] !== ']'\n    ) {\n      index ++\n      let to = pattern[index]\n      if (to === ESCAPE) {\n        // A pattern can not end on a lone backslash -- `checkPattern` has\n        //   already thrown it away -- so there is an upper bound to read.\n        to = pattern[index += 1]\n      }\n      // An out-of-order range matches nothing in git but is a syntax error in\n      //   JavaScript, so it is dropped.  Its lower bound stays: git tests it\n      //   as a plain member before it ever looks at the `-`, so `[c-a]` does\n      //   match `c`.\n      if (prev <= to) {\n        body += `-${escapeMember(to)}`\n      }\n      prev = EMPTY\n    } else if (char === '[' && pattern[index + 1] === ':') {\n      const nameStart = index + 2\n      let end = nameStart\n      while (end < length && pattern[end] !== ']') {\n        end ++\n      }\n\n      if (end === length) {\n        return null\n      }\n\n      if (end > nameStart && pattern[end - 1] === ':') {\n        const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)]\n\n        // An unknown class name makes the whole pattern match nothing\n        if (expanded === UNDEFINED) {\n          return null\n        }\n\n        body += expanded\n        prev = EMPTY\n        index = end\n      } else {\n        // No `:]` to close it, so the `[` is a plain member and scanning\n        //   resumes right after it.\n        body += escapeMember('[')\n        prev = '['\n        index = nameStart - 2\n      }\n    } else {\n      body += escapeMember(char)\n      prev = char\n    }\n\n    index ++\n\n    if (pattern[index] === ']') {\n      return {\n        end: index,\n        source: classSource(negated, body)\n      }\n    }\n  }\n}\n\n// An empty JavaScript class can never match, which is how a pattern that git\n//   gives up on (`WM_ABORT_ALL`) is expressed here.\nconst NEVER_MATCH = '[]'\n\n// A NUL can appear in neither a `.gitignore` line nor a path, which makes it\n//   the one safe placeholder character.  A literal one in the pattern is\n//   held aside all the same, so a collision is impossible by construction.\nconst PLACEHOLDER = '\\u0000'\nconst REGEX_RESTORE_PLACEHOLDER = new RegExp(\n  `${PLACEHOLDER}(\\\\d+)${PLACEHOLDER}`, 'g'\n)\n\n// The one wildcard the chain does not expand for itself is a trailing `*`. How\n//   it expands depends on the mode (`regex` vs `checkRegex`), so `_make` is\n//   left to do it, and until then the pending wildcard travels as this marker.\n//   That is what keeps it apart from a user-escaped literal `\\*`: the unescape\n//   steps collapse the escaped one to the exact `\\*` a wildcard would leave\n//   behind, so by the time `_make` runs the two are otherwise the same string\n//   and a literal star gets wrongly rewritten into a wildcard. This marker is a\n//   private-use character no compiled pattern carries, and it never survives\n//   into a `RegExp` -- `_make` always turns it back into a real wildcard first.\nconst TRAILING_WILDCARD = '\\uE000'\n\n// A trailing \"/**\" is deferred the same way, because `checkRegex` has to tell\n//   it apart from a trailing \"/*\" (see `checkSourceOf`). For `.ignores()` it\n//   still never matches the folder itself (#21).\nconst TRAILING_DOUBLESTAR = '\\uE001'\n\n// Replace every bracket expression with a placeholder the replacers below\n//   leave alone, and translate it separately.\nconst extractBrackets = pattern => {\n  const sources = []\n  const hold = source =>\n    `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`\n\n  const {length} = pattern\n  let out = EMPTY\n  let index = 0\n\n  while (index < length) {\n    const char = pattern[index]\n\n    if (char === ESCAPE) {\n      // > Put a backslash (\"\\\") in front of ... a character to make it literal.\n      //                                            (gitignore(5) -> fnmatch(3))\n      // A backslash quotes the next character, whatever it is, so `\\d` is a\n      //   literal `d`, not the regex digit class, and `\\?` is a literal `?`,\n      //   not a wildcard. Held aside as its literal here, the escape never\n      //   reaches the replacers below, which would otherwise let `\\d`, `\\b`,\n      //   `\\1`, `\\/` keep their regular-expression meaning, and would turn a\n      //   `\\?` into `[^\\/]`.\n      //\n      // Four escapes are left for the chain, each with dedicated handling it\n      //   would be wrong to bypass: `\\*` (a literal star, told apart from a\n      //   wildcard by `TRAILING_WILDCARD` and the wildcard replacers), `\\[`\n      //   (a literal bracket, the one `[` the bracket replacer still expects),\n      //   `\\ ` (a quoted trailing space), and `\\\\` (a literal backslash). A\n      //   lone trailing backslash can reach here after line-ending cleanup.\n      const escaped = pattern[index + 1]\n\n      if (\n        escaped === UNDEFINED\n        || escaped === SLASH && index + 2 === length\n      ) {\n        // Git removes a final directory slash before matching. An escape\n        //   without a character after that removal makes the pattern invalid.\n        out += hold(NEVER_MATCH)\n      } else if (\n        escaped === '*'\n        || escaped === '['\n        || escaped === SPACE\n        || escaped === ESCAPE\n      ) {\n        out += pattern.slice(index, index + 2)\n      } else {\n        out += hold(\n          REGEX_LITERAL_SPECIAL.test(escaped)\n            ? ESCAPE + escaped\n            : escaped\n        )\n      }\n\n      index += 2\n    } else if (char === PLACEHOLDER) {\n      // Hold a literal placeholder character aside as well, so that pattern\n      //   text can never be mistaken for a placeholder we emitted.\n      out += hold(`[${PLACEHOLDER}]`)\n      index ++\n    } else if (char === '[') {\n      const scanned = scanBracket(pattern, index)\n\n      if (scanned === null) {\n        // git gives up on the whole pattern (`WM_ABORT_ALL`), so whatever\n        //   follows can not make it match either.\n        out += hold(NEVER_MATCH)\n        index = length\n      } else {\n        out += hold(scanned.source)\n        index = scanned.end + 1\n      }\n    } else {\n      out += char\n      index ++\n    }\n  }\n\n  return {\n    source: out,\n    sources\n  }\n}\n\n// A step of the chain below is normally a `[matcher, replacer]` pair handed\n//   to `String.replace`. `DIRECT` marks the ones that are plain string work\n//   instead, and take `(source, pattern)`.\n//\n// Anchoring the two ends is exactly that -- a test of one character and a\n//   concatenation -- and putting it through the regular expression engine\n//   cost a third of this chain for nothing: 167ns where 10ns does the same\n//   job. The two are still steps in the same list, in the same places,\n//   because their position in the order is part of what they mean.\nconst DIRECT = null\n\n// A separator at the beginning or in the middle of a pattern, as opposed to\n//   one at the very end.\nconst REGEX_INNER_SLASH = /\\/(?!$)/\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// >  (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n//      you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\n// The chain that turns one gitignore pattern into a regular expression\n//   source, in order. A step is either\n//\n//   [matcher, replacer]            handed to `String.replace`\n//   [matcher, replacer, required]  the same, but skipped outright unless\n//                                    `required` appears in the string, which\n//                                    the matcher cannot match without\n//   [DIRECT, transform]            plain string work, taking (source, pattern)\n//\n// The `required` character is only ever a shortcut: finding it does not mean\n//   the matcher will match, and not finding it means it cannot. It is there\n//   because scanning for one character costs a fraction of running a matcher\n//   that then finds nothing -- for the wildcard step, whose `[^\\\\]+`\n//   backtracks its way through the whole string before giving up, 11ns\n//   against 400ns.\nconst REPLACERS = [\n\n  // Replace (\\ ) with ' '\n  // Only a space: an escaped tab or other whitespace is already a literal by\n  //   the time it reaches here, and a bare tab must be left as one, not turned\n  //   into a space.\n  // (\\ ) -> ' '\n  // (\\\\ ) -> '\\\\ '\n  // (\\\\\\ ) -> '\\\\ '\n  [\n    // A run of backslashes is taken whole, from its first one, so no match\n    //   ever starts again inside it -- `(\\\\+?) ` did, which made a long run\n    //   quadratic.\n    /(\\\\+)( ?)/g,\n    (_, run, space) => space\n      ? run.slice(0, run.length - run.length % 2) + SPACE\n      : run,\n    ESCAPE + SPACE\n  ],\n\n  // Escape metacharacters\n  // which is written down by users but means special for regular expressions.\n\n  // > There are 12 characters with special meanings:\n  // > - the backslash \\,\n  // > - the caret ^,\n  // > - the dollar sign $,\n  // > - the period or dot .,\n  // > - the vertical bar or pipe symbol |,\n  // > - the question mark ?,\n  // > - the asterisk or star *,\n  // > - the plus sign +,\n  // > - the opening parenthesis (,\n  // > - the closing parenthesis ),\n  // > - and the opening square bracket [,\n  // > - the opening curly brace {,\n  // > These special characters are often called \"metacharacters\".\n  [\n    /[\\\\$.|*+(){^]/g,\n    match => `\\\\${match}`\n  ],\n\n  [\n    // > a question mark (?) matches a single character\n    /(?!\\\\)\\?/g,\n    () => '[^/]',\n    '?'\n  ],\n\n  // leading slash\n  [\n\n    // > A leading slash matches the beginning of the pathname.\n    // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n    // A leading slash matches the beginning of the pathname\n    /^\\//,\n    () => '^',\n    SLASH\n  ],\n\n  // replace special metacharacter slash after the leading slash\n  [\n    /\\//g,\n    () => '\\\\/',\n    SLASH\n  ],\n\n  [\n    // > A leading \"**\" followed by a slash means match in all directories.\n    // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n    // > the same as pattern \"foo\".\n    // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n    // >   under directory \"foo\".\n    // Notice that the '*'s have been replaced as '\\\\*'\n    /^\\^*(?:\\\\\\*\\\\\\*\\\\\\/)+/,\n\n    // '**/foo' <-> 'foo'\n    () => '^(?:.*\\\\/)?',\n    '*'\n  ],\n\n  // starting\n  [\n    // there will be no leading '/'\n    //   (which has been replaced by section \"leading slash\")\n    // If starts with '**', adding a '^' to the regular expression also works\n    DIRECT,\n    (source, pattern) => {\n      // Nothing to anchor to, or already anchored\n      if (!source || source[0] === '^') {\n        return source\n      }\n\n      // If has a slash `/` at the beginning or middle\n      const anchor = !REGEX_INNER_SLASH.test(pattern)\n        // > Prior to 2.22.1\n        // > If the pattern does not contain a slash /,\n        // >   Git treats it as a shell glob pattern\n        // Actually, if there is only a trailing slash,\n        //   git also treats it as a shell glob pattern\n\n        // After 2.22.1 (compatible but clearer)\n        // > If there is a separator at the beginning or middle (or both)\n        // > of the pattern, then the pattern is relative to the directory\n        // > level of the particular .gitignore file itself.\n        // > Otherwise the pattern may also match at any level below\n        // > the .gitignore level.\n        ? '(?:^|\\\\/)'\n\n        // > Otherwise, Git treats the pattern as a shell glob suitable for\n        // >   consumption by fnmatch(3)\n        : '^'\n\n      return anchor + source\n    }\n  ],\n\n  // two globstars\n  [\n    // Use lookahead assertions so that we could match more than one `'/**'`\n    /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n    // Zero, one or several directories\n    // should not use '*', or it will be replaced by the next replacer\n\n    // Check if it is not the last `'/**'`\n    (_, index, str) => index + 6 < str.length\n\n      // case: /**/ at the end of the pattern, i.e. a trailing `'/**/'`\n      // > A trailing `\"/**/\"` (a trailing `\"/**\"` restricted to directories)\n      // >   matches everything inside, but it should not match the current\n      // >   folder itself, so it requires at least one directory segment.\n      // 'a/**/' matches 'a/b/', 'a/x/y/' but not 'a/'\n      ? str.slice(index + 6) === '\\\\/'\n        ? '(?:\\\\/[^\\\\/]+)+'\n\n        // case: /**/\n        // > A slash followed by two consecutive asterisks then a slash matches\n        // >   zero or more directories.\n        // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n        // '/**/'\n        : '(?:\\\\/[^\\\\/]+)*'\n\n      // case: /**\n      // > A trailing `\"/**\"` matches everything inside.\n\n      // #21: everything inside but it should not include the current folder,\n      //   resolved by `_make`\n      : `\\\\/${TRAILING_DOUBLESTAR}`,\n    '*'\n  ],\n\n  // normal intermediate wildcards\n  [\n    // Never replace escaped '*'\n    // ignore rule '\\*' will match the path '*'\n\n    // 'abc.*/' -> go\n    // 'abc.*'  -> skip this rule,\n    //    coz trailing single wildcard will be handed by [trailing wildcard]\n    /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n    // '*.js' matches '.js'\n    // '*.js' doesn't match 'abc'\n    (_, p1, p2) => {\n      // 1.\n      // > An asterisk \"*\" matches anything except a slash.\n      // 2.\n      // > Other consecutive asterisks are considered regular asterisks\n      // > and will match according to the previous rules.\n      const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n      return p1 + unescaped\n    },\n    '*'\n  ],\n\n  // trailing wildcard, held apart from a literal star\n  [\n    // The step above leaves a trailing `*` alone, so a single `\\*` is all that\n    //   can be left at the end here. Whether it is a wildcard or a literal\n    //   turns on the backslashes the user put in front of it: the escaper has\n    //   since doubled every one, so what stands here is those `2N` doubled\n    //   backslashes and then the star's own escape. An even number of the\n    //   original `N` leaves the star unescaped -- a wildcard -- and an odd\n    //   number escapes it -- a literal. This runs while the two are still\n    //   distinct, before the unescape steps below collapse the literal onto\n    //   the very `\\*` a wildcard leaves behind.\n    /(^|[^\\\\])((?:\\\\\\\\)*)\\\\\\*$/,\n\n    (match, p1, p2) =>\n      // `p2` holds the doubled user backslashes; half of them is `N`.\n      (p2.length / 2) % 2 === 0\n        // A real wildcard: carry it to `_make` as the marker, so the unescape\n        //   steps and the trailing-wildcard rewrite can never mistake it for a\n        //   literal `\\*` (nor the reverse).\n        ? p1 + p2 + TRAILING_WILDCARD\n        // A literal star: leave it exactly as it stands for the unescape steps.\n        : match,\n    '*'\n  ],\n\n  [\n    // unescape, revert step 3 except for back slash\n    // For example, if a user escape a '\\\\*',\n    // after step 3, the result will be '\\\\\\\\\\\\*'\n    /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n    () => ESCAPE,\n    ESCAPE + ESCAPE\n  ],\n\n  [\n    // '\\\\\\\\' -> '\\\\'\n    /\\\\\\\\/g,\n    () => ESCAPE,\n    ESCAPE + ESCAPE\n  ],\n\n  [\n    // Every real bracket expression -- POSIX classes included -- has already\n    //   been held aside by `extractBrackets`, so the only `[` left in the\n    //   pattern is an escaped, literal one.\n\n    // `\\` is escaped by step 3\n    /\\\\\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n\n    // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n    (match, range, endEscape, close) =>\n      `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,\n    '['\n  ],\n\n  // ending\n  [\n    // 'js' will not match 'js.'\n    // 'ab' will not match 'abc'\n    DIRECT,\n\n    // WTF!\n    // https://git-scm.com/docs/gitignore\n    // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n    // which re-fixes #24, #38\n\n    // > If there is a separator at the end of the pattern then the pattern\n    // > will only match directories, otherwise the pattern can match both\n    // > files and directories.\n\n    // 'js*' will not match 'a.js'\n    // 'js/' will not match 'a.js'\n    // 'js' will match 'a.js' and 'a.js/'\n    source => {\n      const last = source[source.length - 1]\n\n      // The pattern is empty, or ends in a pending marker `_make` owns --\n      //   the trailing wildcard, or a trailing \"/**\". A trailing `*` that is\n      //   not the marker is a literal star, which anchors like any other\n      //   final character.\n      if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {\n        return source\n      }\n\n      return last === SLASH\n        // foo/ will not match 'foo'\n        ? `${source}$`\n        // foo matches 'foo' and 'foo/'\n        : `${source}(?=$|\\\\/$)`\n    }\n  ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\uE000$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst replaceTrailingWildcard = (_, p1) => {\n  const prefix = p1\n    // '\\^':\n    // '/*' does not match EMPTY\n    // '/*' does not match everything\n\n    // '\\\\\\/':\n    // 'abc/*' does not match 'abc/'\n    ? `${p1}[^/]+`\n\n    // 'a*' matches 'a'\n    // 'a*' matches 'aa'\n    : '[^/]*'\n\n  return `${prefix}(?=$|\\\\/$)`\n}\n\nconst REGEX_REPLACE_TRAILING_DOUBLESTAR = /\\uE001$/\n\n// 'abc/**' matches everything under 'abc', but not 'abc/' itself (#21)\nconst replaceTrailingDoublestar = () => '.+(?=$|\\\\/$)'\n\nconst WILDCARD = '[^\\\\/]*'\n\n// Where a run of non-slash wildcards is split by single fixed characters --\n//   `[^/]*x[^/]*y...` -- the engine has many equivalent ways to lay the\n//   input across the wildcards, and on input that does not match it works\n//   through all of them, so the time grows with the number of wildcards\n//   rather than the length of the path. Every wildcard but the last in such a\n//   run can be pinned to stop at the character that follows it, which leaves\n//   one way to lay out the input and no rewinding, without changing which\n//   paths match: the fixed characters still bound the count, and the last\n//   wildcard still absorbs the rest.\n//\n// The source is read one token at a time -- a wildcard, a single-character\n//   piece (a literal, an escape, a class), or a parenthesised group or anchor\n//   that ends the run -- so only a genuine wildcard is touched.\n\n// The fixed pieces between the wildcard at `at` and the next wildcard of the\n//   run, joined as they appear in the source. A run never holds two wildcards\n//   in a row, so there is always at least one piece.\nconst separatorAfter = (run, at) => {\n  let separator = EMPTY\n\n  for (let index = at + 1; index < run.length && !run[index].wildcard; index ++) {\n    separator += run[index].single\n  }\n\n  return separator\n}\n\nconst pinWildcards = source => {\n  if (source.indexOf(WILDCARD) < 0) {\n    return source\n  }\n\n  const tokens = []\n  const {length} = source\n  let index = 0\n\n  while (index < length) {\n    const char = source[index]\n\n    if (source.startsWith(WILDCARD, index)) {\n      tokens.push({wildcard: true})\n      index += WILDCARD.length\n    } else if (char === '[') {\n      let end = index + 1\n\n      if (source[end] === '^') {\n        end ++\n      }\n\n      if (source[end] === ']') {\n        end ++\n      }\n\n      while (end < length && source[end] !== ']') {\n        end += source[end] === ESCAPE\n          ? 2\n          : 1\n      }\n\n      end ++\n      tokens.push({single: source.slice(index, end)})\n      index = end\n    } else if (char === ESCAPE) {\n      tokens.push({single: source.slice(index, index + 2)})\n      index += 2\n    } else if (char === '(') {\n      let depth = 0\n      let end = index\n\n      do {\n        if (source[end] === ESCAPE) {\n          end ++\n        } else if (source[end] === '(') {\n          depth ++\n        } else if (source[end] === ')') {\n          depth --\n        }\n\n        end ++\n      } while (end < length && depth > 0)\n\n      if ('*+?'.indexOf(source[end]) >= 0) {\n        end ++\n      }\n\n      tokens.push({boundary: source.slice(index, end)})\n      index = end\n    } else if (char === '^' || char === '$') {\n      tokens.push({boundary: char})\n      index ++\n    } else {\n      tokens.push({single: char})\n      index ++\n    }\n  }\n\n  let out = EMPTY\n  let run = []\n\n  const flush = () => {\n    let lastWildcard\n\n    run.forEach((token, at) => {\n      if (token.wildcard) {\n        lastWildcard = at\n      }\n    })\n\n    run.forEach((token, at) => {\n      if (!token.wildcard) {\n        out += token.single\n        return\n      }\n\n      // A wildcard that is not the last in the run is pinned to the whole\n      //   fixed piece that separates it from the next wildcard, not just to\n      //   that piece's first character: stopping at the first character alone\n      //   would let the wildcard hand over at a place where the rest of the\n      //   separator cannot follow, and the pin leaves no way back, so\n      //   `f*o/*/*` would miss `foo/b/c` -- the first `o` of `foo` is not the\n      //   one the `o/` after it needs. Every piece matches exactly one\n      //   character, so pinning to the first place the whole separator fits\n      //   is the leftmost place it can sit, and the wildcards that follow\n      //   take up whatever is left.\n      out += at === lastWildcard\n        ? WILDCARD\n        : `(?:(?!${separatorAfter(run, at)})[^\\\\/])*`\n    })\n\n    run = []\n  }\n\n  tokens.forEach(token => {\n    if (token.boundary === undefined) {\n      run.push(token)\n      return\n    }\n\n    flush()\n    out += token.boundary\n  })\n\n  flush()\n\n  return out\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => {\n  const {source, sources} = extractBrackets(pattern)\n\n  const replaced = REPLACERS.reduce(\n    // A pass whose matcher finds nothing hands back the very string it was\n    //   given, so asking first costs a search and saves a rewrite. Ten of the\n    //   fifteen passes never fire for a typical .gitignore line, and between\n    //   them they were 45% of this chain.\n    (prev, [matcher, replacer, required]) => {\n      if (matcher === DIRECT) {\n        return replacer(prev, pattern)\n      }\n\n      if (required !== UNDEFINED && prev.indexOf(required) < 0) {\n        return prev\n      }\n\n      // A pass whose matcher finds nothing hands back the very string it was\n      //   given, so asking first costs a search and saves a rewrite.\n      return matcher.test(prev)\n        ? prev.replace(matcher, replacer.bind(pattern))\n        : prev\n    },\n    source\n  )\n\n  // Most patterns hold no bracket expression at all, and then there is\n  //   nothing to put back.\n  return sources.length\n    ? replaced.replace(\n      REGEX_RESTORE_PLACEHOLDER,\n      (match, index) => sources[index]\n    )\n    : replaced\n}\n\n// `checkRegex` tests a path with a trailing slash, 'abc/', the way\n//   `git check-ignore` matches that literal string once the directory itself\n//   is known not to be excluded (see `checkIgnore`): a trailing '/' of the\n//   pattern is dropped, a basename pattern sees an empty basename, and only a\n//   pattern whose last segment is a pending wildcard can match what is left\n//   after the final slash -- 'abc/*' and 'abc/**' match 'abc/', and 'abc/**'\n//   also matches 'abc/d/' (#77, #169).\nconst checkSourceOf = (body, prefix) => {\n  if (body[body.length - 1] === SLASH) {\n    prefix = makeRegexPrefix(body.slice(0, - 1))\n  }\n\n  const head = prefix.slice(0, - 1)\n  const last = prefix[prefix.length - 1]\n\n  return last === TRAILING_WILDCARD\n    ? `${head}$`\n    : last === TRAILING_DOUBLESTAR\n      ? `${head}.*$`\n      : NEVER_MATCH\n}\n\n// A trailing slash does not stop a pattern being basename-only: it restricts\n//   the match to a directory, it does not let the pattern reach across one.\n//   Everything else a pattern can hold -- a wildcard, a character class, an\n//   escape -- stays inside a single path segment too, so a pattern with no\n//   separator in it can only ever describe the last one.\nconst matchesBasename = body => {\n  const index = body.indexOf(SLASH)\n\n  return index < 0 || index === body.length - 1\n}\n\n// The last segment of a path, keeping a trailing slash, because a pattern that\n//   ends in one matches only a directory.\n// 'a/b/c.js' -> 'c.js';  'a/b/' -> 'b/';  'c.js' -> 'c.js' (no copy made)\nconst basenameOf = path => {\n  const end = path.length - 1\n\n  const index = path.lastIndexOf(\n    SLASH,\n    path[end] === SLASH\n      ? end - 1\n      : end\n  )\n\n  return index < 0\n    ? path\n    : path.slice(index + 1)\n}\n\n// The parent directory of a path, with its trailing separator, or EMPTY when\n//   the path has none.\n// 'a/b/c' -> 'a/b/';  'a/b/' -> 'a/';  'a' -> EMPTY;  'a/' -> EMPTY\n//\n// A path holding an empty segment has to be taken apart, because its\n//   ancestors are not prefixes of it: the parent of 'a//b' is 'a/', not\n//   'a//', and the parent of '/a/' is nothing at all. Both shapes reach here\n//   -- 'a//b' is accepted outright, and `checkIgnore` does not put the path\n//   it is given through the relative-path check.\n//\n// Every other path is a prefix of itself, and cutting one costs a fraction of\n//   splitting it into an array and joining that back at every level: 73ns\n//   against 207ns.\nconst parentOf = path => {\n  if (\n    path.charCodeAt(0) === SLASH_CODE\n    || path.indexOf(DOUBLE_SLASH) >= 0\n  ) {\n    const slices = path.split(SLASH).filter(Boolean)\n\n    slices.pop()\n\n    return slices.length\n      ? slices.join(SLASH) + SLASH\n      : EMPTY\n  }\n\n  const end = path.length - 1\n\n  // Look back from before a trailing separator, since that one belongs to the\n  //   path itself.\n  //\n  // A negative place to start would be a trap here: `lastIndexOf` clamps one\n  //   to 0 and searches there rather than reporting no match, so '/' would\n  //   come back as its own parent and the walk would never end. It cannot\n  //   happen -- that is the only path short enough to produce one, and the\n  //   test above has already sent it the other way.\n  const cut = path.lastIndexOf(\n    SLASH,\n    path.charCodeAt(end) === SLASH_CODE\n      ? end - 1\n      : end\n  )\n\n  return cut < 0\n    ? EMPTY\n    : path.slice(0, cut + 1)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// Blank lines and comments are told by `createRule`, once the pattern is\n//   normalized.\nconst checkPattern = pattern => pattern\n  && isString(pattern)\n  && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n  constructor (\n    pattern,\n    mark,\n    body,\n    ignoreCase,\n    negative,\n    prefix\n  ) {\n    this.pattern = pattern\n    this.mark = mark\n    this.negative = negative\n\n    define(this, 'body', body)\n    define(this, 'ignoreCase', ignoreCase)\n    define(this, 'regexPrefix', prefix)\n  }\n\n  // Worked out on first use and kept behind an own property, the way `regex`\n  //   caches itself in `_regex`. Deciding it in the constructor instead would\n  //   add a fourth `defineProperty` to every rule ever built, which cost 4% of\n  //   every compile -- including the compiles of rules that are never matched\n  //   against anything.\n  get _basenameOnly () {\n    return define(this, '_basenameOnly', matchesBasename(this.body))\n  }\n\n  get regex () {\n    const key = UNDERSCORE + MODE_IGNORE\n\n    if (this[key]) {\n      return this[key]\n    }\n\n    return this._make(MODE_IGNORE, key)\n  }\n\n  get checkRegex () {\n    const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n    if (this[key]) {\n      return this[key]\n    }\n\n    return this._make(MODE_CHECK_IGNORE, key)\n  }\n\n  _make (mode, key) {\n    const str = pinWildcards(\n      mode === MODE_IGNORE\n        ? this.regexPrefix\n        .replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard)\n        .replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar)\n        : checkSourceOf(this.body, this.regexPrefix)\n    )\n\n    const regex = this.ignoreCase\n      ? new RegExp(str, 'i')\n      : new RegExp(str)\n\n    return define(this, key, regex)\n  }\n}\n\nconst isLineEnd = char => char === '\\r' || char === '\\n'\n\n// Drop a line terminator, which can remain when patterns are passed as an\n//   array, and then the trailing spaces. Git trims spaces only, and a space\n//   escaped by an odd run of backslashes stays, unescaped, as the last one.\n// Scanned from the end: a regular expression can only try each start in\n//   turn, which is quadratic over a long run of spaces or backslashes.\n// 'a  ' -> 'a';  'a\\ ' -> 'a ';  'a\\\\ ' -> 'a\\\\';  'a\\t' -> 'a\\t'\nconst trimEnd = body => {\n  let end = body.length\n\n  while (end && isLineEnd(body[end - 1])) {\n    end --\n  }\n\n  const lineEnd = end\n\n  while (end && body[end - 1] === SPACE) {\n    end --\n  }\n\n  if (end === lineEnd) {\n    return body.slice(0, end)\n  }\n\n  let backslashes = 0\n\n  while (backslashes < end && body[end - backslashes - 1] === ESCAPE) {\n    backslashes ++\n  }\n\n  return backslashes % 2\n    ? body.slice(0, end - 1) + SPACE\n    : body.slice(0, end)\n}\n\nconst createRule = ({\n  pattern,\n  mark\n}, ignoreCase) => {\n  // Git drops a BOM before it reads the first line, so before anything else.\n  let body = pattern[0] === BOM\n    ? pattern.slice(1)\n    : pattern\n\n  // > A line starting with # serves as a comment.\n  if (body[0] === '#') {\n    return\n  }\n\n  let negative = false\n\n  // > An optional prefix \"!\" which negates the pattern;\n  if (body[0] === '!') {\n    negative = true\n    body = body.slice(1)\n  }\n\n  // Normalize the body before checking which slashes anchor the pattern.\n  //   Otherwise `bar/ ` is mistaken for a pattern containing an inner slash.\n  //   Only a body ending in a space or a line terminator has anything to trim.\n  const last = body[body.length - 1]\n\n  if (last === SPACE || last === '\\r' || last === '\\n') {\n    body = trimEnd(body)\n  }\n\n  // > A blank line matches no files, so it can serve as a separator for\n  // >   readability.\n  // Nor does a lone \"!\", or anything else left empty here: an empty pattern\n  //   would compile to a regex matching every path.\n  if (!body) {\n    return\n  }\n\n  body = body\n  // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n  // >   begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n  .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n  // > Put a backslash (\"\\\") in front of the first hash for patterns that\n  // >   begin with a hash.\n  .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n  const regexPrefix = makeRegexPrefix(body)\n\n  return new IgnoreRule(\n    pattern,\n    mark,\n    body,\n    ignoreCase,\n    negative,\n    regexPrefix\n  )\n}\n\nclass RuleManager {\n  constructor (ignoreCase) {\n    this._ignoreCase = ignoreCase\n    this._rules = []\n\n    // How many of the rules git would tag `EXC_FLAG_NODIR`.\n    //\n    // The scan uses it to decide, once for the whole set, whether handing\n    //   those rules the basename is worth what it costs the others. The\n    //   shortcut saves a full-path scan on every rule it applies to and costs\n    //   a check on every rule it does not, so a set where almost nothing is\n    //   basename-only comes out behind -- a 955 pattern set with 44 of them\n    //   measured 19% slower with the shortcut always on.\n    //\n    // Deciding this by measurement rather than by meaning is safe: a\n    //   basename-only pattern gives the very same answer against the whole\n    //   path, it just takes longer to say so. The choice can only change how\n    //   fast the scan runs, never what it returns.\n    this._basenameCount = 0\n  }\n\n  _add (pattern) {\n    // #32\n    if (pattern && pattern[KEY_IGNORE]) {\n      this._rules = this._rules.concat(pattern._rules._rules)\n      this._basenameCount += pattern._rules._basenameCount\n      this._added = true\n      return\n    }\n\n    if (isString(pattern)) {\n      pattern = {\n        pattern\n      }\n    }\n\n    const rule = checkPattern(pattern.pattern)\n      && createRule(pattern, this._ignoreCase)\n\n    if (rule) {\n      this._added = true\n      this._rules.push(rule)\n\n      // Deliberately not `rule._basenameOnly`: reading that would materialise\n      //   the rule's own copy, and the whole point of leaving it lazy is that\n      //   a rule which is compiled and never matched never pays for it.\n      if (matchesBasename(rule.body)) {\n        this._basenameCount ++\n      }\n    }\n  }\n\n  // @param {Array<string> | string | Ignore} pattern\n  add (pattern) {\n    this._added = false\n\n    makeArray(\n      isString(pattern)\n        ? splitPattern(pattern)\n        : pattern\n    ).forEach(this._add, this)\n\n    if (this._added) {\n      this._literalRules = UNDEFINED\n    }\n\n    return this._added\n  }\n\n  // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule\n  //   ending in a wildcard can match it (see `checkSourceOf`), so the rest\n  //   are left out once, rather than tested or compiled for every path.\n  testLiteral (path) {\n    const rules = this._literalRules || (\n      this._literalRules = this._rules.filter(\n        ({body}) => body[body.length - (\n          body[body.length - 1] === SLASH ? 2 : 1\n        )] === '*'\n      )\n    )\n\n    let ignored = false\n    let unignored = false\n    let matchedRule\n\n    for (let index = rules.length - 1; index >= 0; index --) {\n      const rule = rules[index]\n\n      if (rule.checkRegex.test(path)) {\n        ignored = !rule.negative\n        unignored = rule.negative\n        matchedRule = rule.negative\n          ? UNDEFINED\n          : rule\n        break\n      }\n    }\n\n    const ret = {\n      ignored,\n      unignored\n    }\n\n    if (matchedRule) {\n      ret.rule = matchedRule\n    }\n\n    return ret\n  }\n\n  // Test one single path without recursively checking parent directories\n  //\n  // - checkUnignored `boolean` whether should check if the path is unignored,\n  //   setting `checkUnignored` to `false` could reduce additional\n  //   path matching.\n  // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n  // @returns {TestResult} true if a file is ignored\n  test (path, checkUnignored, mode) {\n    let ignored = false\n    let unignored = false\n    let matchedRule\n\n    // Most of a .gitignore is patterns with no slash in them, and running\n    //   those against the whole path makes the regular expression engine walk\n    //   every directory name on the way to the only segment that could match.\n    //   Handing them the basename instead is what git does, and it is where\n    //   the time in a directory walk goes: the rule scan was two thirds of it.\n    const rules = this._rules\n    const {length} = rules\n\n    const shortcut = this._basenameCount * 2 >= length\n\n    const basename = shortcut\n      ? basenameOf(path)\n      : path\n\n    // A plain loop rather than `forEach`, so that `path`, `basename` and\n    //   `shortcut` are locals. As a callback they became closure variables,\n    //   and reaching for one of those once per rule cost 10% of a scan over a\n    //   large rule set -- more than the shortcut they were there to serve.\n    for (let index = 0; index < length; index ++) {\n      const rule = rules[index]\n      const {negative} = rule\n\n      //          |           ignored : unignored\n      // -------- | ---------------------------------------\n      // negative |   0:0   |   0:1   |   1:0   |   1:1\n      // -------- | ------- | ------- | ------- | --------\n      //     0    |  TEST   |  TEST   |  SKIP   |    X\n      //     1    |  TESTIF |  SKIP   |  TEST   |    X\n\n      // - SKIP: always skip\n      // - TEST: always test\n      // - TESTIF: only test if checkUnignored\n      // - X: that never happen\n      const skip = unignored === negative && ignored !== unignored\n        || negative && !ignored && !unignored && !checkUnignored\n\n      if (!skip && rule[mode].test(\n        shortcut && rule._basenameOnly\n          ? basename\n          : path\n      )) {\n        ignored = !negative\n        unignored = negative\n\n        matchedRule = negative\n          ? UNDEFINED\n          : rule\n      }\n    }\n\n    const ret = {\n      ignored,\n      unignored\n    }\n\n    if (matchedRule) {\n      ret.rule = matchedRule\n    }\n\n    return ret\n  }\n}\n\nconst throwError = (message, Ctor) => {\n  throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n  if (!isString(path)) {\n    return doThrow(\n      `path must be a string, but got \\`${originalPath}\\``,\n      TypeError\n    )\n  }\n\n  // We don't know if we should ignore EMPTY, so throw\n  if (!path) {\n    return doThrow(`path must not be empty`, TypeError)\n  }\n\n  // Check if it is a relative path\n  if (checkPath.isNotRelative(path)) {\n    const r = '`path.relative()`d'\n    return doThrow(\n      `path should be a ${r} string, but got \"${originalPath}\"`,\n      RangeError\n    )\n  }\n\n  return true\n}\n\n// > pathname should be a `path.relative()`d one\n//\n// The same thing `REGEX_TEST_INVALID_PATH` says, spelled out: a path is not\n//   relative if it begins with a separator, or with `./` or `../`, or is\n//   nothing but `.` or `..`. Every match is decided by the first three\n//   characters, and this runs on every path handed to the library -- where it\n//   was 55% of a cached lookup, more than the cache lookup itself.\nconst isNotRelative = path => {\n  const first = path.charCodeAt(0)\n\n  if (first === SLASH_CODE) {\n    return true\n  }\n\n  if (first !== DOT_CODE) {\n    return false\n  }\n\n  // '.'\n  if (path.length === 1) {\n    return true\n  }\n\n  const second = path.charCodeAt(1)\n\n  // './'\n  if (second === SLASH_CODE) {\n    return true\n  }\n\n  if (second !== DOT_CODE) {\n    return false\n  }\n\n  // '..' or '../'\n  return path.length === 2 || path.charCodeAt(2) === SLASH_CODE\n}\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n  constructor ({\n    ignorecase = true,\n    ignoreCase = ignorecase,\n    allowRelativePaths = false\n  } = {}) {\n    define(this, KEY_IGNORE, true)\n\n    this._rules = new RuleManager(ignoreCase)\n    this._strictPathCheck = !allowRelativePaths\n    this._initCache()\n  }\n\n  _initCache () {\n    // A cache for the result of `.ignores()`\n    this._ignoreCache = Object.create(null)\n\n    // A cache for the result of `.test()`\n    this._testCache = Object.create(null)\n  }\n\n  add (pattern) {\n    if (this._rules.add(pattern)) {\n      // Some rules have just added to the ignore,\n      //   making the behavior changed,\n      //   so we need to re-initialize the result cache\n      this._initCache()\n    }\n\n    return this\n  }\n\n  // legacy\n  addPattern (pattern) {\n    return this.add(pattern)\n  }\n\n  // @returns {TestResult}\n  _test (originalPath, cache, checkUnignored) {\n    const path = originalPath\n      // Supports nullable path\n      && checkPath.convert(originalPath)\n\n    checkPath(\n      path,\n      originalPath,\n      this._strictPathCheck\n        ? throwError\n        : RETURN_FALSE\n    )\n\n    return this._t(path, cache, checkUnignored)\n  }\n\n  checkIgnore (path) {\n    // If the path doest not end with a slash, `.ignores()` is much equivalent\n    //   to `git check-ignore`\n    if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {\n      return this.test(path)\n    }\n\n    // Like `git check-ignore`: a directory excluded by itself or by an\n    //   ancestor settles it, and only then is the literal 'abc/' matched\n    //   against the rules (see `checkSourceOf`).\n    const dir = this._t(path, this._testCache, true)\n\n    if (dir.ignored) {\n      return dir\n    }\n\n    const literal = this._rules.testLiteral(path)\n\n    return literal.ignored || literal.unignored\n      ? literal\n      : dir\n  }\n\n  _t (\n    // The path to be tested\n    path,\n\n    // The cache for the result of a certain checking\n    cache,\n\n    // Whether should check if the path is unignored\n    checkUnignored\n  ) {\n    if (path in cache) {\n      return cache[path]\n    }\n\n    const parentPath = parentOf(path)\n\n    // If the path contains a parent directory, check the parent first\n    const parent = parentPath\n      ? this._t(parentPath, cache, checkUnignored)\n      : UNDEFINED\n\n    return cache[path] = parent && parent.ignored\n      // > It is not possible to re-include a file if a parent directory of\n      // >   that file is excluded.\n      ? parent\n      : this._rules.test(path, checkUnignored, MODE_IGNORE)\n  }\n\n  ignores (path) {\n    return this._test(path, this._ignoreCache, false).ignored\n  }\n\n  createFilter () {\n    return path => !this.ignores(path)\n  }\n\n  filter (paths) {\n    return makeArray(paths).filter(this.createFilter())\n  }\n\n  // @returns {TestResult}\n  test (path) {\n    return this._test(path, this._testCache, true)\n  }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n  checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n  /* eslint no-control-regex: \"off\" */\n  const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n  || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n    ? str\n    : str.replace(/\\\\/g, '/')\n\n  checkPath.convert = makePosix\n\n  // 'C:\\\\foo'     <- 'C:\\\\foo' has been converted to 'C:/'\n  // 'd:\\\\foo'\n  const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n  checkPath.isNotRelative = path =>\n    REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n    || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n  // Detect `process` so that it can run in browsers.\n  typeof process !== 'undefined'\n  && process.platform === 'win32'\n) {\n  setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n//   it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","import path from \"node:path\";\nimport { BACKGROUND_CONTEXT, withAbortSignal } from \"@earendil-works/chord/context\";\nimport { getOrThrow } from \"@earendil-works/pi-durable/env\";\nimport ignore from \"ignore\";\n//#region src/server/sessionFilesApi.ts\nconst EXCLUDED_DIRECTORIES = /* @__PURE__ */ new Set([\".git\", \"node_modules\"]);\nconst IGNORE_FILES = [\".gitignore\", \".poignore\"];\nconst FILE_QUERY_TIMEOUT_MS = 2e3;\nconst MAX_FILE_RESULTS = 50;\n/**\n* The project's ignore test, or nothing when it declares no rules.\n*\n* Only the session root's files are read. A nested .gitignore would need one\n* matcher per directory, and the cost of skipping it is a suggestion that\n* should not have been offered rather than a file that cannot be opened. An\n* unreadable or malformed file leaves completion listing everything, because\n* hiding the tree is the worse failure.\n*/\nasync function readIgnoreRules(fs, cwd, context) {\n\tconst rules = (await Promise.all(IGNORE_FILES.map(async (name) => {\n\t\ttry {\n\t\t\tconst result = await fs.readTextFile(path.join(cwd, name), context);\n\t\t\treturn result.ok ? result.value : \"\";\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t}))).join(\"\\n\");\n\tif (rules.trim().length === 0) return void 0;\n\ttry {\n\t\tconst matcher = ignore().add(rules);\n\t\treturn (relativePath) => matcher.ignores(relativePath);\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function listSessionFiles(fs, cwd, query, signal) {\n\tconst context = withAbortSignal(signal, BACKGROUND_CONTEXT);\n\tconst isIgnored = await readIgnoreRules(fs, cwd, context);\n\tconst deadline = Date.now() + FILE_QUERY_TIMEOUT_MS;\n\tconst pending = [\"\"];\n\tlet next = 0;\n\tconst matches = [];\n\tconst queryParts = query.split(/(\\/)/u);\n\tconst matchesQuery = (file) => {\n\t\tconst lower = file.toLowerCase();\n\t\tlet start = 0;\n\t\treturn queryParts.every((part) => {\n\t\t\tconst index = lower.indexOf(part, start);\n\t\t\tstart = index + part.length;\n\t\t\treturn index !== -1;\n\t\t});\n\t};\n\tconst compareMatches = (left, right) => Number(right.toLowerCase().includes(query)) - Number(left.toLowerCase().includes(query)) || left.localeCompare(right);\n\twhile (next < pending.length && matches.length < MAX_FILE_RESULTS) {\n\t\tif (signal.aborted) throw signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error(\"File completion was aborted.\");\n\t\tif (Date.now() > deadline && next > 0) break;\n\t\tconst relativeDirectory = pending[next++];\n\t\tif (relativeDirectory === void 0) break;\n\t\tif (relativeDirectory !== \"\" && matchesQuery(`${relativeDirectory}/`)) matches.push(`${relativeDirectory}/`);\n\t\tif (matches.length === MAX_FILE_RESULTS) break;\n\t\tconst entries = getOrThrow(await fs.listDir(path.join(cwd, relativeDirectory), context));\n\t\tconst matchingDirectories = [];\n\t\tfor (const entry of entries) {\n\t\t\tconst file = relativeDirectory === \"\" ? entry.name : `${relativeDirectory}/${entry.name}`;\n\t\t\tif (entry.kind === \"directory\") {\n\t\t\t\tif (EXCLUDED_DIRECTORIES.has(entry.name) || isIgnored?.(`${file}/`) === true) continue;\n\t\t\t\tif (query && matchesQuery(`${file}/`)) matchingDirectories.push(file);\n\t\t\t\telse pending.push(file);\n\t\t\t} else if (entry.kind === \"file\" && isIgnored?.(file) !== true && matchesQuery(file)) matches.push(file);\n\t\t\tif (matches.length === MAX_FILE_RESULTS) break;\n\t\t}\n\t\tpending.splice(next, 0, ...matchingDirectories.sort(compareMatches));\n\t}\n\treturn matches.sort(compareMatches).slice(0, MAX_FILE_RESULTS);\n}\n/** Bounded, read-only file completion rooted in the owning session, read through the server's platform fs. */\nfunction createSessionFilesApi({ fs }) {\n\treturn {\n\t\tbasePath: \"files\",\n\t\tstart(context) {\n\t\t\tif (context.scope !== \"session\" || !context.cwd) throw new Error(\"File completion requires a session.\");\n\t\t\tconst cwd = context.cwd;\n\t\t\tlet closed = false;\n\t\t\treturn {\n\t\t\t\tasync fetch(request) {\n\t\t\t\t\tif (closed) return new Response(null, { status: 503 });\n\t\t\t\t\tconst url = new URL(request.url);\n\t\t\t\t\tif (request.method !== \"GET\" || url.pathname !== \"/\") return new Response(null, { status: 404 });\n\t\t\t\t\tconst query = (url.searchParams.get(\"q\") ?? \"\").toLowerCase();\n\t\t\t\t\tif (query.length > 256) return Response.json({ error: \"File query is too long.\" }, { status: 400 });\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn Response.json({ files: await listSessionFiles(fs, cwd, query, request.signal) });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn Response.json({ error: \"File completion could not be read.\" }, { status: 503 });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclose() {\n\t\t\t\t\tclosed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\nexport { createSessionFilesApi };\n\n//# sourceMappingURL=sessionFilesApi.mjs.map","import { Type } from \"typebox\";\nimport { Check, Errors } from \"typebox/value\";\n//#region src/schemas/help.ts\n/** Provider-owned Cordis service for the live Help catalog. */\nconst PO_HELP_SERVICE = \"po/help\";\nconst PO_HELP_WHEN = {\n\tstate: { \"minor-mode\": \"help\" },\n\tattribution: {\n\t\tkind: \"minor\",\n\t\tmode: \"help\"\n\t}\n};\nconst PO_HELP_MAX_CONTRIBUTORS = 32;\nconst PO_HELP_MAX_SKILLS = 64;\nconst PO_HELP_MAX_DIAGNOSTICS = 64;\nconst PO_HELP_MAX_DESCRIPTION_LENGTH = 512;\nconst PO_HELP_MAX_DIAGNOSTIC_LENGTH = 512;\nconst MAX_SOURCE_LENGTH = 128;\nconst MAX_SKILL_NAME_LENGTH = 64;\nconst MAX_MODULE_URL_LENGTH = 4096;\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst PO_HELP_ERROR_CODE = {\n\tcontributorLimit: \"HELP_CONTRIBUTOR_LIMIT\",\n\tdisposed: \"HELP_DISPOSED\",\n\tduplicateSkill: \"HELP_DUPLICATE_SKILL\",\n\tinactiveSnapshot: \"HELP_INACTIVE_SNAPSHOT\",\n\tinvalidContribution: \"HELP_INVALID_CONTRIBUTION\",\n\tinvalidGeneration: \"HELP_INVALID_GENERATION\",\n\tinvalidSnapshot: \"HELP_INVALID_SNAPSHOT\"\n};\nvar PoHelpError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"PoHelpError\";\n\t\tthis.code = code;\n\t}\n};\nconst PoHelpSourceSchema = Type.String({\n\tminLength: 1,\n\tmaxLength: MAX_SOURCE_LENGTH,\n\tpattern: \"^[A-Za-z0-9@][A-Za-z0-9@/._:-]*$\"\n});\nconst PoHelpSkillNameSchema = Type.String({\n\tminLength: 1,\n\tmaxLength: MAX_SKILL_NAME_LENGTH,\n\tpattern: \"^[a-z0-9][a-z0-9-]*$\"\n});\nconst PoHelpSkillDescriptorSchema = Type.Object({\n\tname: PoHelpSkillNameSchema,\n\tdescription: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 512\n\t})\n}, { additionalProperties: false });\nconst PoHelpContributionSchema = Type.Object({\n\tsource: PoHelpSourceSchema,\n\tmoduleUrl: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: MAX_MODULE_URL_LENGTH\n\t}),\n\tskills: Type.Array(PoHelpSkillDescriptorSchema, {\n\t\tminItems: 1,\n\t\tmaxItems: 64\n\t})\n}, { additionalProperties: false });\nconst GenerationSchema = Type.String({\n\tminLength: 1,\n\tmaxLength: MAX_IDENTIFIER_LENGTH\n});\nconst PoHelpActivationSchema = Type.Union([\n\tType.Literal(\"inactive\"),\n\tType.Literal(\"activating\"),\n\tType.Literal(\"active\"),\n\tType.Literal(\"degraded\")\n]);\nconst PoHelpSkillSchema = Type.Object({\n\tsource: PoHelpSourceSchema,\n\tname: PoHelpSkillNameSchema,\n\tdescription: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 512\n\t}),\n\tfilePath: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: MAX_MODULE_URL_LENGTH\n\t}),\n\tbaseDir: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: MAX_MODULE_URL_LENGTH\n\t})\n}, { additionalProperties: false });\nconst PoHelpDiagnosticSchema = Type.Object({\n\tsource: Type.Optional(PoHelpSourceSchema),\n\tcode: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 64,\n\t\tpattern: \"^[A-Z0-9_]+$\"\n\t}),\n\tmessage: Type.String({\n\t\tminLength: 1,\n\t\tmaxLength: 512\n\t})\n}, { additionalProperties: false });\nconst PoHelpSnapshotSchema = Type.Object({\n\thostGeneration: GenerationSchema,\n\trevision: Type.Integer({ minimum: 0 }),\n\tactivation: PoHelpActivationSchema,\n\tskills: Type.Array(PoHelpSkillSchema, { maxItems: 64 }),\n\tdiagnostics: Type.Array(PoHelpDiagnosticSchema, { maxItems: 64 })\n}, { additionalProperties: false });\nfunction schemaFailure(schema, value) {\n\tconst [first] = Errors(schema, value);\n\treturn first ? ` at ${first.instancePath || \"/\"}: ${first.message}` : \"\";\n}\nfunction cloneContribution(contribution) {\n\treturn {\n\t\tsource: contribution.source,\n\t\tmoduleUrl: contribution.moduleUrl,\n\t\tskills: contribution.skills.map((skill) => ({ ...skill }))\n\t};\n}\nfunction cloneSnapshot(snapshot) {\n\treturn {\n\t\t...snapshot,\n\t\tskills: snapshot.skills.map((skill) => ({ ...skill })),\n\t\tdiagnostics: snapshot.diagnostics.map((diagnostic) => ({ ...diagnostic }))\n\t};\n}\nfunction validateContribution(contribution) {\n\tif (!Check(PoHelpContributionSchema, contribution)) throw new PoHelpError(PO_HELP_ERROR_CODE.invalidContribution, `Invalid Help contribution${schemaFailure(PoHelpContributionSchema, contribution)}.`);\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const skill of contribution.skills) {\n\t\tif (names.has(skill.name)) throw new PoHelpError(PO_HELP_ERROR_CODE.duplicateSkill, `Help contribution '${contribution.source}' declares duplicate skill '${skill.name}'.`);\n\t\tnames.add(skill.name);\n\t}\n\treturn cloneContribution(contribution);\n}\n/** Creates the provider-owned Help service value for one Cordis session. */\nfunction createPoHelpService(generation) {\n\tif (!Check(GenerationSchema, generation)) throw new PoHelpError(PO_HELP_ERROR_CODE.invalidGeneration, \"Po Help requires a valid generation.\");\n\tconst contributions = /* @__PURE__ */ new Map();\n\tconst contributionListeners = /* @__PURE__ */ new Set();\n\tconst snapshotListeners = /* @__PURE__ */ new Set();\n\tlet registrationSequence = 0;\n\tlet disposed = false;\n\tlet skillInventory;\n\tlet snapshot = {\n\t\thostGeneration: generation,\n\t\trevision: 0,\n\t\tactivation: \"inactive\",\n\t\tskills: [],\n\t\tdiagnostics: []\n\t};\n\tconst ensureActive = () => {\n\t\tif (disposed) throw new PoHelpError(PO_HELP_ERROR_CODE.disposed, \"The Po Help service is disposed.\");\n\t};\n\tconst list = () => [...contributions.values()].map(({ contribution }) => cloneContribution(contribution)).sort((left, right) => left.source.localeCompare(right.source));\n\tconst notifyContributions = () => {\n\t\tconst value = list();\n\t\tfor (const listener of contributionListeners) listener(value);\n\t};\n\treturn Object.freeze({\n\t\tgeneration,\n\t\tregister(contribution) {\n\t\t\tensureActive();\n\t\t\tconst validated = validateContribution(contribution);\n\t\t\tif (!contributions.has(validated.source) && contributions.size >= 32) throw new PoHelpError(PO_HELP_ERROR_CODE.contributorLimit, `Help accepts at most 32 contributors.`);\n\t\t\tregistrationSequence += 1;\n\t\t\tconst token = Symbol(validated.source);\n\t\t\tconst registrationGeneration = `${generation}:help:${registrationSequence}`;\n\t\t\tcontributions.set(validated.source, {\n\t\t\t\ttoken,\n\t\t\t\tgeneration: registrationGeneration,\n\t\t\t\tcontribution: validated\n\t\t\t});\n\t\t\tnotifyContributions();\n\t\t\tlet registrationDisposed = false;\n\t\t\treturn Object.freeze({\n\t\t\t\tsource: validated.source,\n\t\t\t\tgeneration: registrationGeneration,\n\t\t\t\tdispose() {\n\t\t\t\t\tif (registrationDisposed) return;\n\t\t\t\t\tregistrationDisposed = true;\n\t\t\t\t\tif (contributions.get(validated.source)?.token !== token) return;\n\t\t\t\t\tcontributions.delete(validated.source);\n\t\t\t\t\tnotifyContributions();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tlistContributions: list,\n\t\tsubscribeContributions(listener) {\n\t\t\tensureActive();\n\t\t\tcontributionListeners.add(listener);\n\t\t\treturn () => contributionListeners.delete(listener);\n\t\t},\n\t\tgetSnapshot: () => cloneSnapshot(snapshot),\n\t\tpublish(draft) {\n\t\t\tensureActive();\n\t\t\tif (draft.activation === \"inactive\" && draft.skills.length > 0) throw new PoHelpError(PO_HELP_ERROR_CODE.inactiveSnapshot, \"Inactive Help snapshots cannot expose skills.\");\n\t\t\tconst next = {\n\t\t\t\thostGeneration: generation,\n\t\t\t\trevision: snapshot.revision + 1,\n\t\t\t\tactivation: draft.activation,\n\t\t\t\tskills: draft.skills.map((skill) => ({ ...skill })),\n\t\t\t\tdiagnostics: draft.diagnostics.map((diagnostic) => ({ ...diagnostic }))\n\t\t\t};\n\t\t\tif (!Check(PoHelpSnapshotSchema, next)) throw new PoHelpError(PO_HELP_ERROR_CODE.invalidSnapshot, `Invalid Help snapshot${schemaFailure(PoHelpSnapshotSchema, next)}.`);\n\t\t\tsnapshot = next;\n\t\t\tconst published = cloneSnapshot(snapshot);\n\t\t\tfor (const listener of snapshotListeners) listener(cloneSnapshot(published));\n\t\t\treturn published;\n\t\t},\n\t\tsubscribeSnapshot(listener) {\n\t\t\tensureActive();\n\t\t\tsnapshotListeners.add(listener);\n\t\t\treturn () => snapshotListeners.delete(listener);\n\t\t},\n\t\tbindSkillInventory(read) {\n\t\t\tensureActive();\n\t\t\tconst token = Symbol(\"help-skill-inventory\");\n\t\t\tskillInventory = {\n\t\t\t\ttoken,\n\t\t\t\tread\n\t\t\t};\n\t\t\treturn () => {\n\t\t\t\tif (skillInventory?.token === token) skillInventory = void 0;\n\t\t\t};\n\t\t},\n\t\tasync inspectSkills() {\n\t\t\tif (disposed) return void 0;\n\t\t\tif (snapshot.activation === \"inactive\") return [];\n\t\t\tconst reader = skillInventory;\n\t\t\tif (!reader) return void 0;\n\t\t\tconst revision = snapshot.revision;\n\t\t\tconst paths = await reader.read();\n\t\t\tif (disposed || reader !== skillInventory || revision !== snapshot.revision || paths === void 0) return void 0;\n\t\t\tconst accepted = new Set(paths);\n\t\t\treturn snapshot.skills.filter((skill) => accepted.has(skill.filePath)).map((skill) => ({ ...skill }));\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tskillInventory = void 0;\n\t\t\tcontributions.clear();\n\t\t\tcontributionListeners.clear();\n\t\t\tsnapshotListeners.clear();\n\t\t}\n\t});\n}\nfunction readPoHelpService(context) {\n\treturn context.get(PO_HELP_SERVICE);\n}\nfunction requirePoHelpService(context) {\n\tconst service = readPoHelpService(context);\n\tif (!service) throw new Error(\"Po Help is unavailable. Load @agimon-ai/po-help.\");\n\treturn service;\n}\n//#endregion\nexport { PO_HELP_ERROR_CODE, PO_HELP_MAX_CONTRIBUTORS, PO_HELP_MAX_DESCRIPTION_LENGTH, PO_HELP_MAX_DIAGNOSTICS, PO_HELP_MAX_DIAGNOSTIC_LENGTH, PO_HELP_MAX_SKILLS, PO_HELP_SERVICE, PO_HELP_WHEN, PoHelpActivationSchema, PoHelpContributionSchema, PoHelpDiagnosticSchema, PoHelpError, PoHelpSkillDescriptorSchema, PoHelpSkillNameSchema, PoHelpSkillSchema, PoHelpSnapshotSchema, PoHelpSourceSchema, createPoHelpService, readPoHelpService, requirePoHelpService };\n\n//# sourceMappingURL=help.mjs.map","/**\n * Step-by-step progress for `po sync`.\n *\n * Sync spends almost all of its wall clock in three places a user cannot see:\n * the registry check, the mode build, and the runtime precompile. A terminal\n * gets a live line that the finished step overwrites, so the transcript stays\n * as short as the existing summary. Anything else (a pipe, CI, the embedded\n * po runner) gets one line per completed step and no escape sequences.\n */\n\nconst LABEL_WIDTH = 10;\nconst ANSI_ESCAPE = String.fromCharCode(0x1b);\nconst CLEAR_LINE = `${ANSI_ESCAPE}[2K\\r`;\nconst MILLISECONDS_PER_SECOND = 1000;\n\nexport interface SyncProgressOutput {\n  write: NodeJS.WritableStream['write'];\n  isTTY?: boolean;\n}\n\n/** Closes the step a `start` call opened, recording how long it took. */\nexport type SyncStepDone = (summary: string) => void;\n\nexport function formatProgressLine(label: string, message: string): string {\n  return `${`${label}:`.padEnd(LABEL_WIDTH)}${message}`;\n}\n\nfunction formatElapsed(milliseconds: number): string {\n  return `${(milliseconds / MILLISECONDS_PER_SECOND).toFixed(1)}s`;\n}\n\n/** Reports sync phases as they run rather than only after everything is done. */\nexport class SyncProgress {\n  private readonly output: SyncProgressOutput;\n  private readonly now: () => number;\n  private live = false;\n\n  constructor(output: SyncProgressOutput, now: () => number = Date.now) {\n    this.output = output;\n    this.now = now;\n  }\n\n  /** Opens a timed step and returns the call that closes it. */\n  start(label: string, message: string): SyncStepDone {\n    const startedAt = this.now();\n    this.drawLive(formatProgressLine(label, `${message}...`));\n    return (summary) => {\n      this.clearLive();\n      this.output.write(`${formatProgressLine(label, `${summary} (${formatElapsed(this.now() - startedAt)})`)}\\n`);\n    };\n  }\n\n  /** Writes a standalone line, such as one package moving to a new version. */\n  line(label: string, message: string): void {\n    this.clearLive();\n    this.output.write(`${formatProgressLine(label, message)}\\n`);\n  }\n\n  private drawLive(text: string): void {\n    if (!this.output.isTTY) return;\n    this.output.write(`${CLEAR_LINE}${text}`);\n    this.live = true;\n  }\n\n  private clearLive(): void {\n    if (!this.live) return;\n    this.output.write(CLEAR_LINE);\n    this.live = false;\n  }\n}\n","import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { globalPoConfigDirectory } from '@agimon-ai/po-config/config';\nimport { loadMajorModesConfigLenient } from '@agimon-ai/po-config/majorModes';\nimport type { ConfigDiagnostic } from '@agimon-ai/po-config/types';\n\nimport { createLayerResolvers } from '../../../builders/cli/extensionAssembler';\nimport { readGlobalNativeBuildStatus } from '../../../builders/native';\nimport { syncParentPid } from '../../../builders/server/backgroundSync';\nimport { readGlobalWebBuildStatus } from '../../../builders/web';\nimport { HARNESS_STATE_POINTER } from '../../../composition/harnessState';\nimport { missingLayerPackageSpecifiers } from '../../../composition/layerPackageInstaller';\nimport { loadPoConfigLenient } from '../../../composition/projectTrust';\nimport { resolvePoConfigurationRoot } from '../../../composition/repository';\nimport {\n  formatSyncResult,\n  globalWebPluginRoots,\n  runSync as runSyncService,\n  type SyncDeps,\n  type SyncEvent,\n  syncExitCode,\n} from '../../../composition/syncService';\nimport { PO_DOMAINS_ENV, PO_MAJOR_MODE_ENV, PO_PROFILE_ENV } from '../../matrixOptions';\nimport { SyncProgress, type SyncProgressOutput, type SyncStepDone } from './presenter';\n\n/**\n * `po sync`: install what every root's configuration names and ensure the global builds.\n *\n * The roots are the Po home, every registered workspace and the current repository, which\n * sync registers unless `--global` is given. The server composes every session live from\n * configuration and installed packages, so sync only makes sure the packages are there\n * and the one global web build (and the MCP app build) for the current plugin set exists.\n * Then, when no other Po host runs, it prunes old builds and the package store.\n */\n\nconst SYNC_COMMAND = 'sync';\nconst CHECK_OPTION = '--check';\nconst GLOBAL_OPTION = '--global';\nconst JSON_OPTION = '--json';\nconst SKIP_ARTIFACT_BUILDS_OPTION = '--skip-artifact-builds';\nconst SYNC_OPTIONS = new Set([CHECK_OPTION, GLOBAL_OPTION, JSON_OPTION, SKIP_ARTIFACT_BUILDS_OPTION]);\nconst HARNESS_ROOT_ENV = 'PO_ROOT';\nconst PRIVATE_DIRECTORY_MODE = 0o700;\nconst APP_LABEL = 'app';\n/** The po-native over-the-air exporter below a Po source checkout. */\nconst APP_BUNDLE_EXPORTER = path.join('packages', 'clients', 'po-native', 'scripts', 'exportAppBundle.mjs');\n/** Metro prints progress for every module batch; the default 1 MB would cut a long export short. */\nconst APP_EXPORT_OUTPUT_BYTES = 64 * 1024 * 1024;\n\nexport interface SyncRoots {\n  globalOnly: boolean;\n  globalRoot: string;\n  sourceRoot: string;\n  targetRoot: string;\n}\n\n/** Resolves the configuration source and the root whose packages are installed. */\nexport function resolveSyncRoots(\n  args: readonly string[],\n  environment: NodeJS.ProcessEnv = process.env,\n  currentDirectory = process.cwd(),\n  homeDirectory = environment.HOME ?? os.homedir(),\n): SyncRoots {\n  const globalRoot = globalPoConfigDirectory(homeDirectory);\n  const inheritedRoot = environment[HARNESS_ROOT_ENV];\n  const sourceRoot = inheritedRoot\n    ? path.resolve(inheritedRoot)\n    : resolvePoConfigurationRoot(currentDirectory, homeDirectory);\n  const globalOnly = args.includes(GLOBAL_OPTION);\n  return { globalOnly, globalRoot, sourceRoot, targetRoot: globalOnly ? globalRoot : sourceRoot };\n}\n\nconst GLOBAL_SCOPE_INHERITED_KEYS = [\n  HARNESS_ROOT_ENV,\n  HARNESS_STATE_POINTER,\n  PO_MAJOR_MODE_ENV,\n  PO_DOMAINS_ENV,\n  PO_PROFILE_ENV,\n] as const;\n\n/** Removes workspace-only state before a global root is resolved. */\nexport function environmentForSyncScope(environment: NodeJS.ProcessEnv, globalOnly: boolean): NodeJS.ProcessEnv {\n  if (!globalOnly) return environment;\n  const scoped = { ...environment };\n  for (const key of GLOBAL_SCOPE_INHERITED_KEYS) delete scoped[key];\n  return scoped;\n}\n\ntype SyncOutput = SyncProgressOutput;\n\nexport interface SyncCommandOptions {\n  /** Test/embedding override; normal CLI execution uses the process home. */\n  homeDirectory?: string;\n  /** Test seams for the install, build and bundle steps and the lock. */\n  deps?: Partial<SyncDeps>;\n}\n\n/**\n * Reports the config keys sync chose to ignore.\n *\n * Never fatal. A key nobody recognises is usually a config written for another\n * version of a layer, and refusing to build over it is worse than proceeding\n * without it. The strict check lives in `po doctor`.\n */\nfunction writeConfigDiagnostics(diagnostics: readonly ConfigDiagnostic[], output: SyncOutput): void {\n  if (diagnostics.length === 0) return;\n  const lines = diagnostics.map((entry) => `  ${entry.filePath}: ${entry.path}`).join('\\n');\n  output.write(\n    `config:   ignored ${String(diagnostics.length)} unsupported key(s); run po doctor for the strict check\\n${lines}\\n`,\n  );\n}\n\n/** Renders service events through the step presenter, as text for a terminal or a pipe. */\nfunction textRenderer(output: SyncOutput): (event: SyncEvent) => void {\n  const progress = new SyncProgress(output);\n  const open = new Map<string, SyncStepDone>();\n  return (event) => {\n    if (event.type === 'start') open.set(event.label, progress.start(event.label, event.message));\n    else if (event.type === 'done') {\n      open.get(event.label)?.(event.summary);\n      open.delete(event.label);\n    } else if (event.type === 'line') progress.line(event.label, event.message);\n    else output.write(formatSyncResult(event.result));\n  };\n}\n\nfunction jsonLine(output: SyncOutput, value: unknown): void {\n  output.write(`${JSON.stringify(value)}\\n`);\n}\n\n/**\n * Exports the phone app bundle the host offers paired phones, when sync runs from a Po source\n * checkout. Only a person's sync runs it: Metro takes most of a minute. A failure is reported and\n * leaves the sync's result alone, because plugins and builds are already in place.\n */\nfunction exportAppBundle(\n  sourceRoot: string,\n  globalRoot: string,\n  environment: NodeJS.ProcessEnv,\n  emit: (event: SyncEvent) => void,\n): void {\n  const exporter = path.join(sourceRoot, APP_BUNDLE_EXPORTER);\n  if (!fs.existsSync(exporter)) return;\n  emit({ type: 'start', label: APP_LABEL, message: 'exporting the phone app bundle' });\n  const result = spawnSync(process.execPath, [exporter, globalRoot], {\n    cwd: sourceRoot,\n    env: environment,\n    encoding: 'utf8',\n    maxBuffer: APP_EXPORT_OUTPUT_BYTES,\n  });\n  const lines = (text: string | null | undefined) => (text ?? '').split('\\n').filter((line) => line.trim() !== '');\n  const summary =\n    result.status === 0\n      ? lines(result.stdout)\n          .filter((line) => line.startsWith('app '))\n          .join('; ')\n      : `failed: ${lines(result.stderr).slice(-3).join(' ') || result.error?.message || `exit ${String(result.status)}`}`;\n  emit({ type: 'done', label: APP_LABEL, summary });\n}\n\n/**\n * What `--check` and `po doctor` report.\n *\n * Problems are missing packages, in this root and in the global configuration every session\n * also loads, and a missing global web or native build. Warnings are roots the web build leaves out\n * (another admitted workspace whose configuration cannot be composed): worth saying, but\n * not something this sync can fix, so they never make the check fail.\n */\nexport function syncReadiness(\n  targetRoot: string,\n  homeDirectory: string,\n  environment: NodeJS.ProcessEnv,\n): { packages: string[]; web: string[]; native: string[]; warnings: string[] } {\n  const missingIn = (root: string): string[] => {\n    const config = loadMajorModesConfigLenient(root, homeDirectory, environment).config;\n    return missingLayerPackageSpecifiers(config, Object.keys(config.layers), createLayerResolvers(root, environment));\n  };\n  const globalRoot = globalPoConfigDirectory(homeDirectory);\n  const packages = [\n    ...missingIn(targetRoot).map((specifier) => `configured package is not installed: ${specifier}`),\n    ...(path.resolve(targetRoot) === path.resolve(globalRoot)\n      ? []\n      : missingIn(globalRoot).map(\n          (specifier) => `global package is not installed: ${specifier} (run po sync --global)`,\n        )),\n  ];\n  // Plugin roots resolve from installed packages, so the build key means nothing until they are.\n  if (packages.length > 0) return { packages, web: [], native: [], warnings: [] };\n  const warnings: string[] = [];\n  const pluginRoots = globalWebPluginRoots(targetRoot, homeDirectory, environment, (message) => warnings.push(message));\n  const status = readGlobalWebBuildStatus({ poHome: globalRoot, pluginRoots, environment });\n  const web =\n    status.status === 'missing'\n      ? [`global web build ${status.key} is missing`]\n      : status.status === 'failed'\n        ? [`global web build cannot be resolved: ${status.reason}`]\n        : [];\n  const nativeStatus = readGlobalNativeBuildStatus({ poHome: globalRoot, pluginRoots });\n  const native =\n    nativeStatus.status === 'missing'\n      ? [`global native build ${nativeStatus.key} is missing`]\n      : nativeStatus.status === 'failed'\n        ? [`global native build cannot be resolved: ${nativeStatus.reason}`]\n        : [];\n  return { packages, web, native, warnings };\n}\n\n/**\n * Installs every root's configured packages, then ensures the global web build and the MCP app build.\n *\n * Exit codes: 0 when the sync is ok or had nothing to do, 1 when it failed or only partly\n * succeeded, 75 when another sync holds the lock. With `--json`, each progress event is one\n * JSON line and the final line is the `SyncReport`.\n */\nexport async function synchronize(\n  args: string[],\n  environment: NodeJS.ProcessEnv = process.env,\n  currentDirectory = process.cwd(),\n  output: SyncOutput = process.stdout,\n  commandOptions: SyncCommandOptions = {},\n): Promise<number> {\n  const unknown = args.slice(1).filter((argument) => !SYNC_OPTIONS.has(argument));\n  if (unknown.length > 0) throw new Error(`Unknown po sync option(s): ${unknown.join(' ')}`);\n  const check = args.includes(CHECK_OPTION);\n  const json = args.includes(JSON_OPTION);\n  const skipArtifactBuilds = args.includes(SKIP_ARTIFACT_BUILDS_OPTION);\n  const homeDirectory = commandOptions.homeDirectory ?? environment.HOME ?? os.homedir();\n  const { globalOnly, globalRoot, sourceRoot, targetRoot } = resolveSyncRoots(\n    args,\n    environment,\n    currentDirectory,\n    homeDirectory,\n  );\n  const scopedEnvironment = environmentForSyncScope(environment, globalOnly);\n  if (globalOnly && !check) fs.mkdirSync(globalRoot, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });\n  // Sync tolerates keys it does not recognise so a config written against a\n  // different version cannot break a build. `po doctor` reports them.\n  const modes = loadMajorModesConfigLenient(sourceRoot, homeDirectory, scopedEnvironment);\n  const diagnostics = [...loadPoConfigLenient(sourceRoot, homeDirectory).diagnostics, ...modes.diagnostics];\n  if (json && diagnostics.length > 0) jsonLine(output, { type: 'config', diagnostics });\n  else if (!json) writeConfigDiagnostics(diagnostics, output);\n\n  if (check) {\n    const readiness = syncReadiness(targetRoot, homeDirectory, scopedEnvironment);\n    for (const warning of readiness.warnings) output.write(`warning:  ${warning}\\n`);\n    const problems = [...readiness.packages, ...readiness.web, ...readiness.native];\n    if (problems.length === 0) {\n      output.write('po sync is up to date\\n');\n      return 0;\n    }\n    output.write(`po sync is out of date:\\n${problems.map((entry) => `  ${entry}`).join('\\n')}\\n`);\n    return 1;\n  }\n\n  const origin = syncParentPid(environment) === undefined ? 'cli' : 'background';\n  const onEvent = json ? (event: SyncEvent) => jsonLine(output, event) : textRenderer(output);\n  const report = await runSyncService(\n    {\n      homeDirectory,\n      environment: scopedEnvironment,\n      globalRoot,\n      // --global covers every root but registers no repository.\n      ...(globalOnly ? {} : { repoRoot: sourceRoot }),\n      // A host's background job leaves a rerun marker when the lock is held instead of failing.\n      origin,\n      onEvent,\n      ...(skipArtifactBuilds ? { skipArtifactBuilds: true } : {}),\n    },\n    commandOptions.deps,\n  );\n  // The phone app bundle is an artifact build too.\n  if (!globalOnly && !skipArtifactBuilds && origin === 'cli' && report.status !== 'failed' && report.status !== 'busy')\n    exportAppBundle(sourceRoot, globalRoot, environment, onEvent);\n  if (json) jsonLine(output, { type: 'report', report });\n  else for (const error of report.errors) output.write(`error:    ${error}\\n`);\n  return syncExitCode(report.status);\n}\n\n/** Compatibility API. Executables call the command function directly. */\nexport class SyncCommand {\n  readonly name = SYNC_COMMAND;\n  private readonly homeDirectory: string | undefined;\n\n  constructor(options: SyncCommandOptions = {}) {\n    this.homeDirectory = options.homeDirectory;\n  }\n\n  matches(args: string[]): boolean {\n    return args[0] === this.name;\n  }\n\n  async execute(\n    args: string[],\n    environment: NodeJS.ProcessEnv = process.env,\n    currentDirectory = process.cwd(),\n    output: SyncOutput = process.stdout,\n  ): Promise<number> {\n    return synchronize(args, environment, currentDirectory, output, { homeDirectory: this.homeDirectory });\n  }\n}\n","import os from 'node:os';\nimport path from 'node:path';\n\nimport { loadPoConfig } from '@agimon-ai/po-config/config';\nimport { loadDomains } from '@agimon-ai/po-config/domains';\nimport { loadMajorModesConfig } from '@agimon-ai/po-config/majorModes';\nimport { loadProfiles } from '@agimon-ai/po-config/profiles';\n\nimport { resolvePoConfigurationRoot } from '../../../composition/repository';\nimport { wantsHelp } from '../../router';\nimport { syncReadiness } from '../sync';\nimport { doctorHelp } from './help';\n\nconst DOCTOR_COMMAND = 'doctor';\nconst HARNESS_ROOT_ENV = 'PO_ROOT';\nconst LABEL_WIDTH = 14;\n\nexport interface DoctorOutput {\n  write(chunk: string): void;\n}\n\n/** One checked area and what it found. Empty problems means the section passed. */\ninterface Section {\n  label: string;\n  problems: string[];\n}\n\nfunction formatSection(section: Section): string {\n  const label = section.label.padEnd(LABEL_WIDTH);\n  if (section.problems.length === 0) return `${label}ok\\n`;\n  return `${label}${section.problems.length === 1 ? 'FAILED' : `${String(section.problems.length)} problem(s)`}\\n${section.problems\n    .map((problem) => `  ${problem}\\n`)\n    .join('')}`;\n}\n\nfunction messageOf(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\n/** Runs one check, turning the throw a strict parser uses into a reported problem. */\nfunction check(run: () => void): string[] {\n  try {\n    run();\n    return [];\n  } catch (error) {\n    return [messageOf(error)];\n  }\n}\n\n/**\n * Reports what is wrong with a Po installation without changing anything.\n *\n * The strict counterpart to `po sync`, which tolerates unknown config keys\n * so a build cannot break over one. Everything `sync --check` reports is\n * reported here too, so this is the one command to run when something is off.\n */\nexport function runDoctor(\n  args: string[],\n  environment: NodeJS.ProcessEnv = process.env,\n  currentDirectory = process.cwd(),\n  output: DoctorOutput = process.stdout,\n): number {\n  if (wantsHelp(args.slice(1))) {\n    output.write(doctorHelp());\n    return 0;\n  }\n  const { sections, problems } = collectDoctorReport(environment, currentDirectory);\n  for (const section of sections) output.write(formatSection(section));\n  if (problems === 0) {\n    output.write('\\nno problems found\\n');\n    return 0;\n  }\n  output.write(`\\n${String(problems)} problem(s) found\\n`);\n  return 1;\n}\n\n/** The CLI and session diagnostic tool run the same read-only checks. */\nexport function collectDoctorReport(environment: NodeJS.ProcessEnv, currentDirectory: string) {\n  const homeDirectory = environment.HOME ?? os.homedir();\n  const inheritedRoot = environment[HARNESS_ROOT_ENV];\n  const repoRoot = inheritedRoot\n    ? path.resolve(inheritedRoot)\n    : resolvePoConfigurationRoot(currentDirectory, homeDirectory);\n  const sections: Section[] = [\n    { label: 'config.yaml', problems: check(() => loadPoConfig(repoRoot, homeDirectory)) },\n    { label: 'modes.yaml', problems: check(() => loadMajorModesConfig(repoRoot, homeDirectory)) },\n    { label: 'domains.yaml', problems: check(() => loadDomains(repoRoot, homeDirectory)) },\n    { label: 'profiles.yaml', problems: check(() => loadProfiles(repoRoot, homeDirectory)) },\n  ];\n  const skipped = sections.some((section) => section.problems.length > 0) ? ['packages', 'web build'] : [];\n  if (skipped.length === 0) {\n    try {\n      const readiness = syncReadiness(repoRoot, homeDirectory, environment);\n      sections.push(\n        { label: 'packages', problems: readiness.packages },\n        { label: 'web build', problems: readiness.web },\n      );\n    } catch (error) {\n      sections.push({ label: 'installation', problems: [messageOf(error)] });\n    }\n  }\n  return {\n    repoRoot,\n    homeDirectory,\n    sections,\n    skipped,\n    problems: sections.reduce((total, section) => total + section.problems.length, 0),\n  };\n}\n/** Compatibility API. Executables call the command function directly. */\nexport class DoctorCommand {\n  readonly name = DOCTOR_COMMAND;\n\n  matches(args: string[]): boolean {\n    return args[0] === this.name;\n  }\n\n  execute(\n    args: string[],\n    environment: NodeJS.ProcessEnv = process.env,\n    currentDirectory = process.cwd(),\n    output: DoctorOutput = process.stdout,\n  ): number {\n    return runDoctor(args, environment, currentDirectory, output);\n  }\n}\n","import { projectHarnessEnvironment } from '@agimon-ai/po-config/harnessState';\nimport type { PoHeadlessSelection } from '@agimon-ai/po-core/headless';\nimport { PO_HELP_WHEN as HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { defineTool } from '@agimon-ai/po-core/serverPlugin';\nimport { Type } from 'typebox';\n\nimport { collectDoctorReport } from '../cli/commands/doctor';\n\nexport const DIAGNOSE_SETUP_NAME = 'diagnose_setup';\nexport interface SetupDiagnosticScope {\n  repoRoot: string;\n  cwd: string;\n  environment: Readonly<Record<string, string | undefined>>;\n  selection: Pick<PoHeadlessSelection, 'majorMode' | 'domains' | 'profile'>;\n}\n\nconst guidance: Readonly<Record<string, string>> = {\n  'config.yaml': 'help-how-to-config',\n  'modes.yaml': 'help-how-to-major-mode',\n  'domains.yaml': 'help-how-to-domain',\n  'profiles.yaml': 'help-how-to-profile',\n};\n\nexport function createSetupDiagnosticsTool(\n  readScope: () => SetupDiagnosticScope,\n  authorize: (signal?: AbortSignal) => AbortSignal,\n) {\n  return defineTool({\n    name: DIAGNOSE_SETUP_NAME,\n    description:\n      \"Check this session's saved configuration, installed packages, and the global web build without changing anything. Returns scoped check results and the relevant setup guidance, never configuration values or credentials.\",\n    parameters: Type.Object({}, { additionalProperties: false }),\n    when: HELP_WHEN,\n    executionMode: 'serial',\n    async execute(_input, execution) {\n      const signal = authorize(execution.signal);\n      const scope = readScope();\n      const environment = projectHarnessEnvironment(\n        {\n          root: scope.repoRoot,\n          majorMode: scope.selection.majorMode,\n          domains: [...scope.selection.domains],\n          profile: scope.selection.profile,\n        },\n        { ...scope.environment },\n      );\n      const report = collectDoctorReport(environment, scope.cwd);\n      signal.throwIfAborted();\n      authorize(execution.signal);\n      const result = {\n        scope: 'current-session',\n        configurationRoot: report.repoRoot,\n        appliedSelection: {\n          majorMode: scope.selection.majorMode,\n          domains: [...scope.selection.domains],\n          profile: scope.selection.profile,\n        },\n        status: report.problems === 0 && report.skipped.length === 0 ? 'checks-passed' : 'issues-found',\n        checks: report.sections.map((section) => ({\n          area: section.label,\n          status: section.problems.length ? 'failed' : 'passed',\n          problemCount: section.problems.length,\n          guidance: guidance[section.label] ?? 'help-how-to-help',\n        })),\n        skipped: report.skipped,\n        limitations:\n          'These are saved configuration and installation checks, not a network authentication or agent health test. Error text and configuration values are omitted to protect credentials. Inspect a failed area with its package guidance before proposing a repair.',\n      };\n      return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], details: result };\n    },\n  });\n}\n","import type { PoHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport { createMachineApi } from '@agimon-ai/po-core/machineApi';\nimport { requirePoFs } from '@agimon-ai/po-core/platform';\nimport { remoteApi } from '@agimon-ai/po-core/remoteApi';\nimport { api } from '@agimon-ai/po-core/runtimeContextApi';\nimport { defineServerPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { createSessionFilesApi } from '@agimon-ai/po-core/sessionFilesApi';\n\nimport { createSetupDiagnosticsTool } from './setupDiagnostics';\n\nexport const poServerPlugin = defineServerPlugin({\n  name: '@agimon-ai/po',\n  global: ({ context, host }) => {\n    const machineApi = createMachineApi({ fs: requirePoFs(context) });\n    return { api: host.context.remoteControl ? [machineApi, remoteApi] : [machineApi] };\n  },\n  session: ({ context, agent, signal: ownerSignal }) => ({\n    api: [api, createSessionFilesApi({ fs: requirePoFs(context) })],\n    commands: [\n      {\n        name: 'fast',\n        description: 'Opt this session into Codex priority service (may increase cost)',\n        async execute(args: string, context: PoHeadlessExecutionContext) {\n          const value = args.trim().toLowerCase();\n          if (value !== 'on' && value !== 'off') throw new Error('Usage: /fast on|off');\n          if (!context.session.setFastMode) throw new Error('Fast mode is unavailable in this session');\n          await context.session.setFastMode(value === 'on');\n        },\n      },\n    ],\n    tools: agent\n      ? [\n          createSetupDiagnosticsTool(\n            () => agent.context,\n            (signal) => {\n              ownerSignal.throwIfAborted();\n              agent.assertActive('@agimon-ai/po');\n              if (!(agent.context.selection.state?.['minor-mode'] ?? []).includes('help'))\n                throw new Error('Help mode is not active.');\n              return signal ? AbortSignal.any([signal, ownerSignal]) : ownerSignal;\n            },\n          ),\n        ]\n      : [],\n  }),\n});\n\nexport default poServerPlugin;\n"],"ignoreList":[7],"mappings":";;;;;;;;;;;;;AAEA,SAAS,WAAW,MAAM;CACzB,OAAO;EACN,GAAG;EACH,MAAM;CACP;AACD;;;;ACLA,eAAe,YAAY,OAAO,SAAS;CAC1C,MAAM,SAAS,CAAC;C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