zidane 9.1.3 → 9.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-CeCavNlg.js → acp-Cl4gCZN6.js} +3 -3
- package/dist/{acp-CeCavNlg.js.map → acp-Cl4gCZN6.js.map} +1 -1
- package/dist/acp-cli.js +4 -4
- package/dist/acp.js +1 -1
- package/dist/{auth-store-port-BKpjlJ8a.js → auth-store-port-DBl2JUC6.js} +2 -2
- package/dist/{auth-store-port-BKpjlJ8a.js.map → auth-store-port-DBl2JUC6.js.map} +1 -1
- package/dist/{auto-update-restart-CQJtndMG.js → auto-update-restart-CF_kjcJd.js} +10 -10
- package/dist/{auto-update-restart-CQJtndMG.js.map → auto-update-restart-CF_kjcJd.js.map} +1 -1
- package/dist/chat.js +9 -9
- package/dist/{cli-shared-DeRHgYvl.js → cli-shared-DIV9c5Nr.js} +3 -3
- package/dist/{cli-shared-DeRHgYvl.js.map → cli-shared-DIV9c5Nr.js.map} +1 -1
- package/dist/{credentials-Bqg-qNBM.js → credentials-D71duF64.js} +2 -2
- package/dist/{credentials-Bqg-qNBM.js.map → credentials-D71duF64.js.map} +1 -1
- package/dist/daemon-cli.js +2 -2
- package/dist/{discovery-CX7nbMCn.js → discovery-DD4wPWKS.js} +4 -4
- package/dist/{discovery-CX7nbMCn.js.map → discovery-DD4wPWKS.js.map} +1 -1
- package/dist/{engine-CxBGgU94.js → engine-BDmtgr2O.js} +3 -3
- package/dist/{engine-CxBGgU94.js.map → engine-BDmtgr2O.js.map} +1 -1
- package/dist/{executor-j_LFRBwS.js → executor-EWOhLyd9.js} +2 -2
- package/dist/{executor-j_LFRBwS.js.map → executor-EWOhLyd9.js.map} +1 -1
- package/dist/extensions/testing.js +2 -2
- package/dist/{extensions-ADlhBQ_1.js → extensions-DklXPjiq.js} +6 -6
- package/dist/{extensions-ADlhBQ_1.js.map → extensions-DklXPjiq.js.map} +1 -1
- package/dist/extensions.js +5 -5
- package/dist/{google-B-Dhmzzf.js → google-BtMW9KzL.js} +2 -2
- package/dist/{google-B-Dhmzzf.js.map → google-BtMW9KzL.js.map} +1 -1
- package/dist/{host-signals-Cb2TlGtN.js → host-signals-91zyko_i.js} +5 -5
- package/dist/{host-signals-Cb2TlGtN.js.map → host-signals-91zyko_i.js.map} +1 -1
- package/dist/{host-C61ntFBC.js → host-uP3t08w8.js} +9 -9
- package/dist/{host-C61ntFBC.js.map → host-uP3t08w8.js.map} +1 -1
- package/dist/{host-version-BIx4CuBM.js → host-version-_RHlAB29.js} +2 -2
- package/dist/{host-version-BIx4CuBM.js.map → host-version-_RHlAB29.js.map} +1 -1
- package/dist/index.js +5 -5
- package/dist/ipc/remote.js +3 -3
- package/dist/{ipc-DiH_P-wr.js → ipc-CatnsVEd.js} +4 -4
- package/dist/{ipc-DiH_P-wr.js.map → ipc-CatnsVEd.js.map} +1 -1
- package/dist/ipc.js +4 -4
- package/dist/{links-BbC_lOnn.js → links-a8C9eby4.js} +8 -8
- package/dist/{links-BbC_lOnn.js.map → links-a8C9eby4.js.map} +1 -1
- package/dist/{loaded-entry-C0vkCVNQ.js → loaded-entry-D6jzt5HQ.js} +2 -2
- package/dist/{loaded-entry-C0vkCVNQ.js.map → loaded-entry-D6jzt5HQ.js.map} +1 -1
- package/dist/{memory-C3w8nO8f.js → memory-CJy52DNi.js} +15 -15
- package/dist/{memory-C3w8nO8f.js.map → memory-CJy52DNi.js.map} +1 -1
- package/dist/{path-display-DRAEpKOU.js → path-display-CAWz-sMq.js} +3 -3
- package/dist/{path-display-DRAEpKOU.js.map → path-display-CAWz-sMq.js.map} +1 -1
- package/dist/providers/google.js +1 -1
- package/dist/{providers-CpXV_uLE.js → providers-zVRxiJDv.js} +2 -2
- package/dist/{providers-CpXV_uLE.js.map → providers-zVRxiJDv.js.map} +1 -1
- package/dist/providers.js +1 -1
- package/dist/{registry-CJHvmvaP.js → registry-CBoYDIND.js} +2 -2
- package/dist/{registry-CJHvmvaP.js.map → registry-CBoYDIND.js.map} +1 -1
- package/dist/{registry-CN6JlZKj.js → registry-CQOU5jvF.js} +2 -2
- package/dist/{registry-CN6JlZKj.js.map → registry-CQOU5jvF.js.map} +1 -1
- package/dist/{registry-CnnKaY9s.js → registry-YUUqbYGr.js} +2 -2
- package/dist/{registry-CnnKaY9s.js.map → registry-YUUqbYGr.js.map} +1 -1
- package/dist/{remote-hosts-DoO9CJUQ.js → remote-hosts-CT8Q95dR.js} +4 -4
- package/dist/{remote-hosts-DoO9CJUQ.js.map → remote-hosts-CT8Q95dR.js.map} +1 -1
- package/dist/{setting-D_FpKFMw.js → setting-_jh2OtiL.js} +2 -2
- package/dist/{setting-D_FpKFMw.js.map → setting-_jh2OtiL.js.map} +1 -1
- package/dist/{settings-keys-CW2UgHgb.js → settings-keys-BT0_oKjO.js} +2 -2
- package/dist/{settings-keys-CW2UgHgb.js.map → settings-keys-BT0_oKjO.js.map} +1 -1
- package/dist/{system-freeze-XgDPIwQS.js → system-freeze-DxJ-lRhu.js} +2 -2
- package/dist/{system-freeze-XgDPIwQS.js.map → system-freeze-DxJ-lRhu.js.map} +1 -1
- package/dist/tui.js +15 -15
- package/dist/{version-szdW1Od9.js → version-DwQI12WA.js} +2 -2
- package/dist/{version-szdW1Od9.js.map → version-DwQI12WA.js.map} +1 -1
- package/dist/{wire-C3l9jl9x.js → wire-Dxwxb7QQ.js} +2 -2
- package/dist/{wire-C3l9jl9x.js.map → wire-Dxwxb7QQ.js.map} +1 -1
- package/dist/{ws-CEHi0CiB.js → ws-CA3o2nie.js} +4 -4
- package/dist/{ws-CEHi0CiB.js.map → ws-CA3o2nie.js.map} +1 -1
- package/dist/{ws-client-t8XNWxcq.js → ws-client-C0iPAAzc.js} +2 -2
- package/dist/{ws-client-t8XNWxcq.js.map → ws-client-C0iPAAzc.js.map} +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-C61ntFBC.js","names":["isThenable","isThenable","failure","errorMessage","errorMessage","unloadOwner"],"sources":["../src/decisions/run-scope.ts","../src/extensions/hooks/registry.ts","../src/extensions/hooks/domain.ts","../src/extensions/integrations/domain.ts","../src/extensions/integrations/store.ts","../src/extensions/ui/dialogs.ts","../src/extensions/ui/domain.ts","../src/extensions/commands/domain.ts","../src/extensions/commands/registry.ts","../src/extensions/rpc/bridge.ts","../src/extensions/contracts/ids.ts","../src/extensions/contracts/owned.ts","../src/extensions/rpc/router.ts","../src/extensions/rpc/domain.ts","../src/extensions/runtime/guard.ts","../src/extensions/catalog/agents.ts","../src/extensions/catalog/mcp.ts","../src/extensions/catalog/skills.ts","../src/extensions/catalog/tools.ts","../src/extensions/contracts/domain.ts","../src/extensions/contracts/registry.ts","../src/extensions/runtime/domains/artifacts.ts","../src/extensions/runtime/domains/generate.ts","../src/extensions/runtime/domains/instructions.ts","../src/extensions/runtime/domains/plugins.ts","../src/extensions/runtime/domains/workspace.ts","../src/extensions/runtime/context.ts","../src/extensions/runtime/lifecycle.ts","../src/extensions/runtime/load-order.ts","../src/extensions/runtime/host.ts"],"sourcesContent":["/**\n * The run a decision belongs to, for decisions made away from the hook\n * context that carries `ctx.decide` (an extension's `ctx.generate.decide`\n * called from a hook observer).\n *\n * An agent binds `decide` to each hook context of a run: decisions made\n * through it fire `decision:start` / `decision:end` on that agent's bus\n * (with the `runId`), are cancelled with the run, and in a replay-mode run\n * are journaled as steps, so a replay takes the branch the live attempt\n * took. A host that runs an observer inside {@link withRunDecide} with that\n * binding lets other callers in the observer reach the same decider through\n * {@link currentRunDecide}.\n */\n\nimport type { AgentDecide } from './types'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nconst runDecide = new AsyncLocalStorage<AgentDecide>()\n\n/**\n * Runs `fn` (and every async continuation it starts) with `decide` as the\n * current run's decider. `undefined`: `fn` runs without one.\n *\n * @param decide - The run-bound decider of the hook context (`ctx.decide`).\n * @param fn - The work.\n * @returns What `fn` returns.\n */\nexport function withRunDecide<T>(decide: AgentDecide | undefined, fn: () => T): T {\n return typeof decide === 'function' ? runDecide.run(decide, fn) : fn()\n}\n\n/** The decider bound by {@link withRunDecide} for the current async context, if any. */\nexport function currentRunDecide(): AgentDecide | undefined {\n return runDecide.getStore()\n}\n","/**\n * The interceptor chain shared by every extension. One registry per\n * runtime: each extension's `ctx.hooks.intercept` registers into it, and\n * the agent call sites (or the legacy-hook bridges) run it.\n *\n * Order: extension load order, then `priority` (higher first), then\n * registration order. Each handler gets the input and the result so far and\n * returns a replacement or `undefined` to keep it. A handler runs through\n * its extension's guard: a throw or a timeout is attributed to the\n * extension and skipped.\n */\n\nimport type { InterceptOptions, InterceptorHandler, Interceptors, SyncInterceptorName } from '../api/hooks'\nimport type { Guard } from '../runtime/deps'\nimport { readonlyView, unwrapReadonly } from './readonly'\n\n/** Name of an interceptor. */\nexport type InterceptorName = keyof Interceptors\n\n/** Interceptors run with `runInterceptors` (every one except the synchronous ones). */\nexport type AsyncInterceptorName = Exclude<InterceptorName, SyncInterceptorName>\n\n/** Every interceptor name, at runtime. Kept exhaustive at compile time. */\nexport const INTERCEPTOR_NAMES = [\n 'run',\n 'behavior',\n 'prompt',\n 'system',\n 'context',\n 'tool.call',\n 'tool.result',\n 'validation',\n 'skills.activate',\n 'mcp.tools',\n 'provider',\n 'retry',\n 'compaction',\n 'title',\n 'shell.env',\n 'http.request',\n 'http.response',\n 'tracing.redact',\n 'content-ref.resolve',\n] as const satisfies readonly InterceptorName[]\n\ntype MissingInterceptorNames = Exclude<InterceptorName, (typeof INTERCEPTOR_NAMES)[number]>\n// Fails to compile when an `Interceptors` key is absent from `INTERCEPTOR_NAMES`.\nconst _interceptorNamesExhaustive: MissingInterceptorNames extends never ? true : MissingInterceptorNames = true\nvoid _interceptorNamesExhaustive\n\nconst SYNC_NAMES: ReadonlySet<InterceptorName> = new Set<InterceptorName>(['tracing.redact'])\n\n/**\n * Whether `name` is an interceptor this runtime knows.\n *\n * @param name - Any string, from an extension.\n * @returns `true` for a key of {@link Interceptors}.\n */\nexport function isInterceptorName(name: string): name is InterceptorName {\n return (INTERCEPTOR_NAMES as readonly string[]).includes(name)\n}\n\n/**\n * Whether `name` runs on a synchronous path (`runInterceptorsSync`).\n *\n * @param name - An interceptor name.\n * @returns `true` for {@link SyncInterceptorName}.\n */\nexport function isSyncInterceptor(name: InterceptorName): name is SyncInterceptorName {\n return SYNC_NAMES.has(name)\n}\n\ntype MatchKeyOf = { [K in InterceptorName]?: (input: Interceptors[K][0]) => string | undefined }\n\n/** What `match` compares against, per interceptor. Interceptors not listed ignore `match`. */\nconst MATCH_KEY: MatchKeyOf = {\n 'tool.call': input => input.tool,\n 'tool.result': input => input.tool,\n 'http.request': input => input.provider,\n 'http.response': input => input.provider,\n 'provider': input => input.descriptor.key,\n 'mcp.tools': input => input.server,\n}\n\n/**\n * Whether interceptor `name` honours `InterceptOptions.match`.\n *\n * @param name - An interceptor name.\n * @returns `true` when the chain filters handlers by `match`.\n */\nexport function supportsMatch(name: InterceptorName): boolean {\n return MATCH_KEY[name] !== undefined\n}\n\n/**\n * Providers whose transport takes no custom fetch: `http.request` /\n * `http.response` never run for them. None today: every built-in provider\n * sends through the fetch the interceptors wrap.\n */\nexport const HTTP_UNSUPPORTED_PROVIDERS: readonly string[] = []\n\n/**\n * The providers in an `http.*` interceptor's `match` that its chain never\n * runs for (see {@link HTTP_UNSUPPORTED_PROVIDERS}).\n *\n * @param name - The interceptor name.\n * @param match - Its `match` option.\n * @returns The unsupported providers it names; empty for any other interceptor.\n */\nexport function unsupportedHttpMatch(name: InterceptorName, match: readonly string[] | undefined): string[] {\n if ((name !== 'http.request' && name !== 'http.response') || !match)\n return []\n return match.filter(provider => HTTP_UNSUPPORTED_PROVIDERS.includes(provider))\n}\n\ntype FinalOf = { [K in InterceptorName]?: (result: Interceptors[K][1]) => boolean }\n\n/** Results that end a chain: later handlers do not run. */\nconst FINAL: FinalOf = {\n 'tool.call': d => typeof d === 'object' && ('block' in d || 'result' in d),\n 'prompt': r => 'handled' in r && r.handled === true,\n}\n\ntype MergeOf = { [K in InterceptorName]?: (previous: Interceptors[K][1], next: Interceptors[K][1]) => Interceptors[K][1] }\n\n/** How a handler's result joins the result so far, where a plain replacement would lose data. */\nconst MERGE: MergeOf = {\n // Metadata namespaces accumulate along the chain: a later handler that returns only `{ result, isError }` keeps them.\n 'tool.result': (previous, next) => {\n if (!previous.metadata || next.metadata === previous.metadata)\n return next\n return { ...next, metadata: { ...previous.metadata, ...next.metadata } }\n },\n}\n\n/** Who registers an interceptor: the extension and the guard its handler runs through. */\nexport interface InterceptorRegistration extends InterceptOptions {\n /** The extension that owns the handler. Sets its place in the load order. */\n extensionId: string\n /** The extension's guard. Bounds and attributes each call. */\n guard: Guard\n}\n\n/** A registered interceptor, as `list` reports it. */\nexport interface InterceptorInfo {\n name: InterceptorName\n extensionId: string\n priority: number\n match?: readonly string[]\n}\n\n/** Options of one chain run. */\nexport interface RunInterceptorsOptions {\n /** Overrides the key `match` filters on (by default read from the input). */\n matchKey?: string\n}\n\n/** Options of {@link createInterceptorRegistry}. */\nexport interface InterceptorRegistryOptions {\n /** Position of an extension in the load order (lower runs first). Default: the order extensions first registered in. */\n loadOrder?: (extensionId: string) => number\n /** Time bound of one handler call, in ms. Default 5000. */\n timeoutMs?: number\n /** Per-interceptor time bounds, overriding `timeoutMs`. */\n timeouts?: Partial<Record<InterceptorName, number>>\n /** Hand handlers shallow read-only views of `input` and `current`. Default `true`. */\n readonlyViews?: boolean\n}\n\n/** The shared interceptor chain. */\nexport interface InterceptorRegistry {\n /**\n * Adds a handler to chain `name`.\n *\n * @returns The unregister function. Calling it twice is a no-op.\n */\n register: <K extends InterceptorName>(name: K, handler: InterceptorHandler<K>, registration: InterceptorRegistration) => () => void\n /**\n * Runs chain `name`: threads `initial` through every matching handler\n * in order and resolves to the final result.\n */\n runInterceptors: <K extends AsyncInterceptorName>(name: K, input: Interceptors[K][0], initial: Interceptors[K][1], opts?: RunInterceptorsOptions) => Promise<Interceptors[K][1]>\n /**\n * Runs a synchronous chain. A handler that returns a promise is counted as\n * an error against its extension and skipped.\n */\n runInterceptorsSync: <K extends SyncInterceptorName>(name: K, input: Interceptors[K][0], initial: Interceptors[K][1], opts?: RunInterceptorsOptions) => Interceptors[K][1]\n /** Whether chain `name` has a handler (that matches `matchKey`, when given). Lets call sites skip building inputs. */\n has: (name: InterceptorName, matchKey?: string) => boolean\n /** The registered handlers, in run order. */\n list: (name?: InterceptorName) => readonly InterceptorInfo[]\n}\n\ninterface Entry {\n name: InterceptorName\n handler: (input: unknown, current: unknown) => unknown\n extensionId: string\n guard: Guard\n priority: number\n match?: ReadonlySet<string>\n matchList?: readonly string[]\n seq: number\n active: boolean\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof (value as { then?: unknown }).then === 'function'\n}\n\n/**\n * Creates the interceptor registry. The runtime makes one and hands it to\n * every extension's hooks domain and to the agent call sites.\n *\n * @param options - Load order, time bounds, read-only views.\n * @returns An empty registry.\n */\nexport function createInterceptorRegistry(options: InterceptorRegistryOptions = {}): InterceptorRegistry {\n const chains = new Map<InterceptorName, Entry[]>()\n const firstSeen = new Map<string, number>()\n const views = options.readonlyViews !== false\n let seq = 0\n\n const orderOf = (extensionId: string): number => {\n if (options.loadOrder)\n return options.loadOrder(extensionId)\n let order = firstSeen.get(extensionId)\n if (order === undefined) {\n order = firstSeen.size\n firstSeen.set(extensionId, order)\n }\n return order\n }\n\n const compare = (a: Entry, b: Entry): number =>\n orderOf(a.extensionId) - orderOf(b.extensionId) || b.priority - a.priority || a.seq - b.seq\n\n const timeoutOf = (name: InterceptorName): number => options.timeouts?.[name] ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const keyOf = (name: InterceptorName, input: unknown, opts?: RunInterceptorsOptions): string | undefined => {\n if (opts?.matchKey !== undefined)\n return opts.matchKey\n const read = MATCH_KEY[name] as ((input: unknown) => string | undefined) | undefined\n return read?.(input)\n }\n\n const matching = (name: InterceptorName, key: string | undefined): Entry[] => {\n const chain = chains.get(name)\n if (!chain)\n return []\n const filters = supportsMatch(name)\n return chain.filter(e => !filters || !e.match || (key !== undefined && e.match.has(key)))\n }\n\n const isFinal = (name: InterceptorName, result: unknown): boolean => {\n const check = FINAL[name] as ((r: unknown) => boolean) | undefined\n return result !== undefined && check !== undefined && check(result)\n }\n\n const merge = (name: InterceptorName, previous: unknown, next: unknown): unknown => {\n const join = MERGE[name] as ((p: unknown, n: unknown) => unknown) | undefined\n return join ? join(previous, next) : next\n }\n\n const view = <T>(value: T): T => views ? readonlyView(value) : value\n const label = (e: Entry): string => `hooks.intercept('${e.name}')`\n\n return {\n register(name, handler, registration) {\n if (!isInterceptorName(name))\n throw new TypeError(`hooks.intercept: unknown interceptor \"${String(name)}\"`)\n if (typeof handler !== 'function')\n throw new TypeError(`hooks.intercept('${name}'): handler must be a function`)\n const match = registration.match ? [...registration.match] : undefined\n const entry: Entry = {\n name,\n handler: handler as Entry['handler'],\n extensionId: registration.extensionId,\n guard: registration.guard,\n priority: registration.priority ?? 0,\n ...(match ? { match: new Set(match), matchList: match } : {}),\n seq: seq++,\n active: true,\n }\n orderOf(entry.extensionId)\n const chain = chains.get(name) ?? []\n chain.push(entry)\n chain.sort(compare)\n chains.set(name, chain)\n return () => {\n if (!entry.active)\n return\n entry.active = false\n const current = chains.get(name)\n const i = current?.indexOf(entry) ?? -1\n if (current && i >= 0)\n current.splice(i, 1)\n }\n },\n\n async runInterceptors(name, input, initial, opts) {\n let current = initial\n for (const e of matching(name, keyOf(name, input, opts))) {\n if (!e.active)\n continue\n const next = await e.guard.call(label(e), () => e.handler(view(input), view(current)), { timeoutMs: timeoutOf(name) })\n if (next !== undefined)\n current = merge(name, current, unwrapReadonly(next)) as typeof current\n if (isFinal(name, current))\n break\n }\n return current\n },\n\n runInterceptorsSync(name, input, initial, opts) {\n let current = initial\n for (const e of matching(name, keyOf(name, input, opts))) {\n if (!e.active)\n continue\n const next = e.guard.callSync(label(e), () => {\n const out = e.handler(view(input), view(current))\n if (isThenable(out)) {\n // Settle it quietly: its value is never used.\n void Promise.resolve(out).catch(() => {})\n throw new TypeError(`${label(e)} must return synchronously, not a promise`)\n }\n return out\n })\n if (next !== undefined)\n current = unwrapReadonly(next) as typeof current\n if (isFinal(name, current))\n break\n }\n return current\n },\n\n has(name, matchKey) {\n const chain = chains.get(name)\n if (!chain?.length)\n return false\n return matchKey === undefined || matching(name, matchKey).length > 0\n },\n\n list(name) {\n const names = name ? [name] : [...chains.keys()]\n return names.flatMap(n => (chains.get(n) ?? []).map(e => ({\n name: e.name,\n extensionId: e.extensionId,\n priority: e.priority,\n ...(e.matchList ? { match: e.matchList } : {}),\n })))\n },\n }\n}\n","/**\n * `ctx.hooks` for one extension. `on` observes agent hooks and host\n * events through a read-only view; `intercept` joins the shared\n * {@link InterceptorRegistry}. Every registration belongs to the\n * extension's owner and goes when it is disposed.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../../agent'\nimport type { AgentDecide } from '../../decisions/types'\nimport type { Disposable } from '../api/core'\nimport type { HookEvents, HooksDomain, OnOptions } from '../api/hooks'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { InterceptorRegistry } from './registry'\nimport { isKnownHookEvent } from '../../agent-hooks'\nimport { withRunDecide } from '../../decisions/run-scope'\nimport { DisposedError } from '../api/core'\nimport { readonlyView } from './readonly'\nimport { supportsMatch, unsupportedHttpMatch } from './registry'\n\n/** Events the host reports, beside the agent hooks. */\nexport type HostEventName = 'run:settled' | 'session:event'\n\n/** The host events, at runtime. */\nexport const HOST_EVENT_NAMES = ['run:settled', 'session:event'] as const satisfies readonly HostEventName[]\n\n/** What the host gives the hooks domain. */\nexport interface HooksPort {\n /**\n * The agent hook bus: `Agent['hooks']` for a single agent, or a fan-out\n * over every agent the host runs. Handlers must be called with the hook's\n * context object.\n */\n agentHooks: Pick<Hookable<AgentHooks>, 'hook'>\n /** Host events: `run:settled` after each run, `session:event` for done, error and needs-attention. */\n hostEvents: {\n on: <K extends HostEventName>(name: K, fn: (event: HookEvents[K]) => void) => () => void\n }\n /**\n * The session an event belongs to. Called for `on(…, { sessionId })`\n * filtering; when it returns `undefined` the domain reads\n * `event.sessionId` or `event.session.id`. A host with one agent per\n * session answers from the bus the event came from.\n */\n sessionIdOf?: (name: keyof HookEvents, event: unknown) => string | undefined\n}\n\n/** Runtime options of {@link createHooksDomain}. */\nexport interface HooksDomainOptions {\n /** The registry every extension's interceptors join. */\n interceptors: InterceptorRegistry\n /** Time bound of one observer call, in ms. Default 5000. */\n observerTimeoutMs?: number\n /** Hand observers a shallow read-only view of the event. Default `true`. */\n readonlyEvents?: boolean\n}\n\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 5000\n\nfunction isHostEvent(name: string): name is HostEventName {\n return (HOST_EVENT_NAMES as readonly string[]).includes(name)\n}\n\n/**\n * The session id an event carries: `sessionId`, else `session.id`.\n *\n * @param event - A hook payload.\n * @returns The id, or `undefined` when the event names no session.\n */\nexport function sessionIdFromEvent(event: unknown): string | undefined {\n if (event === null || typeof event !== 'object')\n return undefined\n const { sessionId, session } = event as { sessionId?: unknown, session?: { id?: unknown } }\n if (typeof sessionId === 'string')\n return sessionId\n if (session && typeof session === 'object' && typeof session.id === 'string')\n return session.id\n return undefined\n}\n\n/**\n * Builds `ctx.hooks` for one extension.\n *\n * Observers never hold up the agent: each runs through the guard, bounded by\n * `observerTimeoutMs`, and the hook returns without waiting for it.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's agent hook bus and host events.\n * @param options - The shared interceptor registry and time bounds.\n * @returns The extension's hooks domain.\n */\nexport function createHooksDomain(deps: DomainDeps, port: HooksPort, options: HooksDomainOptions): HooksDomain {\n const { owner, guard, logger, extensionId } = deps\n const observerTimeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS\n const readonlyEvents = options.readonlyEvents !== false\n\n const track = (what: string, unregister: () => void): Disposable => {\n let done = false\n let fromOwner = false\n const cleanup = owner.onCleanup(() => {\n fromOwner = true\n dispose()\n })\n function dispose(): void {\n if (done)\n return\n done = true\n if (!fromOwner)\n cleanup.dispose()\n try {\n unregister()\n }\n catch (err) {\n logger.warn(`${what}: unregister failed`, { extensionId, error: String(err) })\n }\n }\n return { dispose }\n }\n\n const on: HooksDomain['on'] = (event, handler, opts?: OnOptions) => {\n const what = `hooks.on('${String(event)}')`\n if (owner.disposed)\n throw new DisposedError(what)\n if (typeof event !== 'string' || (!isHostEvent(event) && !isKnownHookEvent(event)))\n throw new TypeError(`hooks.on: unknown event \"${String(event)}\"`)\n if (typeof handler !== 'function')\n throw new TypeError(`${what}: handler must be a function`)\n const wanted = opts?.sessionId\n const observe = (payload: unknown): void => {\n if (wanted !== undefined && (port.sessionIdOf?.(event, payload) ?? sessionIdFromEvent(payload)) !== wanted)\n return\n const view = readonlyEvents ? readonlyView(payload) : payload\n // The run's decider (`ctx.decide` on the event): `ctx.generate.decide` in the observer goes through it.\n const decide = payload !== null && typeof payload === 'object' ? (payload as { decide?: AgentDecide }).decide : undefined\n void guard.call(what, () => withRunDecide(decide, () => (handler as (e: unknown) => void | Promise<void>)(view)), { timeoutMs: observerTimeoutMs })\n }\n const unregister = isHostEvent(event)\n ? port.hostEvents.on(event, observe)\n : port.agentHooks.hook(event as keyof AgentHooks, observe as AgentHooks[keyof AgentHooks])\n return track(what, unregister)\n }\n\n const intercept: HooksDomain['intercept'] = (name, handler, opts) => {\n const what = `hooks.intercept('${String(name)}')`\n if (owner.disposed)\n throw new DisposedError(what)\n const unregister = options.interceptors.register(name, handler, { ...opts, extensionId, guard })\n if (opts?.match && !supportsMatch(name))\n logger.warn(`${what}: \\`match\\` is ignored by this interceptor`, { extensionId })\n const unsupported = unsupportedHttpMatch(name, opts?.match)\n if (unsupported.length > 0)\n logger.warn(`${what}: never runs for ${unsupported.join(', ')}: that transport takes no custom fetch`, { extensionId, providers: unsupported })\n return track(what, unregister)\n }\n\n return { on, intercept }\n}\n","/**\n * `ctx.integrations` for one extension: a view on the process-wide\n * {@link IntegrationRegistry}. Registrations and `onChange` listeners belong\n * to the extension's owner and go when it is disposed; a connect flow\n * started through it aborts then too. Connections are shared: any extension\n * reads, resolves or disconnects any integration's connections.\n */\n\nimport type { IntegrationsDomain } from '../api/sessions'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { IntegrationFlowPort } from './connect'\nimport type { IntegrationRegistry } from './registry'\nimport { assertAlive, track } from '../runtime/owner'\nimport { integrationRegistry } from './registry'\n\n/** What a host provides to `ctx.integrations`: how connect flows show their UI and run commands. */\nexport type IntegrationsHostPort = IntegrationFlowPort\n\n/**\n * Builds `ctx.integrations`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's flow UI and command runner.\n * @param registry - The registry to use. Defaults to the one the host installed (`installIntegrationRegistry`); calls reject when there is none.\n */\nexport function createIntegrationsDomain(deps: DomainDeps, port: IntegrationsHostPort, registry?: IntegrationRegistry): IntegrationsDomain {\n const reg = (): IntegrationRegistry => {\n const found = registry ?? integrationRegistry()\n if (!found)\n throw new Error('Integrations are not available in this host.')\n return found\n }\n const call = async <T>(what: string, fn: () => Promise<T>): Promise<T> => {\n assertAlive(deps.owner, `integrations.${what}`)\n return fn()\n }\n\n return {\n register(spec) {\n assertAlive(deps.owner, 'integrations.register')\n const registration = reg().register(spec, { extensionId: deps.extensionId, guard: deps.guard })\n if (!registration) {\n deps.logger.warn(`integrations.register: \"${spec.id}\" is already registered by another extension; this one is ignored`)\n return { dispose: () => {}, update: () => {} }\n }\n const tracked = track(deps.owner, registration)\n return {\n dispose: () => tracked.dispose(),\n update: (patch) => {\n assertAlive(deps.owner, 'integrations.update')\n registration.update(patch)\n },\n }\n },\n\n connections: id => reg().connections(id),\n\n connection: (id, opts) => reg().connection(id, opts?.account),\n\n setDefault: (id, account) => call('setDefault', () => reg().setDefault(id, account)),\n\n resolve: connection => call('resolve', () => reg().resolve(connection)),\n\n connect: {\n key: (id, key) => call('connect.key', () => reg().connectKey(id, key)),\n start: (id, methodId, opts) => call('connect.start', () => {\n const signal = opts?.signal ? AbortSignal.any([opts.signal, deps.owner.signal]) : deps.owner.signal\n return reg().start(id, methodId, port, { signal })\n }),\n },\n\n disconnect: (id, opts) => call('disconnect', () => reg().disconnect(id, opts?.account)),\n\n onChange(id, listener) {\n assertAlive(deps.owner, 'integrations.onChange')\n const off = reg().onChange(id, (connection) => {\n deps.guard.callSync(`integrations.onChange(${id})`, () => listener(connection))\n })\n return track(deps.owner, { dispose: off })\n },\n }\n}\n","/**\n * Where integration connections persist. The registry reads and writes one\n * record per integration (every connection of it, the default first)\n * through an {@link AuthStorePort}; hosts back it with the credentials file\n * (`./auth-store-port`), tests and SDK embeds with {@link createMemoryAuthStore}.\n */\n\nimport type { Connection, Credential } from '../api/sessions'\n\n/** One stored connection. */\nexport interface StoredIntegration {\n /** What Settings shows and `connection()` returns (`isDefault` is not stored: it is the list's order). */\n connection: Connection\n /** The credential `resolve()` hands out (never with `refreshToken`). */\n credential: Credential\n /** OAuth refresh token. Kept in the store, never handed to extensions. */\n refreshToken?: string\n}\n\n/** A legacy provider sign-in an integration may adopt (`IntegrationSpec.legacyCredentialKey`). */\nexport interface LegacyGrant {\n credential: Credential\n refreshToken?: string\n /** The account the entry names, if any. */\n account?: string\n /** A label the entry carries, if any. */\n label?: string\n}\n\n/**\n * Persistence for integration connections. Synchronous: `connection()` is\n * synchronous, and the file store is too. `read` returns `undefined` for\n * a missing or unreadable record; the first connection is the default.\n * `write(id, undefined)` (or an empty list) deletes.\n */\nexport interface AuthStorePort {\n /** Every stored connection of an integration, the default first. (A single record, from a port written before several connections, reads as the only one.) */\n read: (integrationId: string) => StoredIntegration[] | undefined\n /** Stores the connections of an integration (the default first), or deletes them. */\n write: (integrationId: string, value: readonly StoredIntegration[] | undefined) => void\n /** A legacy sign-in under `key` not adopted yet. Optional: stores without legacy entries omit it. */\n readLegacy?: (key: string) => LegacyGrant | undefined\n /** Marks the legacy entry under `key` adopted by `integrationId`, leaving its tokens in place. */\n markLegacy?: (key: string, integrationId: string) => void\n}\n\n/**\n * An in-memory {@link AuthStorePort}. Nothing survives the process. Records\n * are cloned in and out, like a real store.\n *\n * @param initial - Records to start with, keyed by integration id: one connection or a list (default first).\n * @param legacy - Legacy sign-ins to offer for adoption, keyed by their old key.\n */\nexport function createMemoryAuthStore(initial: Readonly<Record<string, StoredIntegration | readonly StoredIntegration[]>> = {}, legacy: Readonly<Record<string, LegacyGrant>> = {}): AuthStorePort {\n const records = new Map<string, StoredIntegration[]>(Object.entries(structuredClone(initial)).map(([id, v]) => [id, Array.isArray(v) ? v : [v as StoredIntegration]]))\n const grants = new Map<string, LegacyGrant>(Object.entries(structuredClone(legacy)))\n return {\n read: id => structuredClone(records.get(id)),\n write: (id, value) => {\n if (!value?.length)\n records.delete(id)\n else\n records.set(id, structuredClone([...value]))\n },\n readLegacy: key => structuredClone(grants.get(key)),\n markLegacy: (key) => {\n grants.delete(key)\n },\n }\n}\n","/**\n * The dialog router: `ctx.ui` dialogs and toasts go to one client. The\n * client viewing the session wins (the most recently active of them); with\n * no session, or nobody viewing it, the last active client. No client:\n * {@link NoUiError}. Timeouts and abort signals end the dialog on the\n * client too (the port's signal aborts).\n *\n * Toasts and OS notifications are fire-and-forget, so before any client\n * attaches they wait in a small buffer ({@link PENDING_UI_LIMIT} entries,\n * each dropped after {@link PENDING_UI_TTL_MS}) and go, in order, to the\n * first client that can show them: when the port reports a client change\n * (`onClientsChange`), or at the next call that finds one.\n *\n * The router only routes and bounds; it does not interpret answers. The\n * `coerce*` helpers turn a client's answer into the type `ctx.ui` promises.\n */\n\nimport type { PlanPayload, PlanResponse, QuestionPayload, QuestionResponse } from '../../chat/interactions'\nimport type { DialogOptions, SelectOption } from '../api/ui'\nimport type { WireSettings } from '../settings'\nimport type { UiClock } from './clock'\nimport { DialogTimeoutError, NoUiError } from '../api/ui'\nimport { systemClock } from './clock'\n\n/** A connected client as the host reports it. */\nexport interface UiClientInfo {\n /** Unique per connected client (a window, a TUI, a protocol connection). */\n id: string\n /** Sessions it shows now. */\n viewing: readonly string[]\n /** When the user last acted in it (input, focus), epoch ms. */\n lastActiveAt: number\n /** `false`: it cannot show dialogs (a headless protocol client). Default `true`. */\n dialogs?: boolean\n}\n\n/** A dialog on the wire, by kind. */\nexport type DialogRequest\n = | { kind: 'confirm', title: string, message?: string, confirmLabel?: string, danger?: boolean }\n | { kind: 'prompt', title: string, message?: string, placeholder?: string, initial?: string, secret?: boolean }\n | { kind: 'select', title: string, options: readonly SelectOption[], multi?: boolean, placeholder?: string, actions?: readonly { id: string, label: string }[] }\n /** `settings` is the settings renderer's wire format, initial values included. The answer is a value per key. */\n | { kind: 'form', title: string, settings: WireSettings }\n | { kind: 'askUser', payload: QuestionPayload }\n | { kind: 'presentPlan', payload: PlanPayload }\n | { kind: 'toast', text: string, tone: 'info' | 'success' | 'warn' | 'error', actions?: readonly { id: string, label: string }[], timeoutMs?: number }\n\n/** The kinds of {@link DialogRequest}. */\nexport type DialogKind = DialogRequest['kind']\n\n/** What the port gets beside the request. */\nexport interface DialogShowContext {\n /** Aborts when the dialog times out, the caller aborts, or the extension unloads: close it. */\n signal: AbortSignal\n /** The extension asking. */\n extensionId: string\n /** The session it is about, when given. */\n sessionId?: string\n /** Form dialogs: checks one value with the schema (including its `validate`). An error message, or `undefined`. */\n validate?: (key: string, value: unknown) => string | undefined\n}\n\n/** The host side of dialogs: which clients exist, and showing a dialog on one. */\nexport interface DialogPort {\n /** The connected clients now. */\n clients: () => readonly UiClientInfo[]\n /** Shows `request` on `clientId` and resolves with the client's raw answer. */\n show: (clientId: string, request: DialogRequest, ctx: DialogShowContext) => Promise<unknown>\n /**\n * Calls `listener` after a client attached, detached or changed. Returns\n * the unsubscribe. Optional: without it, buffered toasts and\n * notifications go out at the next `ctx.ui` call that finds a client.\n */\n onClientsChange?: (listener: () => void) => () => void\n}\n\n/** Most toasts and notifications kept while no client is attached. The oldest goes first. */\nexport const PENDING_UI_LIMIT = 20\n\n/** How long a buffered toast or notification waits for a client, in ms. */\nexport const PENDING_UI_TTL_MS = 60_000\n\n/** Options of one {@link DialogRouter.open} call. */\nexport interface DialogOpenOptions extends DialogOptions {\n extensionId: string\n /** On timeout: reject with {@link DialogTimeoutError} (default), or resolve `undefined` (toasts). */\n onTimeout?: 'reject' | 'resolve'\n /**\n * With no client: wait in the buffer for one instead of rejecting with\n * {@link NoUiError} (toasts). Resolves `undefined` when dropped (buffer\n * full, {@link PENDING_UI_TTL_MS} passed, aborted, router disposed). The\n * dialog's `timeoutMs` starts once it is shown.\n */\n buffer?: boolean\n /** Form dialogs: see {@link DialogShowContext.validate}. */\n validate?: (key: string, value: unknown) => string | undefined\n}\n\n/** Routes dialogs to clients. */\nexport interface DialogRouter {\n /**\n * The client a call about `sessionId` goes to, or `undefined`.\n * `opts.dialogs` (default `true`) skips clients that cannot show dialogs.\n */\n route: (sessionId?: string, opts?: { dialogs?: boolean }) => UiClientInfo | undefined\n /** Shows `request` on the routed client and resolves with its raw answer. */\n open: (request: DialogRequest, opts: DialogOpenOptions) => Promise<unknown>\n /**\n * Runs `deliver` on the client a fire-and-forget call about `sessionId`\n * goes to (any client, dialogs or not), now or, with no client yet, once\n * one attaches (buffered as for {@link DialogOpenOptions.buffer}).\n */\n deliver: (deliver: (client: UiClientInfo) => void, opts?: { sessionId?: string, signal?: AbortSignal }) => void\n /** Drops what is buffered (toasts resolve `undefined`) and stops listening to the port. */\n dispose: () => void\n}\n\n/** Options for {@link createDialogRouter}. */\nexport interface DialogRouterOptions {\n /** Timer for `timeoutMs`. Default: the real clock. */\n clock?: UiClock\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? Object.assign(new Error('The dialog was aborted'), { name: 'AbortError' })\n}\n\n/**\n * Creates a dialog router over a host port.\n *\n * @param port - Lists clients and shows dialogs on them.\n * @param options - Clock.\n */\nexport function createDialogRouter(port: DialogPort, options: DialogRouterOptions = {}): DialogRouter {\n const clock = options.clock ?? systemClock\n\n const route: DialogRouter['route'] = (sessionId, opts = {}) => {\n const wantDialogs = opts.dialogs ?? true\n const clients = port.clients().filter(c => !wantDialogs || c.dialogs !== false)\n const latest = (list: readonly UiClientInfo[]): UiClientInfo | undefined =>\n list.reduce<UiClientInfo | undefined>((best, c) => (!best || c.lastActiveAt > best.lastActiveAt ? c : best), undefined)\n if (sessionId) {\n const viewing = latest(clients.filter(c => c.viewing.includes(sessionId)))\n if (viewing)\n return viewing\n }\n return latest(clients)\n }\n\n /** A toast or notification waiting for a client. */\n interface Pending {\n sessionId?: string\n /** Needs a client that shows dialogs (toasts). */\n dialogs: boolean\n timer: unknown\n signal?: AbortSignal\n onAbort?: () => void\n deliver: (client: UiClientInfo) => void\n drop: () => void\n }\n const pending: Pending[] = []\n\n const take = (entry: Pending): boolean => {\n const at = pending.indexOf(entry)\n if (at < 0)\n return false\n pending.splice(at, 1)\n clock.clearTimeout(entry.timer)\n if (entry.onAbort)\n entry.signal?.removeEventListener('abort', entry.onAbort)\n return true\n }\n const drop = (entry: Pending): void => {\n if (take(entry))\n entry.drop()\n }\n\n /** Delivers, in order, every buffered entry a client can take now. */\n const flush = (): void => {\n for (const entry of [...pending]) {\n const client = route(entry.sessionId, { dialogs: entry.dialogs })\n if (client && take(entry))\n entry.deliver(client)\n }\n }\n\n const buffer = (entry: Omit<Pending, 'timer'>): void => {\n if (entry.signal?.aborted)\n return entry.drop()\n while (pending.length >= PENDING_UI_LIMIT)\n drop(pending[0]!)\n const queued: Pending = { ...entry, timer: undefined }\n queued.timer = clock.setTimeout(() => drop(queued), PENDING_UI_TTL_MS)\n // A toast nobody will see must not keep a finished process (a headless run) alive.\n ;(queued.timer as { unref?: () => void } | undefined)?.unref?.()\n if (entry.signal) {\n queued.onAbort = () => drop(queued)\n entry.signal.addEventListener('abort', queued.onAbort, { once: true })\n }\n pending.push(queued)\n }\n\n const unsubscribe = port.onClientsChange?.(flush)\n\n const show = (client: UiClientInfo, request: DialogRequest, opts: DialogOpenOptions): Promise<unknown> => {\n if (opts.signal?.aborted)\n return Promise.reject(abortReason(opts.signal))\n const controller = new AbortController()\n return new Promise<unknown>((resolve, reject) => {\n let settled = false\n let timer: unknown\n const onAbort = (): void => {\n const reason = abortReason(opts.signal!)\n // eslint-disable-next-line ts/no-use-before-define -- finish and onAbort refer to each other\n finish(() => reject(reason))\n controller.abort(reason)\n }\n const finish = (fn: () => void): void => {\n if (settled)\n return\n settled = true\n if (timer !== undefined)\n clock.clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n fn()\n }\n opts.signal?.addEventListener('abort', onAbort, { once: true })\n if (opts.timeoutMs !== undefined && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0) {\n timer = clock.setTimeout(() => {\n const error = new DialogTimeoutError(request.kind, opts.timeoutMs!)\n finish(() => (opts.onTimeout === 'resolve' ? resolve(undefined) : reject(error)))\n controller.abort(error)\n }, opts.timeoutMs)\n }\n let shown: Promise<unknown>\n try {\n shown = port.show(client.id, request, {\n signal: controller.signal,\n extensionId: opts.extensionId,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.validate ? { validate: opts.validate } : {}),\n })\n }\n catch (err) {\n shown = Promise.reject(err)\n }\n shown.then(\n value => finish(() => resolve(value)),\n err => finish(() => reject(err)),\n )\n })\n }\n\n const open: DialogRouter['open'] = (request, opts) => {\n if (opts.signal?.aborted)\n return Promise.reject(abortReason(opts.signal))\n if (pending.length > 0)\n flush()\n const client = route(opts.sessionId)\n if (client)\n return show(client, request, opts)\n if (!opts.buffer)\n return Promise.reject(new NoUiError(request.kind))\n return new Promise<unknown>((resolve, reject) => {\n buffer({\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n dialogs: true,\n ...(opts.signal ? { signal: opts.signal } : {}),\n deliver: target => show(target, request, opts).then(resolve, reject),\n drop: () => resolve(undefined),\n })\n })\n }\n\n const deliver: DialogRouter['deliver'] = (fn, opts = {}) => {\n if (opts.signal?.aborted)\n return\n if (pending.length > 0)\n flush()\n const client = route(opts.sessionId, { dialogs: false })\n if (client)\n return fn(client)\n buffer({\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n dialogs: false,\n ...(opts.signal ? { signal: opts.signal } : {}),\n deliver: fn,\n drop: () => {},\n })\n }\n\n const dispose = (): void => {\n unsubscribe?.()\n for (const entry of [...pending])\n drop(entry)\n }\n\n return { route, open, deliver, dispose }\n}\n\n/**\n * A select answer: ids among the options (one unless `multi`), and an\n * action among the declared ones. `undefined` for a cancel or a malformed answer.\n *\n * @param raw - The client's answer.\n * @param request - The select request it answers.\n */\nexport function coerceSelect(raw: unknown, request: Extract<DialogRequest, { kind: 'select' }>): { ids: readonly string[], action?: string } | undefined {\n if (!raw || typeof raw !== 'object')\n return undefined\n const o = raw as { ids?: unknown, action?: unknown }\n const known = new Set(request.options.map(opt => opt.id))\n const ids = Array.isArray(o.ids) ? [...new Set(o.ids.filter((id): id is string => typeof id === 'string' && known.has(id)))] : []\n const action = typeof o.action === 'string' && request.actions?.some(a => a.id === o.action) ? o.action : undefined\n if (ids.length === 0 && !action)\n return undefined\n return { ids: request.multi ? ids : ids.slice(0, 1), ...(action ? { action } : {}) }\n}\n\n/**\n * A toast answer: an action id among the declared ones, else `undefined`.\n *\n * @param raw - The client's answer.\n * @param actions - The toast's actions.\n */\nexport function coerceToastAction(raw: unknown, actions: readonly { id: string }[] | undefined): string | undefined {\n return typeof raw === 'string' && actions?.some(a => a.id === raw) ? raw : undefined\n}\n\n/**\n * An ask-user answer. A malformed answer counts as no answers.\n *\n * @param raw - The client's answer.\n */\nexport function coerceQuestion(raw: unknown): QuestionResponse {\n const o = raw && typeof raw === 'object' ? raw as Partial<QuestionResponse> : undefined\n if (o?.kind === 'question' && o.answers && typeof o.answers === 'object')\n return o as QuestionResponse\n return { kind: 'question', answers: {} }\n}\n\n/**\n * A plan answer. A malformed answer is a rejection.\n *\n * @param raw - The client's answer.\n */\nexport function coercePlan(raw: unknown): PlanResponse {\n const o = raw && typeof raw === 'object' ? raw as Partial<PlanResponse> : undefined\n if (o?.kind === 'plan' && (o.decision === 'approve' || o.decision === 'reject' || o.decision === 'revise'))\n return o as PlanResponse\n return { kind: 'plan', decision: 'reject' }\n}\n","/**\n * `ctx.ui`, `ctx.composer` and `ctx.add` for one extension. Dialogs go\n * through the {@link DialogRouter}; panels, navigation, the composer and OS\n * notifications go to the routed client through a {@link UiClientPort};\n * contributions go to the {@link UiRegistry}.\n */\n\nimport type { AddFn, ComposerDomain, UiDomain } from '../api/ui'\nimport type { PanelFocus } from '../panels'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { DialogOpenOptions, DialogRequest, DialogRouter } from './dialogs'\nimport type { UiRegistry } from './registry'\nimport { parseBindingSpec } from '../../chat/keybindings'\nimport { DisposedError } from '../api/core'\nimport { NoUiError } from '../api/ui'\nimport { resolveMod } from '../commands/keymap'\nimport { coercePlan, coerceQuestion, coerceSelect, coerceToastAction } from './dialogs'\nimport { checkSettingsValues, cleanSettingsSchema, settingsWire } from './settings-form'\n\n/** Files `ctx.composer.attach` takes. */\nexport type ComposerFiles = readonly { path: string }[] | readonly { name: string, mimeType: string, data: Uint8Array }[]\n\n/** A composer edit for one client. */\nexport type ComposerOp\n = | { op: 'insert', text: string }\n | { op: 'setText', text: string }\n | { op: 'attach', files: ComposerFiles }\n\n/** Where `ctx.ui.navigate` goes, with screen ids made full (`<extension>/<id>`). */\nexport type NavigateTarget = { screen: string } | { session: string } | { newSession: true }\n\n/** The host side of the non-dialog `ctx.ui` calls and `ctx.composer`. Each call names the routed client. */\nexport interface UiClientPort {\n /** Opens, closes or toggles a panel (full id or built-in) in the client. Whether it did. */\n panel: (clientId: string, request: { action: 'open' | 'close' | 'toggle', panelId: string, sessionId?: string, focus?: PanelFocus }) => Promise<boolean>\n /** The panels open in the client (beside `sessionId` when given). */\n panelState: (clientId: string, opts: { sessionId?: string }) => Promise<readonly string[]>\n /** Shows a screen, a session or a new session in the client. Whether it did. */\n navigate: (clientId: string, to: NavigateTarget) => Promise<boolean>\n /** Edits the composer of the client (the one for `sessionId` when given). Whether it did. */\n composer: (clientId: string, op: ComposerOp, opts: { sessionId?: string }) => Promise<boolean>\n /** Shows an OS notification from the client, unless the app has focus. */\n notify: (clientId: string, notification: { title: string, body?: string, sound?: boolean, sessionId?: string, extensionId: string }) => void\n /**\n * Presses a chord (`'mod+k'`, `mod` not resolved: the client resolves it\n * for its platform) in the client, as if the user typed it, in the view\n * of `sessionId` when given. Whether a binding took it. Absent: the host's\n * clients cannot, and `ctx.keymap.dispatch` rejects with `NoUiError`.\n */\n keymapDispatch?: (clientId: string, request: { chord: string, sessionId?: string }) => Promise<boolean>\n}\n\n/** What the UI domains share across extensions. */\nexport interface UiDomainPorts {\n registry: UiRegistry\n dialogs: DialogRouter\n client: UiClientPort\n}\n\nfunction signalFor(deps: DomainDeps, signal: AbortSignal | undefined): AbortSignal {\n return signal ? AbortSignal.any([deps.owner.signal, signal]) : deps.owner.signal\n}\n\n/**\n * `ctx.add` for one extension.\n *\n * @param deps - The extension's deps.\n * @param registry - The shared UI registry.\n */\nexport function createUiAdd(deps: DomainDeps, registry: UiRegistry): AddFn {\n return registry.bind(deps)\n}\n\n/**\n * `ctx.ui` for one extension.\n *\n * @param deps - The extension's deps.\n * @param ports - Registry, dialog router and client port.\n */\nexport function createUiDomain(deps: DomainDeps, ports: UiDomainPorts): UiDomain {\n const { registry, dialogs, client } = ports\n\n const open = (request: DialogRequest, opts: Omit<DialogOpenOptions, 'extensionId'>): Promise<unknown> =>\n dialogs.open(request, { ...opts, extensionId: deps.extensionId, signal: signalFor(deps, opts.signal) })\n\n /** Runs a client call; a port failure is logged and counts as \"did nothing\". */\n const onClient = async <T>(label: string, sessionId: string | undefined, fallback: T, fn: (clientId: string) => Promise<T>): Promise<T> => {\n const target = dialogs.route(sessionId, { dialogs: false })\n if (!target)\n return fallback\n try {\n return await fn(target.id)\n }\n catch (err) {\n deps.logger.warn(`ui.${label}: the client failed`, { error: err instanceof Error ? err.message : String(err) })\n return fallback\n }\n }\n\n const panelId = (id: string): string => registry.qualify('panel', deps.extensionId, id)\n\n return {\n confirm: async ({ title, message, confirmLabel, danger, ...opts }) =>\n (await open({ kind: 'confirm', title, ...(message ? { message } : {}), ...(confirmLabel ? { confirmLabel } : {}), ...(danger ? { danger } : {}) }, opts)) === true,\n prompt: async ({ title, message, placeholder, initial, secret, ...opts }) => {\n const raw = await open({ kind: 'prompt', title, ...(message ? { message } : {}), ...(placeholder ? { placeholder } : {}), ...(initial !== undefined ? { initial } : {}), ...(secret ? { secret } : {}) }, opts)\n return typeof raw === 'string' ? raw : undefined\n },\n select: async ({ title, options, multi, placeholder, actions, ...opts }) => {\n const request: Extract<DialogRequest, { kind: 'select' }> = { kind: 'select', title, options, ...(multi ? { multi } : {}), ...(placeholder ? { placeholder } : {}), ...(actions ? { actions } : {}) }\n return coerceSelect(await open(request, opts), request)\n },\n form: async ({ title, schema: authored, values, ...opts }) => {\n const schema = cleanSettingsSchema(deps.extensionId, authored)\n const runValidate = (validate: (value: string) => string | undefined, value: string): string | undefined =>\n deps.guard.callSync('ui.form.validate', () => validate(value))\n const validate = (key: string, value: unknown): string | undefined => {\n const setting = schema.items[key]\n if (!setting)\n return 'unknown setting'\n return checkSettingsValues({ items: { [key]: setting } }, { [key]: value }, runValidate).errors[key]\n }\n const raw = await open({ kind: 'form', title, settings: settingsWire(deps.extensionId, schema, values) }, { ...opts, validate })\n if (raw === undefined || raw === null)\n return undefined\n const check = checkSettingsValues(schema, raw, runValidate)\n const bad = Object.keys(check.errors)\n if (bad.length > 0)\n throw new TypeError(`form: the client sent invalid values for ${bad.join(', ')}`)\n return check.values\n },\n askUser: async (payload, opts = {}) => coerceQuestion(await open({ kind: 'askUser', payload }, opts)),\n presentPlan: async (payload, opts = {}) => coercePlan(await open({ kind: 'presentPlan', payload }, opts)),\n toast: async ({ text, tone, actions, timeoutMs, sessionId }) => {\n const request: DialogRequest = { kind: 'toast', text, tone: tone ?? 'info', ...(actions ? { actions } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}) }\n try {\n const raw = await open(request, { ...(sessionId ? { sessionId } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}), onTimeout: 'resolve', buffer: true })\n return coerceToastAction(raw, actions)\n }\n catch (err) {\n // A toast is fire-and-forget: nobody to show it to is not an error.\n if (err instanceof NoUiError) {\n deps.logger.debug('ui.toast: no client to show it', { text })\n return undefined\n }\n throw err\n }\n },\n notify: ({ title, body, sound, sessionId }) => {\n dialogs.deliver((target) => {\n try {\n client.notify(target.id, { title, ...(body ? { body } : {}), ...(sound ? { sound } : {}), ...(sessionId ? { sessionId } : {}), extensionId: deps.extensionId })\n }\n catch (err) {\n deps.logger.warn('ui.notify: the client failed', { error: err instanceof Error ? err.message : String(err) })\n }\n }, { ...(sessionId ? { sessionId } : {}), signal: deps.owner.signal })\n },\n panel: {\n open: (id, opts = {}) => onClient('panel.open', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'open', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}), ...(opts.focus ? { focus: opts.focus } : {}) })),\n close: (id, opts = {}) => onClient('panel.close', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'close', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}) })),\n toggle: (id, opts = {}) => onClient('panel.toggle', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'toggle', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}) })),\n state: (opts = {}) => onClient<readonly string[]>('panel.state', opts.sessionId, [], clientId =>\n client.panelState(clientId, opts.sessionId ? { sessionId: opts.sessionId } : {})),\n },\n navigate: async (to, opts = {}) => {\n if (opts.signal?.aborted)\n return false\n const target: NavigateTarget = 'screen' in to ? { screen: registry.qualify('screen', deps.extensionId, to.screen) } : to\n return onClient('navigate', opts.sessionId ?? ('session' in to ? to.session : undefined), false, clientId => client.navigate(clientId, target))\n },\n }\n}\n\n/** Longest chord `ctx.keymap.dispatch` takes. */\nconst MAX_CHORD_LENGTH = 64\n\n/**\n * The client side of `ctx.keymap.dispatch` for one extension: routes like\n * the non-dialog `ctx.ui` calls (the client viewing `sessionId`, else the\n * last active one) and asks it to press the chord.\n *\n * @param deps - The extension's deps.\n * @param ports - Dialog router and client port.\n * @returns The dispatch. Rejects with `NoUiError` when no client can take it, with a `TypeError` for a chord that does not parse; a client that fails answers `false`.\n */\nexport function createKeymapDispatch(deps: DomainDeps, ports: Pick<UiDomainPorts, 'dialogs' | 'client'>): (chord: string, sessionId?: string) => Promise<boolean> {\n return async (chord, sessionId) => {\n if (deps.owner.disposed)\n throw new DisposedError('keymap.dispatch')\n if (typeof chord !== 'string' || !chord.trim() || chord.length > MAX_CHORD_LENGTH || !parseBindingSpec(resolveMod(chord, 'linux')))\n throw new TypeError(`keymap.dispatch: \"${String(chord)}\" is not a chord`)\n const press = ports.client.keymapDispatch\n const target = press ? ports.dialogs.route(sessionId, { dialogs: false }) : undefined\n if (!press || !target)\n throw new NoUiError('keymap.dispatch')\n try {\n return await press(target.id, { chord: chord.trim(), ...(sessionId ? { sessionId } : {}) }) === true\n }\n catch (err) {\n deps.logger.warn('keymap.dispatch: the client failed', { error: err instanceof Error ? err.message : String(err) })\n return false\n }\n }\n}\n\n/**\n * `ctx.composer` for one extension.\n *\n * @param deps - The extension's deps.\n * @param ports - Registry, dialog router and client port.\n */\nexport function createComposerDomain(deps: DomainDeps, ports: UiDomainPorts): ComposerDomain {\n const { registry, dialogs, client } = ports\n const edit = async (op: ComposerOp, sessionId: string | undefined): Promise<boolean> => {\n const target = dialogs.route(sessionId, { dialogs: false })\n if (!target)\n return false\n try {\n return await client.composer(target.id, op, sessionId ? { sessionId } : {})\n }\n catch (err) {\n deps.logger.warn(`composer.${op.op}: the client failed`, { error: err instanceof Error ? err.message : String(err) })\n return false\n }\n }\n return {\n insert: (text, opts = {}) => edit({ op: 'insert', text }, opts.sessionId),\n setText: (text, opts = {}) => edit({ op: 'setText', text }, opts.sessionId),\n attach: (files, opts = {}) => edit({ op: 'attach', files }, opts.sessionId),\n completions: { register: provider => registry.completions.register(deps, provider) },\n autocomplete: { register: provider => registry.autocomplete.register(deps, provider) },\n }\n}\n","/**\n * `ctx.commands` and `ctx.keymap` for one extension. Validates each spec,\n * wraps its callbacks so errors are attributed to the extension, ties the\n * registration to the extension's owner, and hands the result to the\n * host-wide {@link CommandRegistry} (the port).\n */\n\nimport type { CommandArgSuggestion, CommandStep } from '../../chat/commands'\nimport type { PaletteItem } from '../../chat/palette'\nimport type { CommandsDomain, CommandSpec, KeymapDomain, PaletteProviderSpec } from '../api/commands'\nimport type { Bindable, Disposable, Readable } from '../api/core'\nimport type { DomainDeps, Guard } from '../runtime/deps'\nimport type { ExtensionPaletteItem, ExtensionPaletteProviderEntry } from '../types'\nimport type { CommandEntry, CommandsDomainPort } from './registry'\nimport { DisposedError } from '../api/core'\nimport { NoUiError } from '../api/ui'\nimport { normalizeChords } from './keymap'\n\n/** Options for {@link createCommandsDomain}. */\nexport interface CommandsDomainOptions {\n /** Palette group for commands and providers that name none. Default: the extension id. */\n displayName?: string\n /** `process.platform` of the host; decides what `mod` means. Default `process.platform`. */\n platform?: string\n /**\n * Presses a chord in the client viewing `sessionId` (`createKeymapDispatch`).\n * Absent: `ctx.keymap.dispatch` rejects with `NoUiError`.\n */\n dispatch?: (chord: string, sessionId?: string) => Promise<boolean>\n}\n\n/** The two namespaces the domain fills on `ctx`. */\nexport interface CommandsDomains {\n /** `ctx.commands`. */\n commands: CommandsDomain\n /** `ctx.keymap`. */\n keymap: KeymapDomain\n}\n\nconst SLASH_TOKEN = /^[^\\s/]\\S*$/\nconst LOCAL_ID = /^[\\w.-]+$/\n\n/**\n * `true` when `value` is a {@link Readable}.\n *\n * @param value - A {@link Bindable} field.\n */\nexport function isReadable<T>(value: Bindable<T> | undefined): value is Readable<T> {\n return !!value && typeof value === 'object'\n && typeof (value as Readable<T>).get === 'function'\n && typeof (value as Readable<T>).subscribe === 'function'\n}\n\n/**\n * An extension palette provider as the host-facing entry, its callbacks guarded.\n *\n * @param deps - The extension's id and guard.\n * @param spec - The provider as registered.\n * @param group - Group for items that name none.\n */\nfunction paletteProviderEntry(deps: DomainDeps, spec: PaletteProviderSpec, group: string): ExtensionPaletteProviderEntry {\n const { extensionId, guard } = deps\n // Namespaced like every palette provider: item ids go out as\n // `<extension>/<id>` and come back bare, so two extensions never collide.\n const id = `${extensionId}/${spec.id}`\n const providerGroup = spec.group?.trim() || group\n const prefix = `${extensionId}/`\n const namespaced = (itemId: string) => (itemId.startsWith(prefix) ? itemId : `${prefix}${itemId}`)\n const stamp = (items: readonly ExtensionPaletteItem[]): PaletteItem[] =>\n items.map(item => ({ ...item, id: namespaced(item.id), group: item.group ?? providerGroup, source: id }))\n const subscribe = spec.subscribe\n const entry: ExtensionPaletteProviderEntry = {\n id,\n owner: extensionId,\n group: providerGroup,\n items: async (ctx) => {\n const query = (ctx as { query?: unknown }).query\n const items = await guard.call(`palette provider ${id} items`, () => spec.items({\n query: typeof query === 'string' ? query : '',\n busy: ctx.busy === true,\n ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}),\n }), { fallback: [] })\n return stamp(Array.isArray(items) ? items : [])\n },\n run: async (itemId, ctx) => {\n const bare = itemId.startsWith(prefix) ? itemId.slice(prefix.length) : itemId\n const result = await guard.call(`palette provider ${id} run`, () => spec.run(bare, ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}))\n if (!result)\n return undefined\n return result.kind === 'items' ? { ...result, items: stamp(result.items) } : result\n },\n ...(typeof subscribe === 'function'\n ? {\n subscribe: (emit: () => void) => {\n const stop = guard.callSync(`palette provider ${id} subscribe`, () => subscribe(emit))\n return () => {\n if (typeof stop === 'function')\n guard.callSync(`palette provider ${id} unsubscribe`, stop)\n }\n },\n }\n : {}),\n }\n return entry\n}\n\n/** Marks a run in flight (`Guard.lease`): an unload meanwhile tears down only once it ends. Throws `DisposedError` once unloaded. */\nfunction lease(guard: Guard, label: string): () => void {\n return guard.lease?.(label) ?? (() => {})\n}\n\n/** `fn` holding a lease while it runs. */\nfunction leased<A extends unknown[], R>(guard: Guard, label: string, fn: (...args: A) => R): (...args: A) => R {\n return (...args: A): R => {\n const release = lease(guard, label)\n let result: R\n try {\n result = fn(...args)\n }\n catch (error) {\n release()\n throw error\n }\n if (result && typeof (result as unknown as PromiseLike<unknown>).then === 'function')\n return (result as unknown as Promise<unknown>).finally(release) as R\n release()\n return result\n }\n}\n\n/**\n * The steps of one pipeline share one lease, from the first step to the last\n * (or the step that throws, or an abort), so an unload between two steps does\n * not tear the extension down under the next one. Keyed by the run's context,\n * which `executeCommand` hands to every step.\n */\nfunction pipeline(guard: Guard, label: string, steps: readonly CommandStep[]): CommandStep[] {\n const runs = new WeakMap<object, () => void>()\n const end = (ctx: object): void => {\n const release = runs.get(ctx)\n runs.delete(ctx)\n release?.()\n }\n return steps.map((step, i) => ({\n run: async (ctx: Parameters<CommandStep['run']>[0]) => {\n if (!runs.has(ctx)) {\n runs.set(ctx, lease(guard, label))\n ctx.signal?.addEventListener('abort', () => end(ctx), { once: true })\n }\n try {\n const result = await step.run(ctx)\n if (i === steps.length - 1)\n end(ctx)\n return result\n }\n catch (error) {\n end(ctx)\n throw error\n }\n },\n }))\n}\n\n/**\n * Makes `ctx.commands` and `ctx.keymap` for one extension.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host-wide registry (or anything with its domain-facing members).\n * @param opts - Palette group and host platform.\n */\nexport function createCommandsDomain(deps: DomainDeps, port: CommandsDomainPort, opts: CommandsDomainOptions = {}): CommandsDomains {\n const { extensionId, owner, guard, logger } = deps\n const platform = opts.platform ?? process.platform\n const group = opts.displayName?.trim() || extensionId\n const noop: Disposable = { dispose() {} }\n\n // Ties a registration to the owner: disposing either one withdraws it once.\n const own = (what: string, register: () => Disposable): Disposable => {\n if (owner.disposed)\n throw new DisposedError(what)\n const registration = register()\n let done = false\n const cleanup = owner.onCleanup(() => dispose())\n function dispose() {\n if (done)\n return\n done = true\n cleanup.dispose()\n registration.dispose()\n }\n return { dispose }\n }\n\n // Counts an error in the extension's budget and logs it, without the\n // guard's timeout: a command may run an agent for minutes. The error is\n // rethrown so the host flow (`executeCommand`) still sees it.\n const report = (label: string, error: unknown) => {\n guard.callSync(label, () => {\n throw error\n })\n }\n const attributed = <A extends unknown[], R>(label: string, fn: (...args: A) => R) => (...args: A): R => {\n let result: R\n try {\n result = fn(...args)\n }\n catch (error) {\n report(label, error)\n throw error\n }\n if (result && typeof (result as unknown as PromiseLike<unknown>).then === 'function') {\n return (result as unknown as Promise<unknown>).catch((error: unknown) => {\n report(label, error)\n throw error\n }) as R\n }\n return result\n }\n\n const read = <T>(label: string, value: Bindable<T>, fallback: T): T => {\n if (!isReadable(value))\n return value\n return guard.callSync(label, () => value.get(), { fallback }) ?? fallback\n }\n\n const register = (spec: CommandSpec): Disposable => {\n if (owner.disposed)\n throw new DisposedError('commands.register')\n if (!spec || typeof spec.id !== 'string' || !LOCAL_ID.test(spec.id)) {\n logger.warn('commands.register: id must be a [A-Za-z0-9_.-]+ token', { id: String(spec?.id) })\n return noop\n }\n const id = `${extensionId}.${spec.id}`\n if (spec.title === undefined || (typeof spec.title === 'string' && !spec.title.trim())) {\n logger.warn('commands.register: missing title', { command: id })\n return noop\n }\n const hasSteps = Array.isArray(spec.steps) && spec.steps.length > 0\n if (typeof spec.run !== 'function' && !hasSteps) {\n logger.warn('commands.register: needs run() or a non-empty steps[]', { command: id })\n return noop\n }\n if (hasSteps && !spec.slash) {\n logger.warn('commands.register: steps run only as a / command; add slash', { command: id })\n return noop\n }\n\n const normalized = normalizeChords(spec.bind, { platform, editable: spec.editable })\n for (const { chord, reason } of normalized.refused) {\n const why = reason === 'reserved'\n ? 'esc and ctrl+c are reserved'\n : reason === 'bare'\n ? 'a bare key on an editable binding would fire while typing'\n : 'the chord does not parse'\n logger.warn(`commands.register: binding refused, ${why}`, { command: id, chord })\n }\n\n let slash: CommandEntry['slash']\n if (spec.slash) {\n const { name, aliases = [], argumentHint } = spec.slash\n if (typeof name !== 'string' || !SLASH_TOKEN.test(name)) {\n logger.warn('commands.register: slash name must be one token without a leading /, slash dropped', { command: id, name: String(name) })\n }\n else {\n const valid = aliases.filter(a => typeof a === 'string' && SLASH_TOKEN.test(a) && a.toLowerCase() !== name.toLowerCase())\n if (valid.length !== aliases.length)\n logger.warn('commands.register: invalid slash aliases dropped', { command: id })\n slash = { name, aliases: [...new Set(valid)], ...(argumentHint ? { argumentHint } : {}) }\n }\n }\n\n const run = spec.run\n const complete = spec.slash?.complete\n const steps: CommandStep[] | undefined = hasSteps\n ? pipeline(guard, `command ${id}`, spec.steps!.map((step, i) => ({ run: attributed(`command ${id} step ${i + 1}`, step.run) })))\n : undefined\n\n const entry: CommandEntry = {\n id,\n extensionId,\n group,\n spec,\n chords: normalized.chords,\n signal: owner.signal,\n logger,\n ...(slash ? { slash } : {}),\n title: () => read(`command ${id} title`, spec.title, id),\n description: () => spec.description === undefined ? undefined : read(`command ${id} description`, spec.description, undefined as string | undefined),\n enabled: () => spec.enabled === undefined ? true : read(`command ${id} enabled`, spec.enabled, false) !== false,\n watch(onChange) {\n const stops: (() => void)[] = []\n for (const [field, value] of [['title', spec.title], ['description', spec.description], ['enabled', spec.enabled]] as const) {\n if (!isReadable<unknown>(value))\n continue\n const stop = guard.callSync(`command ${id} ${field} subscribe`, () => value.subscribe(() => onChange()))\n if (typeof stop === 'function')\n stops.push(stop)\n }\n return () => {\n for (const stop of stops)\n guard.callSync(`command ${id} unsubscribe`, stop)\n }\n },\n ...(typeof run === 'function' ? { run: leased(guard, `command ${id}`, attributed(`command ${id}`, run)) } : {}),\n ...(steps ? { steps } : {}),\n ...(typeof complete === 'function'\n ? {\n complete: async (prefix: string): Promise<readonly CommandArgSuggestion[]> =>\n (await guard.call(`command ${id} complete`, () => complete(prefix), { fallback: [] })) ?? [],\n }\n : {}),\n }\n return own('commands.register', () => port.add(entry))\n }\n\n const provider = (spec: PaletteProviderSpec): Disposable => {\n if (owner.disposed)\n throw new DisposedError('commands.provider')\n if (!spec || typeof spec.id !== 'string' || !spec.id.trim()) {\n logger.warn('commands.provider: missing id')\n return noop\n }\n if (typeof spec.items !== 'function' || typeof spec.run !== 'function') {\n logger.warn('commands.provider: items and run must be functions', { provider: spec.id })\n return noop\n }\n const entry = paletteProviderEntry(deps, spec, group)\n return own('commands.provider', () => port.addProvider(entry, logger))\n }\n\n const commands: CommandsDomain = {\n register,\n provider,\n run: (commandId, runOpts) => port.run(commandId, runOpts),\n list: () => port.list(),\n }\n\n const keymap: KeymapDomain = {\n mode: {\n push(name, modeOpts) {\n if (owner.disposed)\n throw new DisposedError('keymap.mode.push')\n if (typeof name !== 'string' || !name.trim()) {\n logger.warn('keymap.mode.push: missing name')\n return noop\n }\n return own('keymap.mode.push', () => port.keymap.pushMode(name, modeOpts))\n },\n current: () => port.keymap.currentMode(),\n },\n list: () => port.keymapEntries(),\n active: (activeOpts = {}) => [...port.keymap.activeModes(activeOpts.sessionId)],\n dispatch: async (chord, dispatchOpts = {}) => {\n if (owner.disposed)\n throw new DisposedError('keymap.dispatch')\n if (!opts.dispatch)\n throw new NoUiError('keymap.dispatch')\n return opts.dispatch(chord, dispatchOpts.sessionId)\n },\n bindings(commandId) {\n const exact = port.keymap.bindings(commandId)\n if (exact.length > 0 || commandId.includes('.'))\n return exact\n return port.keymap.bindings(`${extensionId}.${commandId}`)\n },\n }\n\n return { commands, keymap }\n}\n","/**\n * The host-facing command registry: every extension's commands, projected\n * into the shapes the hosts already consume.\n *\n * - `/` commands: chat {@link Command} (`src/chat/commands.ts`), the extension\n * layer the hosts pass to `mergeCommands` beside their built-ins.\n * - Palette: {@link ExtensionPaletteProviderEntry} (`src/extensions/types.ts`),\n * one static provider per extension plus the dynamic providers.\n * - Keys: the {@link Keymap} (scopes, modes, fall-through), plus the\n * {@link ExtensionKeybinding} / {@link ExtensionFooterHint} shapes the TUI\n * dispatcher and footer read today.\n *\n * Projections are cached and rebuilt after a change; {@link CommandRegistry.subscribe}\n * tells the hosts when. A bound `title`, `description` or `enabled` counts as a change.\n */\n\nimport type { Command, CommandArgSuggestion, CommandStep, CommandStepContext } from '../../chat/commands'\nimport type { PaletteContext, PaletteItem } from '../../chat/palette'\nimport type { Logger } from '../../logger'\nimport type { CommandInvocation, CommandSource, CommandSpec, KeymapEntry } from '../api/commands'\nimport type { Disposable } from '../api/core'\nimport type { ExtensionFooterHint, ExtensionKeybinding, ExtensionPaletteProviderEntry } from '../types'\nimport type { Keymap, KeyTriggerContext } from './keymap'\nimport { createKeymap } from './keymap'\n\n/**\n * One registered command, as {@link createCommandsDomain} hands it to the\n * registry. Callbacks are already wrapped: errors are attributed to the\n * extension.\n */\nexport interface CommandEntry {\n /** Published id: `<extension>.<id>`. */\n readonly id: string\n /** The registering extension. */\n readonly extensionId: string\n /** Palette group used when the spec names none. */\n readonly group: string\n /** The spec as registered (static fields only are read from it). */\n readonly spec: Readonly<CommandSpec>\n /** Validated, canonical default chords. */\n readonly chords: readonly string[]\n /** The slash name and aliases that passed validation. */\n readonly slash?: { readonly name: string, readonly aliases: readonly string[], readonly argumentHint?: string }\n /** Aborts when the registering owner is disposed. */\n readonly signal: AbortSignal\n /** The extension's logger. */\n readonly logger: Logger\n /** The current title. */\n title: () => string\n /** The current description. */\n description: () => string | undefined\n /** The current `enabled` value. */\n enabled: () => boolean\n /** Calls `onChange` when a bound field changes. Returns the unsubscribe. */\n watch: (onChange: () => void) => () => void\n /** The command's `run`, attributed. Throws and rejects like the original. */\n run?: (invocation: CommandInvocation) => void | false | Promise<void | false>\n /** The command's `steps`, attributed. */\n steps?: readonly CommandStep[]\n /** Argument completion; never throws. */\n complete?: (prefix: string) => Promise<readonly CommandArgSuggestion[]>\n}\n\n/** A command as {@link CommandsDomain.list} reports it. */\nexport interface CommandListing {\n /** Published id. */\n id: string\n /** Current title. */\n title: string\n /** Slash name, without the `/`. */\n slash?: string\n /** Effective chords. */\n bind?: readonly string[]\n}\n\n/** A projected `/` command: the chat {@link Command} plus where it came from. */\nexport type SlashCommand = Command & {\n /** Published id of the command. */\n readonly commandId: string\n /** Hint shown after the name. */\n readonly argumentHint?: string\n}\n\n/** A projected palette item. `featured` and `suggested` are not part of {@link PaletteItem} yet. */\nexport type CommandPaletteItem = PaletteItem & { featured?: true, suggested?: true }\n\n/** Host side of the registry. Every member is optional. */\nexport interface CommandHostPort {\n /** Built-in commands, for {@link CommandRegistry.list}. */\n builtins?: () => readonly CommandListing[]\n /**\n * The host's built-in key bindings (its keybinding registry), with their\n * effective chords after `keybindings.json`, for\n * {@link CommandRegistry.keymapEntries}. An entry here wins over a\n * built-in command of the same id.\n */\n keybindings?: () => readonly KeymapEntry[]\n /** Runs a built-in command. Returns `false` when the id is unknown. */\n runBuiltin?: (id: string, opts: { args: string, sessionId?: string }) => boolean | Promise<boolean>\n /**\n * The session-bound members (`emit`, `runAgent`, `interaction`…) for a run\n * that does not come from `/`. Omit what the host cannot offer.\n */\n invocation?: (source: CommandSource, sessionId?: string) => Partial<CommandStepContext>\n /** Submits `/name args` through the host's prompt pipeline (runs a steps-only command from a key or `run`). */\n submitSlash?: (text: string, sessionId?: string) => void | Promise<void>\n}\n\n/** Options for {@link createCommandRegistry}. */\nexport interface CommandRegistryOptions {\n /** Host effects. */\n port?: CommandHostPort\n /** The keymap to bind into. Default: a new one. */\n keymap?: Keymap\n /** Registry-level log (listener errors). */\n logger?: Logger\n}\n\n/** What {@link createCommandsDomain} needs from the registry. */\nexport interface CommandsDomainPort {\n /** Adds a command. A duplicate published id is refused with a warning. */\n add: (entry: CommandEntry) => Disposable\n /** Adds a dynamic palette provider. A duplicate id is refused with a warning. */\n addProvider: (entry: ExtensionPaletteProviderEntry, logger: Logger) => Disposable\n /** Runs a command by published id. */\n run: (id: string, opts?: { args?: string, sessionId?: string }) => Promise<boolean>\n /** Every command, built-ins included. */\n list: () => readonly CommandListing[]\n /** Every command with its effective bindings, scope and mode: built-in commands and keys, then extension commands. */\n keymapEntries: () => readonly KeymapEntry[]\n /** The shared keymap. */\n readonly keymap: Keymap\n}\n\n/** The host-wide command registry. */\nexport interface CommandRegistry extends CommandsDomainPort {\n /** The extension `/` commands, collisions resolved (first registration wins). */\n slashCommands: () => readonly SlashCommand[]\n /** Palette providers: one static provider per extension, then the dynamic ones. */\n paletteProviders: () => readonly ExtensionPaletteProviderEntry[]\n /** The commands as {@link ExtensionKeybinding}s (default chords; the host applies `keybindings.json`). */\n keybindings: () => readonly ExtensionKeybinding[]\n /** Footer hints for commands with `hint: true` and a chord. */\n footerHints: () => readonly ExtensionFooterHint[]\n /** A command by published id. */\n get: (id: string) => CommandEntry | undefined\n /** Calls `listener` after any projection changed. Returns the unsubscribe. */\n subscribe: (listener: () => void) => () => void\n /** Releases the keymap subscription. */\n dispose: () => void\n}\n\ninterface Projections {\n slash?: SlashCommand[]\n palette?: ExtensionPaletteProviderEntry[]\n keybindings?: ExtensionKeybinding[]\n hints?: ExtensionFooterHint[]\n}\n\nconst WHEN_DISABLED = {\n session: 'Needs an open session',\n busy: 'Wait for the run to finish',\n} as const\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function'\n}\n\nfunction linkSignals(owner: AbortSignal, host: AbortSignal | undefined): AbortSignal {\n return host && host !== owner ? AbortSignal.any([owner, host]) : owner\n}\n\n/** Runs commands for keys, the palette and `run`, building the invocation from the host port. */\nfunction createRunner(port: CommandHostPort) {\n const invocation = (entry: CommandEntry, source: CommandSource, args: string, sessionId?: string): CommandInvocation => {\n const host = port.invocation?.(source, sessionId) ?? {}\n return {\n ...host,\n source,\n args,\n ...(sessionId !== undefined ? { sessionId } : {}),\n signal: linkSignals(entry.signal, host.signal),\n }\n }\n\n // Runs a command from a key: synchronous so the host knows at once whether\n // the key was used. An async run claims the key; its `false` comes too late.\n const triggerFromKey = (entry: CommandEntry, ctx: KeyTriggerContext): boolean => {\n if (!entry.run) {\n if (!entry.slash || !port.submitSlash)\n return false\n void Promise.resolve(port.submitSlash(`/${entry.slash.name}`, ctx.focus.sessionId)).catch(() => undefined)\n return true\n }\n let result: void | false | Promise<void | false>\n try {\n result = entry.run(invocation(entry, 'key', '', ctx.focus.sessionId))\n }\n catch {\n return true\n }\n if (isThenable(result)) {\n void result.then(\n (value) => {\n if (value === false)\n entry.logger.debug('commands: an async run returned false; the key was already used', { command: entry.id })\n },\n () => undefined,\n )\n return true\n }\n return result !== false\n }\n\n const runEntry = async (entry: CommandEntry, source: CommandSource, args: string, sessionId?: string): Promise<boolean> => {\n if (!entry.enabled())\n return false\n if (entry.run) {\n try {\n await entry.run(invocation(entry, source, args, sessionId))\n }\n catch {\n // Already attributed to the extension by the domain.\n }\n return true\n }\n if (entry.slash && port.submitSlash) {\n await port.submitSlash(`/${entry.slash.name}${args ? ` ${args}` : ''}`, sessionId)\n return true\n }\n return false\n }\n return { triggerFromKey, runEntry }\n}\n\n/** The `/` projection: first registration wins, colliding names and aliases are dropped with a warning. */\nfunction projectSlash(entries: readonly CommandEntry[], warnOnce: (entry: CommandEntry, key: string, message: string, attrs: Record<string, unknown>) => void): SlashCommand[] {\n const out: SlashCommand[] = []\n // Same rule as `mergeCommands`: first registration wins, case-insensitive,\n // aliases reserve names. A later command whose alias is taken keeps its\n // name and loses only the alias.\n const owners = new Map<string, string>()\n for (const entry of entries) {\n if (!entry.slash || !entry.enabled())\n continue\n const name = entry.slash.name.toLowerCase()\n const taken = owners.get(name)\n if (taken !== undefined) {\n warnOnce(entry, `name:${name}`, 'commands: slash name already taken, the command is not reachable by /', { command: entry.id, name: entry.slash.name, owner: taken })\n continue\n }\n owners.set(name, entry.id)\n const aliases: string[] = []\n for (const alias of entry.slash.aliases) {\n const key = alias.toLowerCase()\n const aliasOwner = owners.get(key)\n if (aliasOwner !== undefined) {\n if (aliasOwner !== entry.id)\n warnOnce(entry, `alias:${key}`, 'commands: slash alias already taken, dropped', { command: entry.id, alias, owner: aliasOwner })\n continue\n }\n owners.set(key, entry.id)\n aliases.push(alias)\n }\n const run = entry.run\n const steps: readonly CommandStep[] = entry.steps ?? (run\n ? [{\n run: async (ctx: CommandStepContext) => {\n await run({ ...ctx, source: 'slash', ...(ctx.session ? { sessionId: ctx.session.id } : {}) })\n },\n }]\n : [])\n const complete = entry.complete\n out.push({\n commandId: entry.id,\n name: entry.slash.name,\n group: entry.extensionId,\n description: entry.description() ?? entry.title(),\n steps,\n ...(aliases.length > 0 ? { aliases } : {}),\n ...(entry.slash.argumentHint ? { argumentHint: entry.slash.argumentHint } : {}),\n ...(complete ? { completeArgs: (prefix: string) => complete(prefix) } : {}),\n })\n }\n return out\n}\n\n/** One command as a palette row; `when` becomes a `disabled` reason. */\nfunction paletteItem(entry: CommandEntry, ctx: PaletteContext, source: string, keymap: Keymap): CommandPaletteItem {\n const when = entry.spec.when ?? 'always'\n const disabled = when === 'session' && !ctx.sessionId\n ? WHEN_DISABLED.session\n : when === 'idle' && (!ctx.sessionId || ctx.busy)\n ? (ctx.sessionId ? WHEN_DISABLED.busy : WHEN_DISABLED.session)\n : undefined\n const description = entry.description()\n const keywords = entry.spec.keywords?.split(/\\s+/).filter(Boolean)\n const chord = keymap.bindings(entry.id)[0]\n const palette = entry.spec.palette\n return {\n id: entry.id,\n title: entry.title(),\n group: entry.spec.group?.trim() || entry.group,\n source,\n ...(description ? { description } : {}),\n ...(keywords && keywords.length > 0 ? { keywords } : {}),\n ...(entry.spec.icon ? { icon: entry.spec.icon } : {}),\n ...(chord ? { keybinding: chord } : {}),\n ...(disabled ? { disabled } : {}),\n ...(typeof palette === 'object' && palette.featured ? { featured: true as const } : {}),\n ...(typeof palette === 'object' && palette.suggested ? { suggested: true as const } : {}),\n }\n}\n\n/** `ctx.keymap.list`: built-in commands and keys (a key wins over a command of its id), then the extension commands, with their effective bindings. */\nfunction keymapEntriesOf(port: CommandHostPort, keymap: Keymap, entries: readonly CommandEntry[]): KeymapEntry[] {\n const builtins = new Map<string, KeymapEntry>()\n for (const b of port.builtins?.() ?? [])\n builtins.set(b.id, { id: b.id, title: b.title, bindings: [...(b.bind ?? [])], scope: 'global', editable: false })\n for (const k of port.keybindings?.() ?? [])\n builtins.set(k.id, { ...k, bindings: [...k.bindings] })\n const bound = new Map(keymap.list().map(b => [b.commandId, b]))\n const own = entries.map((e): KeymapEntry => {\n const b = bound.get(e.id)\n const mode = b?.mode ?? e.spec.mode\n return {\n id: e.id,\n title: e.title(),\n bindings: [...(b?.chords ?? e.chords)],\n scope: b?.scope ?? e.spec.scope ?? 'global',\n ...(mode !== undefined ? { mode } : {}),\n editable: b?.editable ?? e.spec.editable === true,\n extensionId: e.extensionId,\n }\n })\n return [...builtins.values(), ...own]\n}\n\n/**\n * Makes the host-wide command registry.\n *\n * @param opts - Host port, keymap and logger.\n */\nexport function createCommandRegistry(opts: CommandRegistryOptions = {}): CommandRegistry {\n const port = opts.port ?? {}\n const keymap = opts.keymap ?? createKeymap(opts.logger ? { logger: opts.logger } : {})\n const entries: CommandEntry[] = []\n const providers: { entry: ExtensionPaletteProviderEntry, owner: string }[] = []\n const extensionOrder: string[] = []\n const listeners = new Set<() => void>()\n const warned = new Set<string>()\n let cache: Projections = {}\n\n const changed = () => {\n cache = {}\n for (const listener of [...listeners]) {\n try {\n listener()\n }\n catch (error) {\n opts.logger?.warn('commands: listener threw', { error: String(error) })\n }\n }\n }\n const unsubscribeKeymap = keymap.subscribe(changed)\n\n const noteExtension = (id: string) => {\n if (!extensionOrder.includes(id))\n extensionOrder.push(id)\n }\n\n const { triggerFromKey, runEntry } = createRunner(port)\n\n const warnOnce = (entry: CommandEntry, key: string, message: string, attrs: Record<string, unknown>) => {\n const id = `${entry.id}\\0${key}`\n if (warned.has(id))\n return\n warned.add(id)\n entry.logger.warn(message, attrs)\n }\n\n const staticProvider = (extensionId: string): ExtensionPaletteProviderEntry | undefined => {\n const own = entries.filter(e => e.extensionId === extensionId && e.spec.palette !== false && e.enabled())\n if (own.length === 0)\n return undefined\n const id = `${extensionId}/commands`\n return {\n id,\n owner: extensionId,\n group: own[0]!.group,\n items: ctx => own.filter(e => e.enabled()).map(e => paletteItem(e, ctx, id, keymap)),\n run: async (itemId, ctx) => {\n const entry = own.find(e => e.id === itemId)\n if (!entry)\n return undefined\n // A steps-only command needs the prompt: put `/name ` in the composer.\n if (!entry.run && entry.slash)\n return { kind: 'insert', text: `/${entry.slash.name} ` }\n // Started, not awaited: the palette closes at once, so a dialog the command opens can show.\n void runEntry(entry, 'palette', '', ctx.sessionId)\n return undefined\n },\n }\n }\n\n const projectPalette = (): ExtensionPaletteProviderEntry[] => {\n const out: ExtensionPaletteProviderEntry[] = []\n for (const extensionId of extensionOrder) {\n const provider = staticProvider(extensionId)\n if (provider)\n out.push(provider)\n }\n for (const { entry } of providers)\n out.push(entry)\n return out\n }\n\n const projectKeybindings = (): ExtensionKeybinding[] => entries\n .filter(e => e.enabled() && (e.run || e.slash))\n .map(e => ({\n id: e.id,\n default: e.chords.join(' | '),\n label: e.title(),\n description: e.description() ?? '',\n onTrigger: () => {\n triggerFromKey(e, { chord: '', focus: { scope: 'global' } })\n },\n }))\n\n const projectHints = (): ExtensionFooterHint[] => {\n const out: ExtensionFooterHint[] = []\n for (const entry of entries) {\n if (!entry.spec.hint || !entry.enabled())\n continue\n const chord = keymap.bindings(entry.id)[0]\n if (chord)\n out.push({ key: chord, label: entry.title() })\n }\n return out\n }\n\n const registry: CommandRegistry = {\n keymap,\n add(entry) {\n if (entries.some(e => e.id === entry.id)) {\n entry.logger.warn('commands.register: a command with this id is already registered, ignored', { command: entry.id })\n return { dispose() {} }\n }\n noteExtension(entry.extensionId)\n entries.push(entry)\n const unwatch = entry.watch(changed)\n const binding = keymap.add({\n commandId: entry.id,\n defaults: entry.chords,\n ...(entry.spec.scope ? { scope: entry.spec.scope } : {}),\n ...(entry.spec.editable ? { editable: true } : {}),\n ...(entry.spec.mode ? { mode: entry.spec.mode } : {}),\n ...(entry.spec.when ? { when: entry.spec.when } : {}),\n enabled: entry.enabled,\n trigger: ctx => triggerFromKey(entry, ctx),\n })\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n unwatch()\n const at = entries.indexOf(entry)\n if (at >= 0)\n entries.splice(at, 1)\n binding.dispose()\n changed()\n },\n }\n },\n addProvider(entry, logger) {\n if (providers.some(p => p.entry.id === entry.id)) {\n logger.warn('commands.provider: a provider with this id is already registered, ignored', { provider: entry.id })\n return { dispose() {} }\n }\n noteExtension(entry.owner)\n const slot = { entry, owner: entry.owner }\n providers.push(slot)\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n const at = providers.indexOf(slot)\n if (at >= 0)\n providers.splice(at, 1)\n changed()\n },\n }\n },\n async run(id, runOpts = {}) {\n const entry = entries.find(e => e.id === id)\n if (entry)\n return runEntry(entry, 'api', runOpts.args ?? '', runOpts.sessionId)\n if (!port.runBuiltin)\n return false\n return port.runBuiltin(id, { args: runOpts.args ?? '', ...(runOpts.sessionId !== undefined ? { sessionId: runOpts.sessionId } : {}) })\n },\n list() {\n const own = entries.map((e): CommandListing => {\n const bind = keymap.bindings(e.id)\n return {\n id: e.id,\n title: e.title(),\n ...(e.slash ? { slash: e.slash.name } : {}),\n ...(bind.length > 0 ? { bind } : {}),\n }\n })\n return [...(port.builtins?.() ?? []), ...own]\n },\n keymapEntries: () => keymapEntriesOf(port, keymap, entries),\n slashCommands: () => (cache.slash ??= projectSlash(entries, warnOnce)),\n paletteProviders: () => (cache.palette ??= projectPalette()),\n keybindings: () => (cache.keybindings ??= projectKeybindings()),\n footerHints: () => (cache.hints ??= projectHints()),\n get: id => entries.find(e => e.id === id),\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n dispose() {\n unsubscribeKeymap()\n },\n }\n return registry\n}\n","/**\n * Exposes the router to remote callers: protocol clients over IPC\n * (`rpc.call` / `rpc.event`) and HTTP (`POST /rpc/<contract>/<method>`),\n * and an extension's own UI in a renderer. The host implements the\n * {@link RpcRemoteTransport} port and decides who a connection is; the\n * bridge checks the payload at the trust boundary, passes the host's scope\n * check to the router (a method's `scope` against the connection's token)\n * and forwards events.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcRouter } from './router'\nimport type { RpcCaller, RpcCallParams, RpcEventEnvelope, RpcResponseEnvelope } from './wire'\nimport { jsonBytes, RPC_MAX_PAYLOAD_BYTES, RpcErrorType } from './wire'\n\n/** A remote caller. Remote peers are never extensions. */\nexport type RpcRemoteCaller = Extract<RpcCaller, { kind: 'ui' | 'client' }>\n\n/** What the host provides so remote peers hear events. */\nexport interface RpcRemoteTransport {\n /** Sends one event to remote peers as the `rpc.event` signal. The host picks the recipients. */\n publish: (event: RpcEventEnvelope) => void\n}\n\n/** Options of {@link createRpcRemoteBridge}. */\nexport interface RpcRemoteBridgeOptions {\n /** JSON size cap for request input, response output and event data. Defaults to {@link RPC_MAX_PAYLOAD_BYTES}. */\n maxPayloadBytes?: number\n /** Told about each event not published (not JSON, or over the cap). */\n onDrop?: (event: RpcEventEnvelope, reason: string) => void\n}\n\n/** The remote side of the router. Dispose it to stop forwarding events. */\nexport interface RpcRemoteBridge extends Disposable {\n /**\n * Runs a remote call. `params` is untrusted (`rpc.call` params or the\n * HTTP route plus body). `authorize`: whether the connection's token\n * reaches a method that needs that scope; absent, not limited (a local\n * connection). Never rejects.\n */\n call: (params: unknown, caller: RpcRemoteCaller, signal?: AbortSignal, authorize?: (scope: AccessScope) => boolean) => Promise<RpcResponseEnvelope>\n}\n\nfunction invalid(contract: string, method: string, message: string): RpcResponseEnvelope {\n return { ok: false, error: { type: RpcErrorType.InvalidInput, message }, meta: { contract, method, scope: 'chat' } }\n}\n\n/**\n * Connects `router` to a host transport.\n *\n * @param router - The process router.\n * @param transport - The host's event publisher.\n * @param options - Payload cap and drop reporting.\n * @returns The bridge.\n */\nexport function createRpcRemoteBridge(router: RpcRouter, transport: RpcRemoteTransport, options: RpcRemoteBridgeOptions = {}): RpcRemoteBridge {\n const max = options.maxPayloadBytes ?? RPC_MAX_PAYLOAD_BYTES\n const events = router.onEvent((event) => {\n const bytes = jsonBytes(event.data)\n if (bytes === null)\n return options.onDrop?.(event, 'event data is not JSON')\n if (bytes > max)\n return options.onDrop?.(event, `event data is ${bytes} bytes, over the ${max} byte cap`)\n transport.publish(event)\n })\n\n return {\n async call(params, caller, signal, authorize) {\n if (typeof params !== 'object' || params === null)\n return invalid('', '', 'rpc.call params must be an object')\n const { contract, method, input, directory } = params as Partial<RpcCallParams>\n if (typeof contract !== 'string' || typeof method !== 'string' || !contract || !method)\n return invalid(String(contract ?? ''), String(method ?? ''), 'rpc.call needs a contract and a method')\n if (directory !== undefined && typeof directory !== 'string')\n return invalid(contract, method, 'rpc.call directory must be a string')\n const inBytes = jsonBytes(input)\n if (inBytes === null || inBytes > max)\n return invalid(contract, method, inBytes === null ? 'input is not JSON' : `input is ${inBytes} bytes, over the ${max} byte cap`)\n const response = await router.call({ contract, method, input, ...(directory === undefined ? {} : { directory }) }, { caller, ...(signal ? { signal } : {}), ...(authorize ? { authorize } : {}) })\n if (!response.ok) {\n const errBytes = jsonBytes(response.error.data)\n if (errBytes === null || errBytes > max)\n return { ok: false, error: { type: response.error.type, message: response.error.message }, meta: response.meta }\n return response\n }\n const outBytes = jsonBytes(response.output)\n if (outBytes === null || outBytes > max) {\n const message = outBytes === null ? 'output is not JSON' : `output is ${outBytes} bytes, over the ${max} byte cap`\n return { ok: false, error: { type: RpcErrorType.Internal, message }, meta: response.meta }\n }\n return response\n },\n dispose: () => events.dispose(),\n }\n}\n","/**\n * Id ownership shared by contracts, registries and RPC: an extension may\n * publish under its own id, or under `<id>.<name>`.\n */\n\n/**\n * Whether `extensionId` may publish `id`.\n *\n * @param extensionId - The publishing extension.\n * @param id - The contract, registry or RPC contract id.\n * @returns `true` when `id` is the extension id or starts with `<extensionId>.`.\n */\nexport function ownsId(extensionId: string, id: string): boolean {\n return id === extensionId || (id.length > extensionId.length + 1 && id.startsWith(`${extensionId}.`))\n}\n\n/**\n * Throws when `extensionId` may not publish `id` (see {@link ownsId}).\n *\n * @param what - The call, for the message (`contracts.provide`).\n * @param extensionId - The publishing extension.\n * @param id - The id it tried to publish.\n */\nexport function assertOwnsId(what: string, extensionId: string, id: string): void {\n if (!ownsId(extensionId, id))\n throw new Error(`${what}: \"${id}\" must be \"${extensionId}\" or start with \"${extensionId}.\"`)\n}\n","/**\n * Ties a registration to its owner: disposing the owner disposes it, and\n * disposing it early releases the owner's hook.\n */\n\nimport type { Disposable, Owner } from '../api/core'\n\n/**\n * Wraps `dispose` so it runs once, either when called or when `owner` is disposed.\n *\n * @param owner - The owner the registration belongs to.\n * @param dispose - Withdraws the registration.\n * @returns The registration's Disposable.\n */\nexport function bindToOwner(owner: Owner, dispose: () => void): Disposable {\n let done = false\n let hook: Disposable | undefined\n const run = (): void => {\n if (done)\n return\n done = true\n hook?.dispose()\n dispose()\n }\n hook = owner.onCleanup(run)\n return { dispose: run }\n}\n","/**\n * The process-wide RPC router: registrations by contract id, calls, and\n * event fan-out. One per host process. Every extension's rpc domain\n * registers on it and calls through it; the remote bridge exposes it to\n * protocol clients.\n *\n * A contract id holds a stack of registrations: the same extension loaded\n * for several directories (daemon), or a reloading instance overlapping the\n * old one. A call goes to the registration of the requested directory, else\n * the newest.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcCaller, RpcEventEnvelope, RpcRequestEnvelope, RpcResponseEnvelope, RpcResult, RpcWireError } from './wire'\nimport { errorMessage } from './schema'\nimport { RpcErrorType } from './wire'\n\n/** What a registration handler receives besides method and input. */\nexport interface RpcHandlerContext {\n /** Aborts when the caller gives up. */\n readonly signal: AbortSignal\n /** Who calls. */\n readonly caller: RpcCaller\n}\n\n/** One contract implementation, as the router holds it. */\nexport interface RpcRouterEntry {\n /** Contract id. */\n readonly contractId: string\n /** The implementing extension. */\n readonly extensionId: string\n /** The project the implementing extension runs in. */\n readonly directory: string\n /** Method names with the least token scope a protocol client needs. */\n readonly methods: Readonly<Record<string, { readonly scope: AccessScope }>>\n /** Event names of the contract. */\n readonly events: readonly string[]\n /** Runs a method the entry lists. Validates and never throws. */\n handle: (method: string, input: unknown, ctx: RpcHandlerContext) => Promise<RpcResult>\n}\n\n/** A registered contract, as hosts list it (for the protocol hello, Settings). */\nexport interface RpcContractDescriptor {\n /** Contract id. */\n contract: string\n /** The implementing extension. */\n extensionId: string\n /** The project it runs in. */\n directory: string\n /** Methods with the least token scope a protocol client needs. */\n methods: { name: string, scope: AccessScope }[]\n /** Event names. */\n events: string[]\n}\n\n/** Options of {@link RpcRouter.call}. */\nexport interface RpcRouterCallOptions {\n /** Who calls. */\n caller: RpcCaller\n /**\n * Whether the caller's token reaches a method that needs `scope`. Absent:\n * not limited (in-process callers, local connections, other extensions).\n * A remote host passes its connection's check (`scopeAllows`).\n */\n authorize?: (scope: AccessScope) => boolean\n /** Aborts the call: it then answers `rpc.aborted`. */\n signal?: AbortSignal\n}\n\n/** The process-wide RPC router. */\nexport interface RpcRouter {\n /** Adds an implementation. Disposing it removes it; the one below (if any) answers again. */\n register: (entry: RpcRouterEntry) => Disposable\n /** Runs a call. Never rejects: failures are `ok: false` envelopes. */\n call: (request: RpcRequestEnvelope, opts: RpcRouterCallOptions) => Promise<RpcResponseEnvelope>\n /** Delivers an event to local subscribers and to {@link RpcRouter.onEvent} listeners. */\n emit: (event: RpcEventEnvelope) => void\n /** Listens to one event of one contract, whether or not it is registered yet. */\n subscribe: (contract: string, event: string, listener: (event: RpcEventEnvelope) => void) => Disposable\n /** Listens to every event (the remote bridge forwards them). */\n onEvent: (listener: (event: RpcEventEnvelope) => void) => Disposable\n /** Calls `listener` after each register and unregister. */\n onChange: (listener: () => void) => Disposable\n /** Whether `contract` has a registration. */\n has: (contract: string) => boolean\n /** Every active registration (the one calls go to without a directory), in registration order. */\n list: () => RpcContractDescriptor[]\n}\n\n/**\n * Resolves with `promise`, or with `onAbort()` once `signal` aborts, whichever comes first.\n *\n * @param promise - The work.\n * @param signal - The signal to race.\n * @param onAbort - The value when aborted.\n */\nexport function raceAbort<T, A>(promise: Promise<T>, signal: AbortSignal, onAbort: () => A): Promise<T | A> {\n if (signal.aborted)\n return Promise.resolve(onAbort())\n return new Promise<T | A>((resolve, reject) => {\n const abort = (): void => resolve(onAbort())\n signal.addEventListener('abort', abort, { once: true })\n promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort))\n })\n}\n\nfunction failure(type: string, message: string, data?: unknown): { ok: false, error: RpcWireError } {\n return { ok: false, error: data === undefined ? { type, message } : { type, message, data } }\n}\n\nfunction safeEach<T>(listeners: Set<(value: T) => void>, value: T): void {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n }\n catch {\n // Domain listeners are guarded; a host listener throwing must not stop delivery.\n }\n }\n}\n\n/**\n * Creates an empty router.\n *\n * @returns The router, shared by every extension of the process.\n */\nexport function createRpcRouter(): RpcRouter {\n const entries = new Map<string, RpcRouterEntry[]>()\n const subscribers = new Map<string, Set<(event: RpcEventEnvelope) => void>>()\n const firehose = new Set<(event: RpcEventEnvelope) => void>()\n const changes = new Set<() => void>()\n\n function pick(contract: string, directory: string | undefined): RpcRouterEntry | undefined {\n const stack = entries.get(contract)\n if (!stack?.length)\n return undefined\n if (directory !== undefined) {\n for (let i = stack.length - 1; i >= 0; i--) {\n if (stack[i]!.directory === directory)\n return stack[i]\n }\n }\n return stack.at(-1)\n }\n\n function changed(): void {\n for (const listener of [...changes]) {\n try {\n listener()\n }\n catch {}\n }\n }\n\n function listen<T>(set: Set<T>, listener: T, cleanup?: () => void): Disposable {\n set.add(listener)\n return {\n dispose() {\n set.delete(listener)\n cleanup?.()\n },\n }\n }\n\n return {\n register(entry) {\n const stack = entries.get(entry.contractId) ?? []\n stack.push(entry)\n entries.set(entry.contractId, stack)\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n stack.splice(stack.indexOf(entry), 1)\n if (!stack.length)\n entries.delete(entry.contractId)\n changed()\n },\n }\n },\n\n async call(request, { caller, signal, authorize }) {\n const { contract, method } = request\n const entry = pick(contract, request.directory)\n const spec = entry && Object.hasOwn(entry.methods, method) ? entry.methods[method] : undefined\n const meta = { contract, method, scope: spec?.scope ?? 'chat' as const, ...(entry ? { extensionId: entry.extensionId } : {}) }\n const reply = (result: RpcResult): RpcResponseEnvelope => ({ ...result, meta })\n if (!entry)\n return reply(failure(RpcErrorType.Unavailable, `no extension provides \"${contract}\"`))\n if (!spec)\n return reply(failure(RpcErrorType.Unavailable, `\"${contract}\" has no method \"${method}\"`))\n if (authorize && !authorize(spec.scope))\n return reply(failure(RpcErrorType.Forbidden, `\"${contract}.${method}\" needs a token with the ${spec.scope} scope`))\n const callSignal = signal ?? new AbortController().signal\n const aborted = (): RpcResult => failure(RpcErrorType.Aborted, `the call to \"${contract}.${method}\" was aborted`)\n if (callSignal.aborted)\n return reply(aborted())\n try {\n return reply(await raceAbort(entry.handle(method, request.input, { signal: callSignal, caller }), callSignal, aborted))\n }\n catch (error) {\n return reply(failure(RpcErrorType.Internal, errorMessage(error)))\n }\n },\n\n emit(event) {\n const set = subscribers.get(`${event.contract}\\0${event.event}`)\n if (set)\n safeEach(set, event)\n safeEach(firehose, event)\n },\n\n subscribe(contract, event, listener) {\n const key = `${contract}\\0${event}`\n let set = subscribers.get(key)\n if (!set) {\n set = new Set()\n subscribers.set(key, set)\n }\n const own = set\n return listen(own, listener, () => {\n if (!own.size && subscribers.get(key) === own)\n subscribers.delete(key)\n })\n },\n\n onEvent: listener => listen(firehose, listener),\n onChange: listener => listen(changes, listener),\n has: contract => (entries.get(contract)?.length ?? 0) > 0,\n list: () => [...entries.values()].map((stack) => {\n const entry = stack.at(-1)!\n return {\n contract: entry.contractId,\n extensionId: entry.extensionId,\n directory: entry.directory,\n methods: Object.entries(entry.methods).map(([name, m]) => ({ name, scope: m.scope })),\n events: [...entry.events],\n }\n }),\n }\n}\n","/**\n * `ctx.rpc`: implement contracts and call them. A per-extension view over\n * the process-wide {@link RpcRouter}. Inputs, outputs, declared error data\n * and event data are validated against the contract's schemas on the\n * implementing side, so every caller (in-process or remote) gets the same\n * checks.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcCallContext, RpcClient, RpcContract, RpcDomain, RpcError, RpcEvent, RpcEvents, RpcImplementation, RpcMethodSpec, RpcRegistration } from '../api/rpc'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RpcRouter, RpcRouterEntry } from './router'\nimport type { RpcCaller, RpcEventEnvelope, RpcResult } from './wire'\nimport { DisposedError } from '../api/core'\nimport { RpcCallError } from '../api/rpc'\nimport { assertOwnsId } from '../contracts/ids'\nimport { bindToOwner } from '../contracts/owned'\nimport { raceAbort } from './router'\nimport { checkSchema, errorMessage, isPlainRecord } from './schema'\nimport { RpcErrorType } from './wire'\n\n/** What the host tells the rpc domain about where the extension runs. */\nexport interface RpcDomainPort {\n /** The project the extension runs in. Stamped on its events; its calls prefer providers of the same directory. */\n readonly directory: string\n}\n\n/** Events a `subscribe` iterator keeps for a slow reader before it drops the oldest. */\nexport const RPC_SUBSCRIBE_BUFFER = 1024\n\nconst ACCESS_SCOPES: readonly unknown[] = ['chat', 'approve', 'admin'] satisfies readonly AccessScope[]\n\ntype AnyImpl = Record<string, (input: unknown, ctx: RpcCallContext<RpcMethodSpec>) => unknown>\n\nfunction isRpcError(value: unknown): value is RpcError {\n return typeof value === 'object' && value !== null && (value as { kind?: unknown }).kind === 'rpc-error'\n && typeof (value as { type?: unknown }).type === 'string'\n}\n\nfunction failure(type: string, message: string, data?: unknown): RpcResult {\n return { ok: false, error: data === undefined ? { type, message } : { type, message, data } }\n}\n\nfunction publicCaller(caller: RpcCaller): RpcCallContext<RpcMethodSpec>['caller'] {\n switch (caller.kind) {\n case 'extension': return { kind: 'extension', id: caller.id }\n case 'ui': return { kind: 'ui' }\n case 'client': return { kind: 'client', clientId: caller.clientId }\n }\n}\n\nfunction assertContract(what: string, contract: RpcContract): void {\n if (contract?.kind !== 'rpc' || typeof contract.id !== 'string')\n throw new TypeError(`${what}: not an RPC contract (use Rpc.define)`)\n if (Object.hasOwn(contract.methods, 'events'))\n throw new Error(`${what}: \"${contract.id}\" has a method named \"events\", which clients reserve for events`)\n for (const [name, spec] of Object.entries(contract.methods)) {\n if (Object.hasOwn(spec, 'internal'))\n throw new TypeError(`${what}: \"${contract.id}.${name}\" declares \"internal\", which no longer exists; set scope ('admin' for methods only the app should call)`)\n if (spec.scope !== undefined && !ACCESS_SCOPES.includes(spec.scope))\n throw new TypeError(`${what}: \"${contract.id}.${name}\" scope must be chat, approve or admin`)\n for (const type of Object.keys(spec.errors ?? {})) {\n if (type.startsWith('rpc.'))\n throw new Error(`${what}: \"${contract.id}.${name}\" declares error \"${type}\"; names starting with \"rpc.\" are reserved`)\n }\n }\n}\n\n/**\n * Creates the rpc domain of one extension (or one scope of it).\n *\n * @param deps - Extension id, owner, guard and logger.\n * @param router - The process-wide router, from `createRpcRouter`.\n * @param port - Where the extension runs.\n * @returns `ctx.rpc`.\n */\nexport function createRpcDomain(deps: DomainDeps, router: RpcRouter, port: RpcDomainPort): RpcDomain {\n const { extensionId, owner, guard, logger } = deps\n const self: RpcCaller = { kind: 'extension', id: extensionId }\n\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n\n function register<C extends RpcContract>(contract: C, impl: RpcImplementation<C>): RpcRegistration<C> {\n if (owner.disposed)\n throw new DisposedError('rpc.register')\n assertContract('rpc.register', contract)\n assertOwnsId('rpc.register', extensionId, contract.id)\n const methods = contract.methods as Readonly<Record<string, RpcMethodSpec>>\n const handlers = impl as unknown as AnyImpl\n for (const name of Object.keys(methods)) {\n if (typeof handlers[name] !== 'function')\n throw new TypeError(`rpc.register: \"${contract.id}\" has no implementation for \"${name}\"`)\n }\n\n const life = new AbortController()\n const label = (method: string): string => `rpc ${contract.id}.${method}`\n\n async function settleError(spec: RpcMethodSpec, method: string, error: RpcError): Promise<RpcResult> {\n const schema = spec.errors && Object.hasOwn(spec.errors, error.type) ? spec.errors[error.type] : undefined\n if (!schema)\n return failure(RpcErrorType.Internal, `\"${contract.id}.${method}\" returned undeclared error \"${error.type}\": ${error.message}`)\n const check = await checkSchema(schema, error.data)\n if (!check.ok)\n return failure(RpcErrorType.InvalidOutput, `\"${contract.id}.${method}\" error \"${error.type}\" data is invalid: ${check.message}`)\n return failure(error.type, error.message, check.value)\n }\n\n async function handle(method: string, input: unknown, hctx: { signal: AbortSignal, caller: RpcCaller }): Promise<RpcResult> {\n const spec = methods[method]!\n const inCheck = await checkSchema(spec.input, input)\n if (!inCheck.ok)\n return failure(RpcErrorType.InvalidInput, `\"${contract.id}.${method}\" input is invalid: ${inCheck.message}`)\n let thrown: unknown\n // The guard's signal aborts on its timeout; the caller's on abort; `life` when the provider is withdrawn.\n const run = guard.call(label(method), async (timeout) => {\n const ctx: RpcCallContext<RpcMethodSpec> = {\n signal: AbortSignal.any([hctx.signal, life.signal, timeout]),\n caller: publicCaller(hctx.caller),\n error: (type, message, data) => ({ kind: 'rpc-error', type, message, data }),\n }\n try {\n return { value: await handlers[method]!(inCheck.value, ctx) }\n }\n catch (error) {\n if (isRpcError(error))\n return { value: error as unknown }\n thrown = error\n throw error\n }\n })\n const withdrawn = Symbol('withdrawn')\n const settled = await raceAbort(run, life.signal, (): typeof withdrawn => withdrawn)\n if (settled === withdrawn)\n return failure(RpcErrorType.Unavailable, `\"${contract.id}\" was withdrawn during the call`)\n if (settled === undefined) {\n const why = thrown === undefined ? 'failed or timed out' : `threw: ${errorMessage(thrown)}`\n return failure(RpcErrorType.Internal, `\"${contract.id}.${method}\" ${why}`)\n }\n if (isRpcError(settled.value))\n return settleError(spec, method, settled.value)\n const outCheck = await checkSchema(spec.output, settled.value)\n if (!outCheck.ok)\n return failure(RpcErrorType.InvalidOutput, `\"${contract.id}.${method}\" output is invalid: ${outCheck.message}`)\n return { ok: true, output: outCheck.value }\n }\n\n const entry: RpcRouterEntry = {\n contractId: contract.id,\n extensionId,\n directory: port.directory,\n methods: Object.fromEntries(Object.entries(methods).map(([name, spec]) => [name, { scope: spec.scope ?? 'chat' }])),\n events: Object.keys(contract.events),\n handle,\n }\n const routed = router.register(entry)\n let disposed = false\n let queue: Promise<void> | undefined\n\n function deliver(event: string, data: unknown): void {\n if (disposed)\n return\n const envelope: RpcEventEnvelope = {\n type: `rpc.${contract.id}.${event}`,\n contract: contract.id,\n event,\n data: data as Record<string, unknown>,\n location: { directory: port.directory },\n extensionId,\n }\n router.emit(envelope)\n }\n\n function emit(event: string, data: unknown): void {\n if (disposed)\n return\n const spec = Object.hasOwn(contract.events, event) ? contract.events[event] : undefined\n if (!spec)\n throw new Error(`rpc emit: \"${contract.id}\" has no event \"${event}\"`)\n if (!isPlainRecord(data))\n throw new TypeError(`rpc emit: \"${contract.id}.${event}\" data must be an object`)\n const check = checkSchema(spec.schema, data)\n if (!queue && !(check instanceof Promise)) {\n if (!check.ok)\n throw new TypeError(`rpc emit: \"${contract.id}.${event}\" data is invalid: ${check.message}`)\n deliver(event, check.value)\n return\n }\n // An async validator (or one still pending ahead) keeps emit order by queueing.\n const next: Promise<void> = (queue ?? Promise.resolve()).then(async () => {\n const result = await check\n if (result.ok)\n deliver(event, result.value)\n else\n logger.warn(`rpc emit: \"${contract.id}.${event}\" data is invalid, dropped: ${result.message}`, { extensionId })\n })\n queue = next\n void next.then(() => {\n if (queue === next)\n queue = undefined\n })\n }\n\n const handle$ = owned(() => {\n disposed = true\n life.abort()\n routed.dispose()\n })\n return {\n events: { emit: emit as RpcRegistration<C>['events']['emit'] },\n dispose: () => handle$.dispose(),\n }\n }\n\n function client<C extends RpcContract>(contract: C): RpcClient<C> {\n assertContract('rpc.client', contract)\n const out: Record<string, unknown> = {}\n for (const method of Object.keys(contract.methods)) {\n out[method] = async (input: unknown, opts?: { signal?: AbortSignal }) => {\n const signal = opts?.signal ? AbortSignal.any([opts.signal, owner.signal]) : owner.signal\n const request = input === undefined\n ? { contract: contract.id, method, directory: port.directory }\n : { contract: contract.id, method, input, directory: port.directory }\n const response = await router.call(request, { caller: self, signal })\n if (response.ok)\n return response.output\n throw new RpcCallError(response.error.type, response.error.message, response.error.data)\n }\n }\n out.events = clientEvents(deps, router, contract)\n return out as RpcClient<C>\n }\n\n return { register, client }\n}\n\n/** The event side of a client: guarded listeners and buffered iterators, ended with the owner. */\nfunction clientEvents(deps: DomainDeps, router: RpcRouter, contract: RpcContract): RpcEvents<RpcContract['events']> {\n const { extensionId, owner, guard, logger } = deps\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n return {\n on(name, listener) {\n if (owner.disposed)\n throw new DisposedError('rpc events.on')\n const label = `rpc event ${contract.id}.${name}`\n const sub = router.subscribe(contract.id, name, event => guard.callSync(label, () => listener(toEvent(event))))\n return owned(() => sub.dispose())\n },\n subscribe(name) {\n return {\n [Symbol.asyncIterator](): AsyncIterator<RpcEvent<unknown>> {\n const buffer: RpcEvent<unknown>[] = []\n let wake: (() => void) | undefined\n let done = owner.disposed\n let dropped = 0\n let sub: Disposable | undefined\n const finish = (): void => {\n done = true\n sub?.dispose()\n sub = undefined\n wake?.()\n }\n if (!done) {\n const routed = router.subscribe(contract.id, name, (event) => {\n if (buffer.length >= RPC_SUBSCRIBE_BUFFER) {\n buffer.shift()\n if (dropped++ === 0)\n logger.warn(`rpc subscribe: \"${contract.id}.${name}\" reader is slow, dropping oldest events`, { extensionId })\n }\n buffer.push(toEvent(event))\n wake?.()\n })\n sub = owned(() => {\n routed.dispose()\n finish()\n })\n }\n return {\n async next() {\n while (true) {\n if (buffer.length)\n return { value: buffer.shift()!, done: false }\n if (done)\n return { value: undefined, done: true }\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n }\n },\n async return() {\n finish()\n buffer.length = 0\n return { value: undefined, done: true }\n },\n }\n },\n }\n },\n }\n}\n\nfunction toEvent(envelope: RpcEventEnvelope): RpcEvent<unknown> {\n return { type: envelope.type, data: envelope.data, location: envelope.location }\n}\n","/**\n * Guards: how the runtime calls extension code (extension API).\n *\n * Extensions run in-process and are trusted, so the guard does not sandbox.\n * It bounds and attributes: every callback runs with a timeout, a throw or a\n * timeout is logged against the extension and turns into a fallback, and an\n * error budget (N failures in a sliding window) trips once so the host can\n * disable the extension with the reason. A {@link StallMonitor} times the\n * synchronous part of each callback and names the extension that blocked the\n * event loop. Every call holds a lease on the extension's owner while it\n * runs (`lease`), so an unload waits for it before tearing down what it uses;\n * once the extension is unloaded a call returns its fallback without running.\n */\n\nimport type { Logger } from '../../logger'\nimport type { Guard } from './deps'\nimport { errorMessage } from '../../errors'\nimport { DisposedError } from '../api/core'\n\n/** Default bound of one async extension callback. Matches the setup bound (`SETUP_TIMEOUT_MS`, `runtime/lifecycle.ts`). */\nexport const DEFAULT_CALLBACK_TIMEOUT_MS = 10_000\n\n/** Default synchronous run time that counts as an event-loop stall. */\nexport const DEFAULT_STALL_THRESHOLD_MS = 500\n\n/** How many failures in how long trip the guard. */\nexport interface ErrorBudget {\n /** Failures that trip the guard. */\n maxFailures: number\n /** Sliding window the failures are counted in, in ms. */\n windowMs: number\n}\n\n/** Default {@link ErrorBudget}: 5 failures within a minute. */\nexport const DEFAULT_ERROR_BUDGET: Readonly<ErrorBudget> = { maxFailures: 5, windowMs: 60_000 }\n\n/** An extension callback that threw or timed out, attributed to its extension. */\nexport class ExtensionCallbackError extends Error {\n /** The extension the callback belongs to. */\n readonly extensionId: string\n /** What was called (`'tools.search.execute'`, `'setup'`). */\n readonly label: string\n /** `'error'`: it threw or rejected. `'timeout'`: it did not settle in time. */\n readonly kind: 'error' | 'timeout'\n\n /**\n * @param extensionId - The extension.\n * @param label - What was called.\n * @param kind - Threw or timed out.\n * @param message - Human-readable detail.\n * @param cause - The original error, when it threw.\n */\n constructor(extensionId: string, label: string, kind: 'error' | 'timeout', message: string, cause?: unknown) {\n super(`[${extensionId}] ${label}: ${message}`, cause === undefined ? undefined : { cause })\n this.name = 'ExtensionCallbackError'\n this.extensionId = extensionId\n this.label = label\n this.kind = kind\n }\n}\n\n/** One failure counted in the budget. */\nexport interface GuardFailure {\n /** The attributed error. */\n error: ExtensionCallbackError\n /** When it happened, from the guard's clock. */\n at: number\n}\n\n/** Why a guard tripped. The host disables the extension and shows `reason` in Settings. */\nexport interface GuardTrip {\n /** The extension to disable. */\n extensionId: string\n /** One line for Settings, e.g. `5 errors in 60s. Last: tools.x.execute: boom`. */\n reason: string\n /** The failures in the window that tripped it, oldest first. */\n failures: readonly GuardFailure[]\n}\n\n/** A synchronous callback that ran past the stall threshold. */\nexport interface StallReport {\n /** The extension whose callback was running. */\n extensionId: string\n /** What was called. */\n label: string\n /** Time spent in the callback itself, nested guarded callbacks excluded, in ms. */\n durationMs: number\n}\n\n/** Times guarded synchronous callbacks and reports the ones that block the event loop. */\nexport interface StallMonitor {\n /**\n * Runs `fn` as `extensionId`'s callback and returns its result (or\n * rethrows). When its own run time reaches the threshold, reports a stall\n * against it. Nested runs are attributed to the innermost extension.\n */\n run: <T>(extensionId: string, label: string, fn: () => T) => T\n /** The innermost guarded callback running now, if any. */\n readonly current: { extensionId: string, label: string } | undefined\n}\n\n/** Options for {@link createStallMonitor}. */\nexport interface StallMonitorOptions {\n /** Own run time that counts as a stall, in ms. Default {@link DEFAULT_STALL_THRESHOLD_MS}. */\n thresholdMs?: number\n /** Clock in ms. Default `performance.now`. A test seam. */\n now?: () => number\n /** Receives each stall. Errors it throws are dropped. */\n onStall: (report: StallReport) => void\n}\n\n/**\n * Makes a stall monitor. Share one across every extension of a host so a\n * call from one extension into another is split correctly.\n *\n * @param options - Threshold, clock and the stall sink.\n * @returns The monitor.\n */\nexport function createStallMonitor(options: StallMonitorOptions): StallMonitor {\n const thresholdMs = options.thresholdMs ?? DEFAULT_STALL_THRESHOLD_MS\n const now = options.now ?? (() => performance.now())\n const stack: { extensionId: string, label: string, nested: number }[] = []\n return {\n get current() {\n const top = stack.at(-1)\n return top ? { extensionId: top.extensionId, label: top.label } : undefined\n },\n run(extensionId, label, fn) {\n const frame = { extensionId, label, nested: 0 }\n stack.push(frame)\n const start = now()\n try {\n return fn()\n }\n finally {\n const total = now() - start\n stack.pop()\n const parent = stack.at(-1)\n if (parent)\n parent.nested += total\n const own = total - frame.nested\n if (own >= thresholdMs) {\n try {\n options.onStall({ extensionId, label, durationMs: own })\n }\n catch {}\n }\n }\n },\n }\n}\n\nconst TIMED_OUT = Symbol('timed out')\n\n/** Options for {@link createGuard}. */\nexport interface GuardOptions {\n /** The extension every failure is attributed to. */\n extensionId: string\n /** Where failures, stalls and the trip are logged. */\n logger: Logger\n /** Failures that trip the guard. Default {@link DEFAULT_ERROR_BUDGET}; `false` never trips. */\n budget?: Partial<ErrorBudget> | false\n /** Called once when the budget is spent. The host disables the extension with `trip.reason`. */\n onTrip?: (trip: GuardTrip) => void\n /** Called on every failure, before the budget check. */\n onFailure?: (failure: GuardFailure) => void\n /** Default bound of `call`, in ms. Default {@link DEFAULT_CALLBACK_TIMEOUT_MS}. `Infinity` means none. */\n timeoutMs?: number\n /** A shared stall monitor. Default: a private one that logs stalls as warnings and calls `onStall`. */\n stalls?: StallMonitor\n /** Receives stalls when the guard makes its own monitor. */\n onStall?: (report: StallReport) => void\n /** Clock for the budget window, in ms. Default `Date.now`. A test seam. */\n now?: () => number\n /**\n * Takes a lease on the extension's owner for one call (`RuntimeOwner.lease`):\n * throws `DisposedError` once it is disposed. Absent: calls are not tracked.\n */\n lease?: (label: string, opts: { timeoutMs?: number }) => () => void\n}\n\n/** A {@link Guard} with its budget state. */\nexport interface RuntimeGuard extends Guard {\n /** The extension the guard attributes to. */\n readonly extensionId: string\n /** Set once the budget is spent. A tripped guard no longer runs callbacks: `call` (except `teardown` calls) and `callSync` return their fallback. */\n readonly tripped: GuardTrip | undefined\n /** The failures inside the current window, oldest first. */\n readonly failures: readonly GuardFailure[]\n /** Counts an error the host caught itself (a rejected cleanup, a broken event handler) against the extension. */\n report: (label: string, error: unknown) => void\n}\n\n/**\n * Makes the guard for one extension.\n *\n * @param options - Extension id, logger, budget, timeouts and sinks.\n * @returns The guard.\n */\nexport function createGuard(options: GuardOptions): RuntimeGuard {\n const { extensionId, logger } = options\n const now = options.now ?? Date.now\n const defaultTimeout = options.timeoutMs ?? DEFAULT_CALLBACK_TIMEOUT_MS\n const budget = options.budget === false ? undefined : { ...DEFAULT_ERROR_BUDGET, ...options.budget }\n const stalls = options.stalls ?? createStallMonitor({\n onStall: (report) => {\n logger.warn(`${report.label} blocked the event loop for ${Math.round(report.durationMs)}ms`, { extension: report.extensionId, label: report.label, durationMs: report.durationMs })\n options.onStall?.(report)\n },\n })\n let failures: GuardFailure[] = []\n let tripped: GuardTrip | undefined\n\n const prune = (): void => {\n if (budget)\n failures = failures.filter(f => now() - f.at < budget.windowMs)\n }\n\n const fail = (error: ExtensionCallbackError): void => {\n logger.error(error.message, { extension: extensionId, label: error.label, kind: error.kind, ...(error.cause !== undefined ? { error: errorMessage(error.cause) } : {}) })\n const failure: GuardFailure = { error, at: now() }\n failures.push(failure)\n prune()\n try {\n options.onFailure?.(failure)\n }\n catch {}\n if (!budget || tripped || failures.length < budget.maxFailures)\n return\n const last = error.message.replace(`[${extensionId}] `, '')\n tripped = {\n extensionId,\n reason: `${failures.length} errors in ${Math.round(budget.windowMs / 1000)}s. Last: ${last}`,\n failures: [...failures],\n }\n logger.error(`error budget spent, disabling: ${tripped.reason}`, { extension: extensionId })\n try {\n options.onTrip?.(tripped)\n }\n catch {}\n }\n\n const threw = (label: string, cause: unknown): void => {\n fail(new ExtensionCallbackError(extensionId, label, 'error', errorMessage(cause), cause))\n }\n\n const lease = (label: string, opts: { timeoutMs?: number } = {}): (() => void) =>\n options.lease ? options.lease(`[${extensionId}] ${label}`, opts) : () => {}\n\n /** A lease for a guarded call, or `undefined` when the extension is unloaded (the call does not run). */\n const tryLease = (label: string, timeoutMs?: number): (() => void) | undefined => {\n try {\n return lease(label, timeoutMs !== undefined && Number.isFinite(timeoutMs) ? { timeoutMs } : {})\n }\n catch (error) {\n if (error instanceof DisposedError)\n return undefined\n throw error\n }\n }\n\n return {\n extensionId,\n get tripped() { return tripped },\n get failures() {\n prune()\n return [...failures]\n },\n\n report: threw,\n lease,\n\n async call<T>(label: string, fn: (signal: AbortSignal) => T | Promise<T>, opts: { timeoutMs?: number, fallback?: T, teardown?: boolean } = {}): Promise<T | undefined> {\n if (tripped && !opts.teardown)\n return opts.fallback\n // A teardown call runs while the owner tears down: it holds no lease.\n const release = opts.teardown ? () => {} : tryLease(label, opts.timeoutMs ?? defaultTimeout)\n if (!release)\n return opts.fallback\n try {\n return await runCall(label, fn, opts)\n }\n finally {\n release()\n }\n },\n\n callSync<T>(label: string, fn: () => T, opts: { fallback?: T } = {}): T | undefined {\n if (tripped)\n return opts.fallback\n const release = tryLease(label)\n if (!release)\n return opts.fallback\n let value: T\n try {\n value = stalls.run(extensionId, label, fn)\n }\n catch (error) {\n release()\n threw(label, error)\n return opts.fallback\n }\n if (isThenable(value)) {\n Promise.resolve(value).catch(error => threw(label, error)).finally(release)\n return value\n }\n release()\n return value\n },\n }\n\n async function runCall<T>(label: string, fn: (signal: AbortSignal) => T | Promise<T>, opts: { timeoutMs?: number, fallback?: T }): Promise<T | undefined> {\n const controller = new AbortController()\n let result: T | Promise<T>\n try {\n result = stalls.run(extensionId, label, () => fn(controller.signal))\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n if (!isThenable(result))\n return result\n const pending = Promise.resolve(result)\n const timeoutMs = opts.timeoutMs ?? defaultTimeout\n if (!Number.isFinite(timeoutMs)) {\n try {\n return await pending\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(resolve, timeoutMs, TIMED_OUT)\n })\n try {\n const value = await Promise.race([pending, timedOut])\n if (value !== TIMED_OUT)\n return value\n const message = `timed out after ${timeoutMs}ms`\n controller.abort(new Error(`${label} ${message}`))\n // A late rejection was already accounted for by the timeout.\n pending.catch(() => {})\n fail(new ExtensionCallbackError(extensionId, label, 'timeout', message))\n return opts.fallback\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n finally {\n clearTimeout(timer)\n }\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof (value as PromiseLike<unknown>).then === 'function'\n}\n","/**\n * The agents catalog: `ctx.agents`. Two sections, agent profiles and\n * spawnable sub-agents, plus the default profile id, all edited by one\n * {@link AgentEditor} per transform.\n */\n\nimport type { AgentProfile } from '../../chat/agents'\nimport type { ExtensionSubagentDef } from '../../tools/spawn'\nimport type { AgentEditor, AgentsDomain, Disposable, ItemOrigin } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** Supplies the base profiles, sub-agents and default. The host connects config and built-ins. */\nexport interface AgentsCatalogPort extends RefreshablePort {\n /** Built-in and config profiles. */\n profiles: () => readonly Sourced<AgentProfile>[]\n /** The host's base sub-agents (the spawn tool's registry). */\n subagents?: () => readonly Sourced<ExtensionSubagentDef>[]\n /** The configured default profile id. */\n defaultId?: () => string | undefined\n}\n\n/** Catalog-wide agent state. */\nexport interface AgentsState {\n /** The default profile id. */\n defaultId?: string\n /** The extension whose transform set the default. */\n defaultSetBy?: string\n}\n\n/** Section item types of the agents catalog. */\nexport interface AgentsSections {\n /** Agent profiles, by `id`. */\n profiles: AgentProfile\n /** Spawnable sub-agents, by `name`. */\n subagents: ExtensionSubagentDef\n}\n\n/** A replayed agents value. `state.defaultId` is cleared when its profile is gone. */\nexport type AgentsValue = CatalogValue<AgentsSections, AgentsState>\n\n/** The shared agents catalog a host builds once. */\nexport interface AgentsCatalog {\n /** The replayed value. */\n read: () => AgentsValue\n /** Adds a profile. */\n registerProfile: (profile: AgentProfile, origin: ItemOrigin) => Disposable\n /** Adds a sub-agent. */\n registerSubagent: (def: ExtensionSubagentDef, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createAgentsEngine>\n}\n\nfunction createAgentsEngine(port: AgentsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<AgentsSections, AgentsState, void>({\n ...options,\n name: 'agents',\n sections: {\n profiles: { key: profile => profile.id, base: () => port.profiles() },\n subagents: { key: def => def.name, base: () => port.subagents?.() ?? [] },\n },\n state: {\n base: () => {\n const defaultId = port.defaultId?.()\n return defaultId === undefined ? {} : { defaultId }\n },\n clone: state => ({ ...state }),\n },\n })\n}\n\n/** Builds the {@link AgentEditor} over one transform's draft. */\nfunction agentEditor(draft: CatalogDraft<AgentsSections, AgentsState, void>): AgentEditor {\n const profiles = draft.sections.profiles\n const subagents = draft.sections.subagents\n return {\n list: profiles.list,\n get: profiles.get,\n origin: profiles.origin,\n add: profiles.add,\n update: profiles.update,\n remove: profiles.remove,\n default: {\n get: () => {\n draft.assertOpen()\n return draft.state.defaultId\n },\n set: (id) => {\n draft.assertOpen()\n if (!profiles.get(id))\n throw new Error(`agents.default.set: no profile \"${id}\"`)\n draft.state = { defaultId: id, defaultSetBy: draft.extensionId }\n },\n },\n subagents: {\n list: subagents.list,\n get: subagents.get,\n origin: subagents.origin,\n add: subagents.add,\n update: subagents.update,\n remove: subagents.remove,\n override: (name, override) => {\n if (typeof override !== 'function')\n throw new TypeError('agents.subagents.override: override must be a function')\n const current = subagents.cloneOf(name)\n let def: Omit<ExtensionSubagentDef, 'name'> | undefined\n if (current) {\n const { name: _name, ...rest } = current\n def = rest\n }\n const next = override(def)\n if (next === undefined)\n subagents.remove(name)\n else\n subagents.replace({ ...next, name })\n },\n },\n }\n}\n\n/** Creates the shared agents catalog. */\nexport function createAgentsCatalog(port: AgentsCatalogPort, options: CatalogOptions = {}): AgentsCatalog {\n const engine = createAgentsEngine(port, options)\n return {\n engine,\n read: () => {\n const value = engine.read()\n const { defaultId } = value.state\n if (defaultId === undefined || value.sections.profiles.get(defaultId))\n return value\n return Object.freeze({ ...value, state: Object.freeze({}) })\n },\n registerProfile: (profile, origin) => engine.register('profiles', profile, origin),\n registerSubagent: (def, origin) => engine.register('subagents', def, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.agents` over the shared catalog. */\nexport function createAgentsDomain(deps: DomainDeps, catalog: AgentsCatalog): AgentsDomain {\n return {\n register(profile) {\n if (!profile || typeof profile.id !== 'string' || profile.id.length === 0)\n throw new TypeError('agents.register: profile needs a non-empty id')\n return owned(deps, 'agents.register', () => catalog.registerProfile(profile, extensionOrigin(deps)))\n },\n subagents: {\n register(def) {\n if (!def || typeof def.name !== 'string' || def.name.length === 0)\n throw new TypeError('agents.subagents.register: def needs a non-empty name')\n return owned(deps, 'agents.subagents.register', () => catalog.registerSubagent(def, extensionOrigin(deps)))\n },\n },\n transform: fn => addTransform(deps, catalog.engine, 'agents.transform', agentEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.profiles.items,\n }\n}\n","/**\n * The MCP server catalog: `ctx.mcp`. Server configs replay like every\n * catalog; connection status and calls go to the host, which connects the\n * replayed configs.\n */\n\nimport type { McpServerConfig } from '../../mcp'\nimport type { CatalogEditor, Disposable, ItemOrigin, McpDomain, McpServerStatus } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** A server status as a host reports it. The catalog fills `url`, `command` and `toolPrefix` the host leaves out. */\nexport type McpPortStatus = Omit<McpServerStatus, 'toolPrefix'> & { toolPrefix?: string }\n\n/**\n * The prefix the agent gives a server's tools: `mcp_<name>_` (the\n * canonical naming of `connectMcpServers`, see `src/agent-mcp-naming.ts`).\n *\n * @param server - The server name as configured.\n * @returns The prefix of its canonical tool names.\n */\nexport function mcpToolPrefix(server: string): string {\n return `mcp_${server}_`\n}\n\n/**\n * A host's status with the catalog's config data: `url` and `command` from\n * the replayed server config when the host gave none, and `toolPrefix`.\n *\n * @param status - What the host reported.\n * @param config - The server's replayed config, when the catalog has it.\n * @returns The status `ctx.mcp.list` reports.\n */\nexport function completeMcpStatus(status: McpPortStatus, config: McpServerConfig | undefined): McpServerStatus {\n const url = status.url ?? config?.url\n const command = status.command ?? config?.command\n return {\n ...status,\n ...(url ? { url } : {}),\n ...(command ? { command } : {}),\n toolPrefix: status.toolPrefix ?? mcpToolPrefix(status.name),\n }\n}\n\n/** Supplies config servers and talks to live connections. Each host implements it. */\nexport interface McpCatalogPort extends RefreshablePort {\n /** Servers from config files and built-ins. */\n servers: () => readonly Sourced<McpServerConfig>[]\n /** Status of every connection the host holds. */\n status: () => readonly McpPortStatus[]\n /** Calls a tool of a connected server. */\n call: (server: string, tool: string, args: Record<string, unknown> | undefined, opts: { timeoutMs?: number, signal?: AbortSignal }) => Promise<{ content: unknown, isError: boolean }>\n}\n\n/** Section item types of the MCP catalog. */\nexport interface McpSections {\n /** Server configs, by `name`. */\n servers: McpServerConfig\n}\n\n/** A replayed MCP value. */\nexport type McpValue = CatalogValue<McpSections, undefined>\n\n/** The shared MCP catalog a host builds once. */\nexport interface McpCatalog {\n /** The replayed server configs. */\n read: () => McpValue\n /** Adds a server config. */\n register: (server: McpServerConfig, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change (the host reconnects). */\n subscribe: (listener: () => void) => () => void\n /** The port, for status and calls. */\n readonly port: McpCatalogPort\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createMcpEngine>\n}\n\nfunction createMcpEngine(port: McpCatalogPort, options: CatalogOptions) {\n return createCatalogSet<McpSections, undefined, void>({\n ...options,\n name: 'mcp',\n sections: { servers: { key: server => server.name, base: () => port.servers() } },\n })\n}\n\n/** Creates the shared MCP catalog. */\nexport function createMcpCatalog(port: McpCatalogPort, options: CatalogOptions = {}): McpCatalog {\n const engine = createMcpEngine(port, options)\n return {\n engine,\n port,\n read: () => engine.read(),\n register: (server, origin) => engine.register('servers', server, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.mcp` over the shared catalog. */\nexport function createMcpDomain(deps: DomainDeps, catalog: McpCatalog): McpDomain {\n return {\n register(server) {\n if (!server || typeof server.name !== 'string' || server.name.length === 0)\n throw new TypeError('mcp.register: server needs a non-empty name')\n return owned(deps, 'mcp.register', () => catalog.register(server, extensionOrigin(deps)))\n },\n transform: fn => addTransform(deps, catalog.engine, 'mcp.transform', (draft): CatalogEditor<McpServerConfig> => {\n const { list, get, origin, add, update, remove } = draft.sections.servers\n return { list, get, origin, add, update, remove }\n }, fn),\n reload: catalog.reload,\n list: () => {\n const servers = catalog.read().sections.servers\n return catalog.port.status().map(status => completeMcpStatus(status, servers.get(status.name)))\n },\n call: (server, tool, args, opts = {}) => catalog.port.call(server, tool, args, opts),\n }\n}\n","/**\n * The skills catalog: `ctx.skills`. Skill configs, plus the set of skills\n * auto-activated at the start of every run (`autoinvoke`). Per-run choices\n * belong to `hooks.intercept('skills.activate')`, not here.\n */\n\nimport type { SkillConfig } from '../../skills'\nimport type { CatalogEditor, Disposable, ItemOrigin, SkillsDomain } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** Supplies discovered skills. The host connects skill discovery and plugins. */\nexport interface SkillsCatalogPort extends RefreshablePort {\n /** Discovered and built-in skills. */\n skills: () => readonly Sourced<SkillConfig>[]\n /** Names auto-activated before any transform (config). */\n autoinvoke?: () => readonly string[]\n}\n\n/** One auto-invoke decision. */\nexport interface AutoinvokeEntry {\n /** On or off. */\n readonly on: boolean\n /** The extension whose transform decided it; absent for the base. */\n readonly by?: string\n}\n\n/** Catalog-wide skill state: auto-invoke decisions by skill name. */\nexport interface SkillsState {\n /** Decisions by skill name. */\n autoinvoke: Record<string, AutoinvokeEntry>\n}\n\n/** Section item types of the skills catalog. */\nexport interface SkillsSections {\n /** Skills, by `name`. */\n skills: SkillConfig\n}\n\n/** A replayed skills value. */\nexport type SkillsValue = CatalogValue<SkillsSections, SkillsState>\n\n/** The editor a skills transform gets. */\nexport type SkillEditor = CatalogEditor<SkillConfig> & { autoinvoke: (name: string, on: boolean) => void }\n\n/** The shared skills catalog a host builds once. */\nexport interface SkillsCatalog {\n /** The replayed value. */\n read: () => SkillsValue\n /** Names of present skills to activate at the start of every run. */\n autoinvoked: () => readonly string[]\n /** Adds a skill. */\n register: (skill: SkillConfig, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createSkillsEngine>\n}\n\nfunction createSkillsEngine(port: SkillsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<SkillsSections, SkillsState, void>({\n ...options,\n name: 'skills',\n sections: { skills: { key: skill => skill.name, base: () => port.skills() } },\n state: {\n base: () => ({ autoinvoke: Object.fromEntries((port.autoinvoke?.() ?? []).map(name => [name, { on: true }])) }),\n clone: state => ({ autoinvoke: { ...state.autoinvoke } }),\n },\n })\n}\n\nfunction skillEditor(draft: CatalogDraft<SkillsSections, SkillsState, void>): SkillEditor {\n const { list, get, origin, add, update, remove } = draft.sections.skills\n return {\n list,\n get,\n origin,\n add,\n update,\n remove,\n autoinvoke: (name, on) => {\n draft.assertOpen()\n draft.state.autoinvoke[name] = { on, by: draft.extensionId }\n },\n }\n}\n\n/** Creates the shared skills catalog. */\nexport function createSkillsCatalog(port: SkillsCatalogPort, options: CatalogOptions = {}): SkillsCatalog {\n const engine = createSkillsEngine(port, options)\n return {\n engine,\n read: () => engine.read(),\n autoinvoked: () => {\n const value = engine.read()\n return Object.entries(value.state.autoinvoke)\n .filter(([name, entry]) => entry.on && value.sections.skills.get(name))\n .map(([name]) => name)\n },\n register: (skill, origin) => engine.register('skills', skill, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.skills` over the shared catalog. */\nexport function createSkillsDomain(deps: DomainDeps, catalog: SkillsCatalog): SkillsDomain {\n return {\n register(skill) {\n if (!skill || typeof skill.name !== 'string' || skill.name.length === 0)\n throw new TypeError('skills.register: skill needs a non-empty name')\n return owned(deps, 'skills.register', () => catalog.register(skill, extensionOrigin(deps)))\n },\n transform: fn => addTransform(deps, catalog.engine, 'skills.transform', skillEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.skills.items,\n }\n}\n","/**\n * The tools catalog: `ctx.tools`. The base is the tool set of the agent\n * being built (built-ins and MCP tools), which differs per session, so a\n * read takes the phase, the session and optionally that base. Extension\n * tools are added after it, then transforms replay with a {@link ToolEditor}.\n */\n\nimport type { ToolResultMetadata } from '../../types'\nimport type { Disposable, ItemOrigin, NamedTool, ToolEditor, ToolMetadataNamespace, ToolsDomain } from '../api'\nimport type { Json } from '../api/storage'\nimport type { DomainDeps, Guard } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogOptions, CatalogValue, SectionValue, Sourced } from './engine'\nimport { clonePlain } from './clone'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet, once } from './engine'\n\n/** What a tools read is for. */\nexport interface ToolCatalogContext {\n /** `'pre-run'` when listing before a run (pickers, Settings), `'run'` when building the run. */\n readonly phase: 'pre-run' | 'run'\n /** The session the tools are for. */\n readonly sessionId?: string\n /** The agent's own tools for this read. Default: the port's base. Reads with a base are not memoized. */\n readonly base?: readonly Sourced<NamedTool>[]\n}\n\n/** Supplies the base tools. The host connects the agent's tool set. */\nexport interface ToolsCatalogPort extends RefreshablePort {\n /** Built-in and MCP tools for a context with no explicit base. */\n base: (context: { phase: 'pre-run' | 'run', sessionId?: string }) => readonly Sourced<NamedTool>[]\n}\n\n/** An extension's tool-result metadata namespace. */\nexport interface ToolMetadataEntry {\n /** The namespace (the key under `ToolResultMetadata`). */\n readonly namespace: string\n /** The extension that owns it. */\n readonly extensionId: string\n /** The spec as registered. Call it through {@link ToolsCatalog.metadata}, which guards it. */\n readonly spec: ToolMetadataNamespace\n}\n\n/** The shared tools catalog a host builds once. */\nexport interface ToolsCatalog {\n /** Replays for a context. Default context: `{ phase: 'pre-run' }`. */\n read: (context?: ToolCatalogContext) => SectionValue<NamedTool> & { readonly failures: CatalogValue<{ tools: NamedTool }, undefined>['failures'] }\n /** Adds an extension's tool. */\n register: (tool: NamedTool, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /** Tool-result metadata namespaces. */\n metadata: {\n /** Every registered namespace. */\n list: () => readonly ToolMetadataEntry[]\n /** Context-panel rows for a namespace, through its extension's guard. */\n contextRows: (namespace: string, entries: readonly { value: Json }[]) => readonly { label: string, value: string }[] | undefined\n /** Compact summary of one value, through its extension's guard. */\n summarize: (namespace: string, metadata: ToolResultMetadata) => Json | undefined\n }\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createToolsEngine>\n /**\n * Registers a metadata namespace for the domain factory.\n *\n * @internal\n */\n registerMetadata: (entry: ToolMetadataEntry, guard: Guard) => Disposable\n}\n\n/**\n * Copies a tool for `update`. Own property descriptors are kept, so getters\n * (live state on the spawn tool) stay live; the spec is deep-copied.\n */\nfunction cloneTool(tool: NamedTool): NamedTool {\n const def = Object.create(Object.getPrototypeOf(tool.def), Object.getOwnPropertyDescriptors(tool.def)) as NamedTool['def']\n def.spec = clonePlain(tool.def.spec)\n return { name: tool.name, def }\n}\n\nfunction createToolsEngine(port: ToolsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<{ tools: NamedTool }, undefined, ToolCatalogContext>({\n ...options,\n name: 'tools',\n sections: {\n tools: {\n key: tool => tool.name,\n base: context => context.base ?? port.base({ phase: context.phase, ...(context.sessionId !== undefined ? { sessionId: context.sessionId } : {}) }),\n clone: cloneTool,\n },\n },\n contextKey: context => context.base ? undefined : `${context.phase}\\u0000${context.sessionId ?? ''}`,\n })\n}\n\n/** Creates the shared tools catalog. */\nexport function createToolsCatalog(port: ToolsCatalogPort, options: CatalogOptions = {}): ToolsCatalog {\n const engine = createToolsEngine(port, options)\n const namespaces = new Map<string, { entry: ToolMetadataEntry, guard: Guard }>()\n return {\n engine,\n read: (context = { phase: 'pre-run' }) => {\n const value = engine.read(context)\n return Object.freeze({ ...value.sections.tools, failures: value.failures })\n },\n register: (tool, origin) => engine.register('tools', tool, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n registerMetadata(entry, guard) {\n const owner = namespaces.get(entry.namespace)\n if (owner && owner.entry.extensionId !== entry.extensionId)\n throw new Error(`tools.metadata: namespace \"${entry.namespace}\" belongs to \"${owner.entry.extensionId}\"`)\n const record = { entry, guard }\n namespaces.set(entry.namespace, record)\n return once(() => {\n if (namespaces.get(entry.namespace) === record)\n namespaces.delete(entry.namespace)\n })\n },\n metadata: {\n list: () => [...namespaces.values()].map(record => record.entry),\n contextRows(namespace, entries) {\n const record = namespaces.get(namespace)\n const fn = record?.entry.spec.contextRows\n if (!record || !fn)\n return undefined\n return record.guard.callSync(`tools.metadata.${namespace}.contextRows`, () => fn({ namespace, entries }))\n },\n summarize(namespace, metadata) {\n const record = namespaces.get(namespace)\n const fn = record?.entry.spec.summarize\n if (!record || !fn)\n return undefined\n return record.guard.callSync(`tools.metadata.${namespace}.summarize`, () => fn(metadata))\n },\n },\n }\n}\n\n/**\n * `def` whose `execute` holds a lease on the extension (`Guard.lease`) while\n * it runs: an agent that took the tool before an unload finishes the call\n * on live domains. A call that starts after the unload throws\n * `DisposedError`. Same prototype and properties, like {@link cloneTool}.\n */\nfunction leasedTool(deps: DomainDeps, name: string, def: NamedTool['def']): NamedTool['def'] {\n const lease = deps.guard.lease\n if (!lease)\n return def\n const execute = def.execute\n const wrapped = Object.create(Object.getPrototypeOf(def), Object.getOwnPropertyDescriptors(def)) as NamedTool['def']\n wrapped.execute = function (this: unknown, ...args: Parameters<typeof execute>) {\n const release = lease(`tool ${name}`)\n let result: ReturnType<typeof execute>\n try {\n result = execute.apply(this, args)\n }\n catch (error) {\n release()\n throw error\n }\n if (result && typeof (result as PromiseLike<unknown>).then === 'function')\n return (result as Promise<Awaited<typeof result>>).finally(release) as typeof result\n release()\n return result\n }\n return wrapped\n}\n\n/** Creates one extension's `ctx.tools` over the shared catalog. */\nexport function createToolsDomain(deps: DomainDeps, catalog: ToolsCatalog): ToolsDomain {\n return {\n register(name, def) {\n if (typeof name !== 'string' || name.length === 0)\n throw new TypeError('tools.register: name must be a non-empty string')\n if (!def || typeof def.execute !== 'function')\n throw new TypeError(`tools.register: \"${name}\" needs a ToolDef with execute`)\n return owned(deps, 'tools.register', () => catalog.register({ name, def: leasedTool(deps, name, def) }, extensionOrigin(deps)))\n },\n metadata(namespace, spec) {\n if (typeof namespace !== 'string' || namespace.length === 0)\n throw new TypeError('tools.metadata: namespace must be a non-empty string')\n return owned(deps, 'tools.metadata', () => catalog.registerMetadata({ namespace, extensionId: deps.extensionId, spec }, deps.guard))\n },\n transform: fn => addTransform(deps, catalog.engine, 'tools.transform', (draft): ToolEditor => {\n const tools = draft.sections.tools\n return {\n phase: draft.context.phase,\n ...(draft.context.sessionId !== undefined ? { sessionId: draft.context.sessionId } : {}),\n list: tools.list,\n get: tools.get,\n origin: tools.origin,\n add: tools.add,\n update: tools.update,\n remove: tools.remove,\n }\n }, fn),\n reload: catalog.reload,\n list: () => catalog.read().items,\n }\n}\n","/**\n * `ctx.contracts`: provide and use contracts, add to and list registries.\n * A per-extension view over the process-wide {@link ContractRegistry}.\n * Everything registered or subscribed through it ends with the owner.\n */\n\nimport type { ContractsDomain, ContractToken, RegistryToken } from '../api/contracts'\nimport type { Disposable, LiveAccessor, Readable } from '../api/core'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { ContractRegistry } from './registry'\nimport { DisposedError } from '../api/core'\nimport { assertOwnsId } from './ids'\nimport { bindToOwner } from './owned'\n\n/**\n * Creates the contracts domain of one extension (or one scope of it).\n *\n * @param deps - Extension id, owner, guard and logger.\n * @param registry - The process-wide store, from `createContractRegistry`.\n * @returns `ctx.contracts`.\n */\nexport function createContractsDomain(deps: DomainDeps, registry: ContractRegistry): ContractsDomain {\n const { extensionId, owner, guard } = deps\n const accessors = new Map<string, LiveAccessor<unknown>>()\n const lists = new Map<string, Readable<readonly unknown[]>>()\n\n function live(what: string): void {\n if (owner.disposed)\n throw new DisposedError(what)\n }\n\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n\n function guardedSubscribe<T>(what: string, watch: (listener: (value: T) => void) => () => void, listener: (value: T) => void): () => void {\n live(what)\n const sub = owned(watch(value => guard.callSync(what, () => listener(value))))\n return () => sub.dispose()\n }\n\n return {\n provide<T>(token: ContractToken<T>, impl: T): Disposable {\n live('contracts.provide')\n assertOwnsId('contracts.provide', extensionId, token.id)\n const provision = registry.provide(token.id, extensionId, impl)\n return owned(() => provision.dispose())\n },\n use<T>(token: ContractToken<T>): LiveAccessor<T> {\n let accessor = accessors.get(token.id)\n if (!accessor) {\n const id = token.id\n accessor = {\n get: () => registry.live(id),\n value: () => {\n const current = registry.live(id)\n return current.status === 'active' ? current.value : undefined\n },\n subscribe: listener => guardedSubscribe(`contracts.use(${id})`, l => registry.watch(id, l), listener),\n }\n accessors.set(id, accessor)\n }\n return accessor as LiveAccessor<T>\n },\n add<T>(token: RegistryToken<T>, item: T): Disposable {\n live('contracts.add')\n const entry = registry.add(token.id, extensionId, item)\n return owned(() => entry.dispose())\n },\n list<T>(token: RegistryToken<T>): Readable<readonly T[]> {\n assertOwnsId('contracts.list', extensionId, token.id)\n let list = lists.get(token.id)\n if (!list) {\n const id = token.id\n list = {\n get: () => registry.items(id),\n subscribe: listener => guardedSubscribe(`contracts.list(${id})`, l => registry.watchItems(id, l), listener),\n }\n lists.set(id, list)\n }\n return list as Readable<readonly T[]>\n },\n }\n}\n","/**\n * The process-wide store behind `ctx.contracts`: who provides each\n * contract, and what each registry holds. One per host process; every\n * extension's contracts domain reads and writes it.\n *\n * A contract id holds a stack of provisions. The newest is active; when it\n * goes, the one below it (an older instance of the same extension still\n * unloading) becomes active again. Every change of the active provision\n * bumps the id's generation, so a consumer can tell a reload from no change.\n */\n\nimport type { Disposable, Live } from '../api/core'\n\n/** Options of {@link createContractRegistry}. */\nexport interface ContractRegistryOptions {\n /**\n * Position of an extension in load order (lower loads first). Registry\n * items are listed by it. Extensions it doesn't know (`undefined`) come\n * after the known ones, in the order they first added an item.\n */\n loadOrder?: (extensionId: string) => number | undefined\n}\n\n/** The process-wide contract and registry store. */\nexport interface ContractRegistry {\n /** Makes `impl` the active provision of contract `id`. Ownership is checked by the caller. */\n provide: (id: string, extensionId: string, impl: unknown) => Disposable\n /** The current state of contract `id`. The same object until it changes. */\n live: (id: string) => Live<unknown>\n /** Calls `listener` after each change of contract `id`. Returns the unsubscribe. */\n watch: (id: string, listener: (live: Live<unknown>) => void) => () => void\n /** Adds `item` to registry `id` on behalf of `extensionId`. */\n add: (id: string, extensionId: string, item: unknown) => Disposable\n /** Items of registry `id` in load order. The same array until it changes. */\n items: (id: string) => readonly unknown[]\n /** Calls `listener` after each change of registry `id`. Returns the unsubscribe. */\n watchItems: (id: string, listener: (items: readonly unknown[]) => void) => () => void\n}\n\ninterface Provision { extensionId: string, impl: unknown }\ninterface ContractState {\n stack: Provision[]\n generation: number\n live: Live<unknown>\n listeners: Set<(live: Live<unknown>) => void>\n}\ninterface Item { extensionId: string, item: unknown, seq: number }\ninterface RegistryState {\n entries: Item[]\n view: readonly unknown[]\n listeners: Set<(items: readonly unknown[]) => void>\n}\n\nconst PENDING: Live<unknown> = Object.freeze({ status: 'pending' })\nconst EMPTY: readonly unknown[] = Object.freeze([])\n\nfunction notify<T>(listeners: Set<(value: T) => void>, value: T): void {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n }\n catch {\n // Listeners are guarded by the domain; one failing never stops the rest.\n }\n }\n}\n\n/**\n * Creates an empty contract and registry store.\n *\n * @param options - Load order for registry listing.\n * @returns The store, shared by every extension's contracts domain.\n */\nexport function createContractRegistry(options: ContractRegistryOptions = {}): ContractRegistry {\n const contracts = new Map<string, ContractState>()\n const registries = new Map<string, RegistryState>()\n const firstSeen = new Map<string, number>()\n let seq = 0\n\n function contract(id: string): ContractState {\n let state = contracts.get(id)\n if (!state) {\n state = { stack: [], generation: 0, live: PENDING, listeners: new Set() }\n contracts.set(id, state)\n }\n return state\n }\n\n function registry(id: string): RegistryState {\n let state = registries.get(id)\n if (!state) {\n state = { entries: [], view: EMPTY, listeners: new Set() }\n registries.set(id, state)\n }\n return state\n }\n\n function rank(extensionId: string): [number, number] {\n const order = options.loadOrder?.(extensionId)\n return order === undefined ? [1, firstSeen.get(extensionId) ?? 0] : [0, order]\n }\n\n function rebuild(state: RegistryState): void {\n const sorted = [...state.entries].sort((a, b) => {\n const [ka, oa] = rank(a.extensionId)\n const [kb, ob] = rank(b.extensionId)\n return ka - kb || oa - ob || a.seq - b.seq\n })\n state.view = Object.freeze(sorted.map(entry => entry.item))\n notify(state.listeners, state.view)\n }\n\n return {\n provide(id, extensionId, impl) {\n const state = contract(id)\n const provision: Provision = { extensionId, impl }\n state.stack.push(provision)\n state.generation++\n state.live = Object.freeze({ status: 'active', value: impl, generation: state.generation })\n notify(state.listeners, state.live)\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n const index = state.stack.indexOf(provision)\n const wasActive = index === state.stack.length - 1\n state.stack.splice(index, 1)\n if (!wasActive)\n return\n const next = state.stack.at(-1)\n if (next) {\n state.generation++\n state.live = Object.freeze({ status: 'active', value: next.impl, generation: state.generation })\n }\n else {\n state.live = Object.freeze({ status: 'inactive', reason: `${extensionId} withdrew \"${id}\"` })\n }\n notify(state.listeners, state.live)\n },\n }\n },\n live: id => contracts.get(id)?.live ?? PENDING,\n watch(id, listener) {\n const { listeners } = contract(id)\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n add(id, extensionId, item) {\n if (!firstSeen.has(extensionId))\n firstSeen.set(extensionId, firstSeen.size)\n const state = registry(id)\n const entry: Item = { extensionId, item, seq: seq++ }\n state.entries.push(entry)\n rebuild(state)\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n state.entries.splice(state.entries.indexOf(entry), 1)\n rebuild(state)\n },\n }\n },\n items: id => registries.get(id)?.view ?? EMPTY,\n watchItems(id, listener) {\n const { listeners } = registry(id)\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n }\n}\n","/**\n * `ctx.artifacts` (extension API): artifact kinds, plus list / find /\n * record over the host runtime bridge's artifacts facade. A kind is checked\n * as `registerArtifactKind` checks it; its callbacks run through the guard.\n */\n\nimport type { SessionArtifact } from '../../../session/artifacts'\nimport type { ArtifactsDomain } from '../../api/sessions'\nimport type { ExtensionArtifactKindRegistration } from '../../types'\nimport type { DomainDeps } from '../deps'\nimport type { ArtifactsPort } from './ports'\nimport { ARTIFACT_KIND_PATTERN } from '../../../session/artifacts'\nimport { createArtifactDetectHook } from '../../artifact-detect'\nimport { createArtifactsSurface } from '../../host-runtime'\nimport { assertAlive, assertUsable, track } from '../owner'\n\nconst CALLBACKS = ['detect', 'validateMeta', 'render', 'resolve', 'badge'] as const\n\n/** Throws a TypeError naming what is wrong with `registration`. */\nfunction checkKind(registration: ExtensionArtifactKindRegistration): void {\n if (!registration || typeof registration.kind !== 'string' || !ARTIFACT_KIND_PATTERN.test(registration.kind))\n throw new TypeError('artifacts.kinds.register: kind must match [\\\\w.:-]+')\n if (typeof registration.label !== 'string' || !registration.label)\n throw new TypeError(`artifacts.kinds.register: kind \"${registration.kind}\" needs a label`)\n for (const fn of CALLBACKS) {\n if (registration[fn] !== undefined && typeof registration[fn] !== 'function')\n throw new TypeError(`artifacts.kinds.register: ${fn} of kind \"${registration.kind}\" must be a function`)\n }\n}\n\n/** A copy of `registration` whose callbacks run through the guard: a throw or a timeout is attributed and turns into \"nothing\". */\nfunction guarded(deps: DomainDeps, registration: ExtensionArtifactKindRegistration): ExtensionArtifactKindRegistration {\n const { guard } = deps\n const { kind, detect, validateMeta, render, resolve, badge } = registration\n const label = (fn: string): string => `artifacts.kind(${kind}).${fn}`\n return {\n ...registration,\n ...(detect ? { detect: async outcome => guard.call(label('detect'), () => detect(outcome)) } : {}),\n ...(validateMeta ? { validateMeta: meta => guard.callSync(label('validateMeta'), () => validateMeta(meta), { fallback: false }) ?? false } : {}),\n ...(render ? { render: (artifact: SessionArtifact) => guard.callSync(label('render'), () => render(artifact)) } : {}),\n ...(resolve ? { resolve: async (artifact, opts) => guard.call(label('resolve'), () => resolve(artifact, opts)) } : {}),\n ...(badge ? { badge: artifacts => guard.callSync(label('badge'), () => badge(artifacts)) } : {}),\n }\n}\n\n/**\n * Creates one extension's `ctx.artifacts`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's artifact scope and kind registry.\n * @returns The domain. Calls throw (or reject) with `DisposedError` once the owner is disposed.\n */\nexport function createArtifactsDomain(deps: DomainDeps, port: ArtifactsPort): ArtifactsDomain {\n const { extensionId, owner, logger } = deps\n const surface = createArtifactsSurface(() => port.current()?.artifacts?.() ?? null)\n return {\n kinds: {\n register(registration) {\n assertAlive(owner, 'artifacts.kinds.register')\n checkKind(registration)\n if (!port.registerKind)\n throw new Error(`artifacts.kinds.register: this host does not support artifact kinds (extension \"${extensionId}\").`)\n const safe = guarded(deps, registration)\n const detect = createArtifactDetectHook(safe, { warn: (message, fields) => logger.warn(message, fields) })\n return track(owner, port.registerKind({ extensionId, registration: safe, ...(detect ? { detect } : {}) }))\n },\n },\n list: async (query) => {\n assertUsable(owner, 'artifacts.list')\n return surface.list(query)\n },\n // The store answers newest first: the most recently updated match.\n find: async (kind, uri) => {\n assertUsable(owner, 'artifacts.find')\n return (await surface.find(kind, uri))[0]\n },\n record: async (input) => {\n assertUsable(owner, 'artifacts.record')\n return surface.record(input)\n },\n }\n}\n","/**\n * `ctx.generate` (extension API): model calls outside any session. The\n * host resolves the provider (the user's credentials and default model) and\n * counts usage; `object` reuses the schema-pinned side-channel call behind\n * the chat commands' `ctx.generateData`, `decide` the decisions model, and\n * `image` the host's image port (the generate_image tool's models).\n */\n\nimport type { AgentDecide, DecisionOutcome, DecisionQuestions, DecisionRequest } from '../../../decisions/types'\nimport type { Provider } from '../../../providers'\nimport type { TurnUsage } from '../../../types'\nimport type { GenerateDomain, GenerateImageOptions } from '../../api/sessions'\nimport type { DomainDeps } from '../deps'\nimport type { GenerateImageReference, GenerateImageRequest, GenerateModelRef, GeneratePort, ResolvedGenerateModel } from './ports'\nimport { createHooks } from 'hookable'\nimport { generateStructuredData } from '../../../chat/generate-data'\nimport { createDecider } from '../../../decisions'\nimport { currentRunDecide } from '../../../decisions/run-scope'\nimport { IMAGE_ASPECT_RATIOS, MAX_IMAGES_PER_REQUEST } from '../../../providers/images'\nimport { validateStoreValue } from '../../storage/validate'\nimport { assertUsable, isTornDown } from '../owner'\n\n/**\n * Wraps `provider` so each `stream` call that returns reports its usage.\n * Other members forward to the original, bound to it (class providers keep\n * their private state).\n */\nfunction counting(provider: Provider, onUsage: (usage: TurnUsage) => void): Provider {\n const stream: Provider['stream'] = async (options, callbacks) => {\n const result = await provider.stream(options, callbacks)\n onUsage(result.usage)\n return result\n }\n return new Proxy(provider, {\n get(target, prop) {\n if (prop === 'stream')\n return stream\n const value = Reflect.get(target, prop, target) as unknown\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value\n },\n })\n}\n\n/** Most reference images one `generate.image` call takes, as the generate_image tool. */\nexport const MAX_IMAGE_REFERENCES = 8\n\n/** Largest prompt `generate.image` takes, in characters. */\nconst MAX_IMAGE_PROMPT = 32_000\n\n/**\n * Checks `ctx.generate.image` options (an extension's input) and builds the\n * host request. Throws a `TypeError` naming the first problem.\n *\n * @param extensionId - The calling extension.\n * @param opts - The options as passed.\n * @param signal - The combined owner and caller signal.\n */\nexport function imageRequest(extensionId: string, opts: GenerateImageOptions, signal: AbortSignal): GenerateImageRequest {\n if (!opts || typeof opts.prompt !== 'string' || !opts.prompt.trim() || opts.prompt.length > MAX_IMAGE_PROMPT)\n throw new TypeError(`generate.image: prompt must be a non-empty string of at most ${MAX_IMAGE_PROMPT} characters`)\n const n = opts.n ?? 1\n if (!Number.isInteger(n) || n < 1 || n > MAX_IMAGES_PER_REQUEST)\n throw new TypeError(`generate.image: n must be an integer from 1 to ${MAX_IMAGES_PER_REQUEST}`)\n if (opts.aspectRatio !== undefined && !(IMAGE_ASPECT_RATIOS as readonly string[]).includes(opts.aspectRatio))\n throw new TypeError(`generate.image: aspectRatio must be one of ${IMAGE_ASPECT_RATIOS.join(', ')}`)\n const model = opts.model\n if (model !== undefined && (typeof model?.providerId !== 'string' || typeof model.modelId !== 'string' || !model.providerId || !model.modelId))\n throw new TypeError('generate.image: model must be { providerId, modelId }')\n const references = opts.references ?? []\n if (!Array.isArray(references) || references.length > MAX_IMAGE_REFERENCES)\n throw new TypeError(`generate.image: references must be a list of at most ${MAX_IMAGE_REFERENCES}`)\n const refs = references.map((ref, i): GenerateImageReference => {\n if (ref && typeof (ref as { path?: unknown }).path === 'string' && (ref as { path: string }).path)\n return { path: (ref as { path: string }).path }\n const bytes = ref as { mimeType?: unknown, data?: unknown }\n if (bytes && typeof bytes.mimeType === 'string' && bytes.mimeType.startsWith('image/') && bytes.data instanceof Uint8Array)\n return { mimeType: bytes.mimeType, data: bytes.data }\n throw new TypeError(`generate.image: references[${i}] must be { path } or { mimeType: 'image/…', data: Uint8Array }`)\n })\n const save = opts.save === true\n ? {}\n : opts.save && typeof opts.save === 'object'\n ? (typeof opts.save.sessionId === 'string' && opts.save.sessionId ? { sessionId: opts.save.sessionId } : {})\n : undefined\n return {\n extensionId,\n prompt: opts.prompt.trim(),\n ...(model ? { model: { providerId: model.providerId, modelId: model.modelId } } : {}),\n n,\n ...(opts.aspectRatio !== undefined ? { aspectRatio: opts.aspectRatio } : {}),\n references: refs,\n ...(save ? { save } : {}),\n signal,\n }\n}\n\n/** The owner's signal, combined with the caller's when given. */\nfunction combined(owner: AbortSignal, signal: AbortSignal | undefined): AbortSignal {\n return signal ? AbortSignal.any([signal, owner]) : owner\n}\n\n/**\n * Creates one extension's `ctx.generate`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's provider resolution, usage counter and decisions model.\n * @returns The domain. Calls reject with `DisposedError` once the owner is disposed, and abort with it.\n */\nexport function createGenerateDomain(deps: DomainDeps, port: GeneratePort): GenerateDomain {\n const { extensionId, owner } = deps\n // Answers `unavailable` (or throws DecisionUnavailableError with `{ throw: true }`) when the host has no decisions model.\n let unavailable: AgentDecide | undefined\n // Inside a hook observer of a run: that run's decider, so the decision is\n // stamped, cancelled and (in a replay run) journaled like the agent's own.\n const decider = (): AgentDecide => currentRunDecide() ?? port.decide ?? (unavailable ??= createDecider({ providers: [], config: undefined, hooks: createHooks() }).forRun(undefined))\n\n const resolve = async (method: 'text' | 'object', model: GenerateModelRef | undefined): Promise<ResolvedGenerateModel & { counted: Provider }> => {\n assertUsable(owner, `generate.${method}`)\n const resolved = await port.resolve(model)\n assertUsable(owner, `generate.${method}`)\n const counted = counting(resolved.provider, (usage) => {\n try {\n port.recordUsage?.({ extensionId, method, providerId: resolved.providerId, modelId: resolved.modelId, usage })\n }\n catch (error) {\n deps.logger.warn('generate: recording usage failed', { error: error instanceof Error ? error.message : String(error) })\n }\n })\n return { ...resolved, counted }\n }\n\n const decide = ((request: DecisionRequest<DecisionQuestions>, options?: { throw: true }): Promise<DecisionOutcome<DecisionQuestions>> => {\n assertUsable(owner, 'generate.decide')\n const scoped = { ...request, signal: combined(owner.signal, request.signal) }\n return options ? decider()(scoped, options) : decider()(scoped)\n }) as AgentDecide\n Object.defineProperty(decide, 'available', { get: () => !isTornDown(owner) && decider().available })\n\n return {\n async text(opts) {\n const { counted, modelId } = await resolve('text', opts.model)\n const result = await counted.stream(\n {\n model: modelId,\n system: opts.system ?? '',\n tools: [],\n messages: [counted.userMessage(opts.prompt)],\n signal: combined(owner.signal, opts.signal),\n },\n { onText: () => {} },\n )\n return result.text\n },\n async object(opts) {\n const { counted, modelId } = await resolve('object', opts.model)\n const payload = await generateStructuredData<unknown>({\n provider: counted,\n model: modelId,\n prompt: opts.prompt,\n schema: opts.schema,\n ...(opts.system !== undefined ? { system: opts.system } : {}),\n signal: combined(owner.signal, opts.signal),\n })\n // The model's answer is untrusted: check it against the schema (and take its parsed value).\n const checked = await validateStoreValue(opts.schema, payload)\n if (!checked.ok)\n throw new Error(`generate.object: the model's answer does not match the schema: ${checked.error}`)\n return checked.value as never\n },\n decide,\n async image(opts) {\n assertUsable(owner, 'generate.image')\n const request = imageRequest(extensionId, opts, combined(owner.signal, opts?.signal))\n if (!port.image)\n throw new Error('generate.image: this host cannot generate images')\n const result = await port.image(request)\n assertUsable(owner, 'generate.image')\n try {\n port.recordUsage?.({ extensionId, method: 'image', providerId: result.providerId, modelId: result.modelId, usage: { input: 0, output: 0, ...(result.costUsd !== undefined ? { cost: result.costUsd } : {}) } })\n }\n catch (error) {\n deps.logger.warn('generate: recording usage failed', { error: error instanceof Error ? error.message : String(error) })\n }\n return { images: result.images }\n },\n }\n}\n","/**\n * `ctx.instructions` (extension API): text extensions add to the system\n * prompt. An entry without a session applies to every session (like a\n * registry system prompt fragment); a session entry applies to that session only. A\n * `key` replaces the extension's earlier entry with the same key and\n * session, in place. Entries belong to the owner they were added through.\n */\n\nimport type { Disposable, InstructionsDomain } from '../../api'\nimport type { DomainDeps } from '../deps'\nimport type { InstructionsRegistry } from '../outputs'\nimport { track } from '../owner'\n\n/** Options of {@link createInstructionsRegistry}. */\nexport interface InstructionsRegistryOptions {\n /** Load-order rank of an extension (lower first). Read on every `list`. Default: registration order only. */\n order?: (extensionId: string) => number\n}\n\ninterface Entry {\n readonly extensionId: string\n readonly sessionId?: string\n readonly slot?: string\n text: string\n seq: number\n /** Drops the owner link once the entry is gone. */\n unlink?: () => void\n}\n\n/**\n * Creates the shared instructions registry the agent reads, with the factory\n * of each extension's `ctx.instructions`.\n *\n * @param options - Load order.\n * @returns The registry, plus `domain(deps)` to make one extension's domain.\n */\nexport function createInstructionsRegistry(options: InstructionsRegistryOptions = {}): InstructionsRegistry & { domain: (deps: DomainDeps) => InstructionsDomain } {\n const entries = new Set<Entry>()\n const bySlot = new Map<string, Entry>()\n const listeners = new Set<() => void>()\n let nextSeq = 0\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n }\n catch {}\n }\n }\n\n const remove = (entry: Entry): void => {\n if (!entries.delete(entry))\n return\n if (entry.slot !== undefined && bySlot.get(entry.slot) === entry)\n bySlot.delete(entry.slot)\n entry.unlink?.()\n notify()\n }\n\n const sorted = (list: Entry[]): Entry[] => {\n const rank = options.order\n return list.sort((a, b) => (rank ? rank(a.extensionId) - rank(b.extensionId) : 0) || a.seq - b.seq)\n }\n\n return {\n list: (sessionId) => {\n const all = [...entries]\n const global = sorted(all.filter(entry => entry.sessionId === undefined))\n const scoped = sessionId === undefined ? [] : sorted(all.filter(entry => entry.sessionId === sessionId))\n return [...global, ...scoped].map(entry => entry.text)\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n domain: (deps: DomainDeps): InstructionsDomain => ({\n add(text, opts = {}): Disposable {\n if (typeof text !== 'string')\n throw new TypeError('instructions.add: text must be a string')\n if (opts.sessionId !== undefined && (typeof opts.sessionId !== 'string' || opts.sessionId.length === 0))\n throw new TypeError('instructions.add: sessionId must be a non-empty string')\n if (opts.key !== undefined && (typeof opts.key !== 'string' || opts.key.length === 0))\n throw new TypeError('instructions.add: key must be a non-empty string')\n const slot = opts.key === undefined ? undefined : JSON.stringify([deps.extensionId, opts.sessionId ?? null, opts.key])\n const previous = slot === undefined ? undefined : bySlot.get(slot)\n const entry: Entry = {\n extensionId: deps.extensionId,\n ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),\n ...(slot !== undefined ? { slot } : {}),\n text,\n // A replacement keeps the place of the entry it replaces.\n seq: previous?.seq ?? nextSeq++,\n }\n // Throws DisposedError (and adds nothing) once the owner is disposed.\n const handle = track(deps.owner, { dispose: () => remove(entry) })\n entry.unlink = handle.dispose\n if (previous) {\n entries.delete(previous)\n previous.unlink?.()\n }\n entries.add(entry)\n if (slot !== undefined)\n bySlot.set(slot, entry)\n notify()\n return handle\n },\n }),\n }\n}\n","/**\n * `ctx.plugins` (extension API): loads an Agent Plugin folder with the\n * plugin loader (`loadAgentPlugin`) and registers its skills and MCP servers through the catalogs.\n * The returned plugin is a Disposable that withdraws them; it is also\n * withdrawn with the owner it was loaded through.\n */\n\nimport type { LoadedPlugin } from '../../../plugins'\nimport type { SkillSource } from '../../../skills'\nimport type { PluginsDomain } from '../../api/catalogs'\nimport type { Disposable, ExtensionSource } from '../../api/core'\nimport type { DomainDeps } from '../deps'\nimport type { PluginsPort } from './ports'\nimport { basename, isAbsolute, resolve } from 'node:path'\nimport { loadAgentPlugin } from '../../../plugins'\nimport { DisposedError } from '../../api/core'\nimport { withProvenance } from '../../shared'\nimport { resolveStoragePath } from '../../storage/paths'\nimport { assertAlive, track } from '../owner'\n\n/** The skill source a plugin's skills inherit: the extension's scope (config-installed extensions are user-level). */\nfunction skillSource(source: ExtensionSource): SkillSource {\n return source === 'config' ? 'user' : source\n}\n\n/**\n * Creates one extension's `ctx.plugins`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The extension's location and the catalog registration functions.\n * @returns The domain. `load` rejects with `DisposedError` when the owner is disposed before or during the load.\n */\nexport function createPluginsDomain(deps: DomainDeps, port: PluginsPort): PluginsDomain {\n const { extensionId, owner, logger } = deps\n return {\n async load(spec) {\n assertAlive(owner, 'plugins.load')\n const options = typeof spec === 'string' ? { dir: spec } : spec\n const requested = options?.dir\n if (typeof requested !== 'string' || requested.length === 0)\n throw new TypeError('plugins.load: dir must be a non-empty string')\n const extension = port.extension(extensionId)\n if (!extension)\n throw new Error(`plugins.load: the host does not know extension \"${extensionId}\".`)\n\n // Relative specs resolve against the extension's folder (vendored plugins); inline extensions use the cwd.\n const target = isAbsolute(requested) ? requested : resolve(extension.dir ?? extension.paths.cwd, requested)\n const source = skillSource(extension.source)\n const loaded = await loadAgentPlugin(target, {\n source,\n // `${PLUGIN_DATA}` lives in the loading extension's storage root.\n dataRoot: extension.storagePath?.('data', 'plugin-data')\n ?? resolveStoragePath({ paths: extension.paths, extensionId, ...(extension.dir !== undefined ? { dir: extension.dir } : {}), logger }, 'data', 'plugin-data'),\n ...(options.skills !== undefined ? { skills: options.skills } : {}),\n ...(options.mcp !== undefined ? { mcp: options.mcp } : {}),\n ...(options.namePrefix !== undefined ? { namePrefix: options.namePrefix } : {}),\n })\n\n // Diagnostics are logged, never thrown: a bad package must not fail the extension that loaded it.\n for (const diagnostic of loaded.diagnostics) {\n const detail = { plugin: loaded.manifest?.name ?? target, code: diagnostic.code, ...(diagnostic.path ? { path: diagnostic.path } : {}) }\n if (diagnostic.severity === 'error')\n logger.error(`plugins.load: ${diagnostic.message}`, detail)\n else\n logger.warn(`plugins.load: ${diagnostic.message}`, detail)\n }\n if (owner.disposed)\n throw new DisposedError('plugins.load')\n\n const origin = { kind: 'extension', id: extensionId } as const\n const parts: Disposable[] = []\n const withdraw = (): void => {\n for (const part of parts.splice(0).reverse()) {\n try {\n part.dispose()\n }\n catch (error) {\n logger.warn('plugins.load: withdrawing a registration failed', { error: error instanceof Error ? error.message : String(error) })\n }\n }\n }\n try {\n if (loaded.ok) {\n for (const skill of loaded.skills)\n parts.push(port.registerSkill(withProvenance(skill, source, extensionId), origin))\n for (const server of loaded.mcpServers)\n parts.push(port.registerMcpServer(server, origin))\n }\n // A rejected plugin is recorded too: \"the plugin is broken\" beats it silently missing.\n if (port.recordPlugin)\n parts.push(port.recordPlugin({ name: loaded.manifest?.name ?? basename(target), extensionName: extensionId, dir: target, plugin: loaded }))\n }\n catch (error) {\n withdraw()\n throw error\n }\n const handle = track(owner, { dispose: withdraw })\n logger.debug('plugins.load: registered', { plugin: loaded.manifest?.name, skills: loaded.skills.length, mcpServers: loaded.mcpServers.length })\n return Object.assign(loaded, { dispose: handle.dispose }) as LoadedPlugin & Disposable\n },\n }\n}\n","/**\n * `ctx.workspace` (extension API): the host runtime bridge's workspace facade, owner-checked.\n * Shell and file operations run in the session's execution context, resolved\n * live on every call; detached calls reject.\n */\n\nimport type { WorkspaceDomain } from '../../api/sessions'\nimport type { DomainDeps } from '../deps'\nimport type { WorkspacePort } from './ports'\nimport { createWorkspaceSurface } from '../../host-runtime'\nimport { assertUsable } from '../owner'\n\n/**\n * Creates one extension's `ctx.workspace`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's live runtime implementation.\n * @returns The domain. Every call rejects with `DisposedError` once the owner is disposed; `exec` aborts with it.\n */\nexport function createWorkspaceDomain(deps: DomainDeps, port: WorkspacePort): WorkspaceDomain {\n const { owner } = deps\n const surface = createWorkspaceSurface(\n async () => await port.current()?.workspace?.() ?? null,\n () => port.current()?.workspaceAvailable?.(),\n )\n return {\n available: async () => {\n assertUsable(owner, 'workspace.available')\n return surface.available()\n },\n exec: async (command, options = {}) => {\n assertUsable(owner, 'workspace.exec')\n const signal = options.signal ? AbortSignal.any([options.signal, owner.signal]) : owner.signal\n return surface.exec(command, { ...options, signal })\n },\n readFile: async (path) => {\n assertUsable(owner, 'workspace.readFile')\n return surface.readFile(path)\n },\n writeFile: async (path, content) => {\n assertUsable(owner, 'workspace.writeFile')\n return surface.writeFile(path, content)\n },\n listFiles: async (path, options) => {\n assertUsable(owner, 'workspace.listFiles')\n return surface.listFiles(path, options)\n },\n fileSize: async (path) => {\n assertUsable(owner, 'workspace.fileSize')\n return surface.fileSize(path)\n },\n }\n}\n","/**\n * Builds the {@link ExtensionContext} of one extension from the domain\n * factories (extension API).\n *\n * Every domain gets {@link DomainDeps} bound to one owner: the extension's\n * root owner, or a child made by `ctx.scope()`. A scope rebuilds the domain\n * views on its child owner, so disposing the scope withdraws exactly what\n * was registered through it. Storage and settings keep one cache per\n * extension; a scope wraps them so its subscriptions end with the scope.\n */\n\nimport type { AgentDecide } from '../../decisions/types'\nimport type { Logger } from '../../logger'\nimport type { InstructionsDomain } from '../api/catalogs'\nimport type { ExtensionContext, ExtensionInfo } from '../api/context'\nimport type { AppInfo, Disposable, ExtensionPaths, ExtensionSource } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { SessionFacetsDomain, SessionsDomain } from '../api/sessions'\nimport type { SettingsDomain, SettingsSchema } from '../api/settings'\nimport type { KeyValue, StorageDomain, Store } from '../api/storage'\nimport type { DesktopDomain } from '../api/ui'\nimport type { AgentsCatalog, McpCatalog, ModelsCatalog, ProvidersCatalog, SkillsCatalog, ToolsCatalog } from '../catalog'\nimport type { CommandRegistry } from '../commands'\nimport type { ContractRegistry } from '../contracts'\nimport type { HooksPort, InterceptorRegistry } from '../hooks'\nimport type { IntegrationFlowPort, IntegrationRegistry } from '../integrations'\nimport type { RpcRouter } from '../rpc'\nimport type { SettingsDomainInstance } from '../settings'\nimport type { StorageRuntime } from '../storage'\nimport type { DialogRouter, UiClientPort, UiRegistry } from '../ui'\nimport type { DomainDeps, Guard } from './deps'\nimport type { HostRuntimePorts } from './domains'\nimport type { FacetsRuntime } from './facets'\nimport type { InstructionsRegistry } from './outputs'\nimport type { RuntimeOwner } from './owner'\nimport { createHooks } from 'hookable'\nimport { createDecider } from '../../decisions'\nimport { createAgentsDomain, createMcpDomain, createModelsDomain, createProvidersDomain, createSkillsDomain, createToolsDomain } from '../catalog'\nimport { createCommandsDomain } from '../commands'\nimport { createContractsDomain } from '../contracts'\nimport { createHooksDomain } from '../hooks'\nimport { createIntegrationsDomain } from '../integrations'\nimport { createRpcDomain } from '../rpc'\nimport { createComposerDomain, createKeymapDispatch, createUiAdd, createUiDomain } from '../ui'\nimport { createArtifactsDomain, createGenerateDomain, createPluginsDomain, createSessionsDomain, createWorkspaceDomain } from './domains'\nimport { track } from './owner'\n\n/**\n * The desktop app's main-process handle behind `ctx.desktop`. Only the\n * desktop host gives one; elsewhere `ctx.desktop` is undefined.\n */\nexport interface DesktopPort {\n /** The `electron` module. */\n electron: () => unknown\n /** Window list and window events. `on` returns the unsubscribe. */\n windows: {\n list: () => readonly { id: number, focused: boolean }[]\n on: (event: 'open' | 'close' | 'focus', listener: (window: { id: number }) => void) => () => void\n }\n}\n\n/** The instructions registry together with its per-extension domain factory (`createInstructionsRegistry`). */\nexport type InstructionsRuntime = InstructionsRegistry & { domain: (deps: DomainDeps) => InstructionsDomain }\n\n/** The shared registries and host ports every extension's context draws on. One set per runtime. */\nexport interface ContextServices {\n /** Host and version data behind `ctx.app`. */\n readonly app: AppInfo\n /** Interceptors extensions add with `ctx.hooks`. */\n readonly interceptors: InterceptorRegistry\n /** The catalogs behind `ctx.tools`, `ctx.agents`, `ctx.models`, `ctx.providers`, `ctx.mcp` and `ctx.skills`. */\n readonly catalogs: {\n readonly tools: ToolsCatalog\n readonly agents: AgentsCatalog\n readonly models: ModelsCatalog\n readonly providers: ProvidersCatalog\n readonly mcp: McpCatalog\n readonly skills: SkillsCatalog\n }\n /** System prompt text behind `ctx.instructions`. */\n readonly instructions: InstructionsRuntime\n /** The facet registry behind `ctx.sessions.facets`. */\n readonly facets: FacetsRuntime\n /** The registry behind `ctx.add`. */\n readonly ui: UiRegistry\n /** Routes `ctx.ui` dialogs to a client. */\n readonly dialogs: DialogRouter\n /** Panels, navigation and composer calls on a client. */\n readonly uiClient: UiClientPort\n /** The registry behind `ctx.commands` and `ctx.keymap`. */\n readonly commands: CommandRegistry\n /** The router behind `ctx.rpc`. */\n readonly rpc: RpcRouter\n /** The registry behind `ctx.contracts`. */\n readonly contracts: ContractRegistry\n /** The registry behind `ctx.integrations`. */\n readonly integrations: IntegrationRegistry\n /** How integration sign-in flows show their UI. */\n readonly integrationFlows: IntegrationFlowPort\n /** Session, generate, workspace, artifacts and plugins ports. A missing port makes that domain reject. */\n readonly host: HostRuntimePorts\n /** The desktop app's handle behind `ctx.desktop`. Absent on other hosts. */\n readonly desktop?: DesktopPort\n /** Platform for keymap `mod` resolution. Default `process.platform`. */\n readonly platform?: string\n /** `ctx.extensions`. */\n readonly extensions: { list: () => readonly ExtensionInfo[], get: (id: string) => ExtensionInfo | undefined }\n}\n\n/** What is specific to one extension. */\nexport interface ExtensionContextInput<S extends SettingsSchema = SettingsSchema> {\n /** The extension's validated definition. */\n readonly definition: ExtensionDefinition<S>\n /** Where the extension was found. */\n readonly source: ExtensionSource\n /** The extension's folder. */\n readonly dir?: string\n /** Paths handed to the extension as `ctx.paths`. */\n readonly paths: ExtensionPaths\n /** The extension's logger. */\n readonly logger: Logger\n /** Bounds the extension's callbacks with timeouts and an error budget. */\n readonly guard: Guard\n /** The extension's hooks port (its own agent-hook bus and host events). */\n readonly hooks: HooksPort\n /** The extension's storage runtime, built on its root owner. */\n readonly storage: StorageRuntime\n /** The extension's settings domain, built on its root owner. */\n readonly settings: SettingsDomainInstance<S>\n /** The extension's project directory for RPC routing. Default `paths.projectRoot ?? paths.cwd`. */\n readonly directory?: string\n}\n\n/**\n * The members of host domains that return synchronously. On a host without\n * the port they throw at once instead of returning a rejected promise.\n */\nconst SYNC_MEMBERS: ReadonlySet<string> = new Set(['artifacts.kinds.register'])\n\n/** Values of a missing domain that are not calls (`generate.decide.available`). */\nconst UNAVAILABLE_VALUES: Readonly<Record<string, unknown>> = { 'generate.decide.available': false }\n\n/**\n * A domain whose host port is missing. Every member is a function: a\n * synchronous one (see {@link SYNC_MEMBERS}) throws, an async one rejects,\n * each with an error naming the member and the host. Nested members\n * (`kinds.register`) work the same way. `generate.decide` keeps\n * {@link AgentDecide}'s shape: `available` is `false`, and a call answers\n * `unavailable` (or throws `DecisionUnavailableError` with `{ throw: true }`).\n */\nfunction unavailableDomain<T>(name: string, host: string): T {\n const error = (path: string): Error => new Error(`ctx.${path} is not available in the ${host} host`)\n const make = (path: string): unknown => new Proxy(() => {}, {\n get: (_target, prop) => {\n if (prop === 'then' || typeof prop === 'symbol')\n return undefined\n const child = `${path}.${prop}`\n return Object.hasOwn(UNAVAILABLE_VALUES, child) ? UNAVAILABLE_VALUES[child] : make(child)\n },\n apply: (_target, _this, args: unknown[]) => {\n if (SYNC_MEMBERS.has(path))\n throw error(path)\n if (path === 'generate.decide')\n return unavailableDecider()(...(args as Parameters<AgentDecide>))\n return Promise.reject(error(path))\n },\n })\n return make(name) as T\n}\n\nlet noDecider: AgentDecide | undefined\n/** The decisions model of a host without one: `available` false, every call answers `unavailable`. */\nfunction unavailableDecider(): AgentDecide {\n return noDecider ??= createDecider({ providers: [], config: undefined, hooks: createHooks() }).forRun(undefined)\n}\n\nfunction hostDomain<P, T>(name: string, host: string, port: P | undefined, factory: (port: P) => T): T {\n return port === undefined ? unavailableDomain<T>(name, host) : factory(port)\n}\n\n/**\n * `ctx.sessions` with `facets`, which work on every host: on a host without\n * sessions the rest of the domain rejects, `facets` still registers.\n */\nfunction sessionsDomain(base: Omit<SessionsDomain, 'facets'>, facets: SessionFacetsDomain): SessionsDomain {\n if (typeof base === 'function')\n return new Proxy(base as SessionsDomain, { get: (target, prop, receiver) => (prop === 'facets' ? facets : Reflect.get(target, prop, receiver)) })\n return { ...base, facets }\n}\n\n/** `ctx.storage` bound to a scope: subscriptions made through it end with the scope. */\nfunction scopedStorage(root: StorageDomain, owner: RuntimeOwner): StorageDomain {\n const kv = (scope: Parameters<StorageDomain['kv']>[0], sessionId?: string): KeyValue => {\n const inner = root.kv(scope, sessionId)\n return { ...inner, subscribe: listener => track(owner, inner.subscribe(listener)) }\n }\n const scopeReadable = <T>(readable: { get: () => T, subscribe: (l: (v: T) => void) => () => void }) => ({\n get: readable.get,\n subscribe: (listener: (value: T) => void) => {\n const off = readable.subscribe(listener)\n return track(owner, { dispose: off }).dispose\n },\n })\n const store: StorageDomain['store'] = (name, schema, initial, opts) => {\n const inner = root.store(name, schema, initial, opts) as Store<unknown>\n return {\n ...scopeReadable(inner),\n set: inner.set,\n select: <U>(pick: (value: unknown) => U) => scopeReadable(inner.select(pick)),\n } as never\n }\n return { kv, store, memory: root.memory, path: root.path }\n}\n\n/** `ctx.settings` bound to a scope: `onChange` listeners end with the scope. */\nfunction scopedSettings<S extends SettingsSchema>(root: SettingsDomain<S>, owner: RuntimeOwner): SettingsDomain<S> {\n return Object.freeze({\n get: root.get,\n locked: root.locked,\n onChange: ((key, listener) => track(owner, root.onChange(key, listener))) as SettingsDomain<S>['onChange'],\n })\n}\n\n/**\n * Builds the context `setup` receives, bound to `owner`. `ctx.scope()`\n * makes a child owner and a context rebuilt on it.\n *\n * @param input - The extension's definition, paths, logger, guard and per-extension runtimes.\n * @param services - The runtime's shared registries and host ports.\n * @param owner - The owner registrations attach to (the root owner for `setup`).\n * @returns The context.\n */\nexport function createExtensionContext<S extends SettingsSchema>(\n input: ExtensionContextInput<S>,\n services: ContextServices,\n owner: RuntimeOwner,\n): ExtensionContext<S> {\n const { definition, logger, guard } = input\n const deps: DomainDeps = { extensionId: definition.id, owner, guard, logger }\n const isRoot = owner.parent === undefined\n const { catalogs, host } = services\n const uiPorts = { registry: services.ui, dialogs: services.dialogs, client: services.uiClient }\n const commands = createCommandsDomain(deps, services.commands, {\n ...(definition.displayName !== undefined ? { displayName: definition.displayName } : {}),\n ...(services.platform !== undefined ? { platform: services.platform } : {}),\n dispatch: createKeymapDispatch(deps, uiPorts),\n })\n const settings = isRoot ? input.settings.api : scopedSettings(input.settings.api, owner)\n const storage = isRoot ? input.storage.storage : scopedStorage(input.storage.storage, owner)\n\n const ctx: ExtensionContext<S> = {\n id: definition.id,\n ...(definition.version !== undefined ? { version: definition.version } : {}),\n ...(input.dir !== undefined ? { dir: input.dir } : {}),\n source: input.source,\n app: services.app,\n paths: input.paths,\n logger,\n signal: owner.signal,\n scope: () => {\n const child = owner.scope(`${owner.label}/scope`)\n const childCtx = createExtensionContext(input, services, child)\n return Object.assign(childCtx, { dispose: () => child.dispose() })\n },\n // Like the cleanup `setup` returns: runs once the calls in flight ended.\n onCleanup: cleanup => owner.onTeardown(cleanup),\n add: createUiAdd(deps, services.ui),\n tools: createToolsDomain(deps, catalogs.tools),\n hooks: createHooksDomain(deps, input.hooks, { interceptors: services.interceptors }),\n commands: commands.commands,\n keymap: commands.keymap,\n agents: createAgentsDomain(deps, catalogs.agents),\n models: createModelsDomain(deps, catalogs.models),\n providers: createProvidersDomain(deps, catalogs.providers),\n mcp: createMcpDomain(deps, catalogs.mcp),\n skills: createSkillsDomain(deps, catalogs.skills),\n plugins: hostDomain('plugins', services.app.host, host.plugins, port => createPluginsDomain(deps, port)),\n instructions: services.instructions.domain(deps),\n artifacts: hostDomain('artifacts', services.app.host, host.artifacts, port => createArtifactsDomain(deps, port)),\n sessions: sessionsDomain(host.sessions === undefined ? unavailableDomain('sessions', services.app.host) : createSessionsDomain(deps, host.sessions), services.facets.domain(deps)),\n generate: hostDomain('generate', services.app.host, host.generate, port => createGenerateDomain(deps, port)),\n workspace: hostDomain('workspace', services.app.host, host.workspace, port => createWorkspaceDomain(deps, port)),\n storage,\n settings,\n integrations: createIntegrationsDomain(deps, services.integrationFlows, services.integrations),\n rpc: createRpcDomain(deps, services.rpc, { directory: input.directory ?? input.paths.projectRoot ?? input.paths.cwd }),\n contracts: createContractsDomain(deps, services.contracts),\n ui: createUiDomain(deps, uiPorts),\n composer: createComposerDomain(deps, uiPorts),\n ...(services.desktop ? { desktop: desktopDomain(services.desktop, owner) } : {}),\n extensions: services.extensions,\n }\n return ctx\n}\n\n/** `ctx.desktop` over the host's port: window listeners end with the owner. */\nfunction desktopDomain(port: DesktopPort, owner: RuntimeOwner): DesktopDomain {\n return {\n electron: <T>() => port.electron() as T,\n windows: {\n list: () => port.windows.list(),\n on: (event, listener): Disposable => track(owner, { dispose: port.windows.on(event, listener) }),\n },\n }\n}\n","/**\n * Running an extension's `setup` and unloading it (extension API).\n *\n * Setup runs through the extension's guard with a 10 s bound\n * ({@link SETUP_TIMEOUT_MS}), so its errors are attributed and its\n * synchronous part is timed for stalls. A returned cleanup joins the\n * extension's owner. When setup throws or times out, everything it\n * registered so far is rolled back by disposing the owner: later\n * registrations from the still-running setup throw `DisposedError`.\n * The cleanup `setup` returns runs in the owner's teardown phase: after the\n * extension's in-flight calls ended (`owner.ts`).\n */\n\nimport type { ExtensionContext } from '../api/context'\nimport type { Cleanup } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { SettingsSchema } from '../api/settings'\nimport type { Guard } from './deps'\nimport type { RuntimeOwner } from './owner'\nimport { errorMessage } from '../../errors'\n\n/** How long `setup` may take, in ms. */\nexport const SETUP_TIMEOUT_MS = 10_000\n\n/** How long unload waits for async cleanups, in ms. */\nexport const UNLOAD_TIMEOUT_MS = 5_000\n\n/** Builds the `ctx` handed to `setup`, bound to `owner`. */\nexport type ContextFactory<S extends SettingsSchema = SettingsSchema> = (owner: RuntimeOwner) => ExtensionContext<S>\n\n/** Why a setup failed. */\nexport type SetupFailureReason\n /** `setup` threw or rejected. */\n = | 'threw'\n /** `setup` did not settle in time. */\n | 'timeout'\n /** The host's context factory threw: a host bug, not counted against the extension. */\n | 'context'\n /** The owner was disposed before or during setup (the extension was unloaded meanwhile). */\n | 'disposed'\n /** The guard refused to run it (its error budget is spent). */\n | 'refused'\n\n/** What {@link runSetup} reports. */\nexport type SetupOutcome\n = | { ok: true, warnings: readonly string[] }\n | { ok: false, reason: SetupFailureReason, error: string, cause?: unknown }\n\n/** Options for {@link runSetup}. */\nexport interface RunSetupOptions {\n /** Setup bound in ms. Default {@link SETUP_TIMEOUT_MS}. */\n timeoutMs?: number\n /** How long the rollback waits for async cleanups. Default {@link UNLOAD_TIMEOUT_MS}. */\n rollbackTimeoutMs?: number\n}\n\n/** What {@link unload} reports. */\nexport interface UnloadOutcome {\n /** `false` when an async cleanup was still running at the bound. It keeps running; nothing waits for it. */\n ok: boolean\n /** Set when `ok` is false. */\n error?: string\n /** Calls were still running: the registrations are withdrawn, the teardown waits for them (`owner.settled`). */\n draining?: boolean\n}\n\nconst NOT_SETTLED = Symbol('not settled')\n\n/**\n * Runs `definition.setup` with a context bound to `owner`.\n *\n * @param definition - The validated extension.\n * @param ctxFactory - Builds `ctx` for `owner`.\n * @param owner - The extension's root owner. Disposed on failure.\n * @param guard - The extension's guard.\n * @param options - Bounds.\n * @returns `ok`, or why it failed.\n */\nexport async function runSetup<S extends SettingsSchema>(\n definition: ExtensionDefinition<S>,\n ctxFactory: ContextFactory<S>,\n owner: RuntimeOwner,\n guard: Guard,\n options: RunSetupOptions = {},\n): Promise<SetupOutcome> {\n const timeoutMs = options.timeoutMs ?? SETUP_TIMEOUT_MS\n const fail = async (reason: SetupFailureReason, error: string, cause?: unknown): Promise<SetupOutcome> => {\n await unload(owner, { timeoutMs: options.rollbackTimeoutMs })\n return { ok: false, reason, error, ...(cause !== undefined ? { cause } : {}) }\n }\n\n if (owner.disposed)\n return { ok: false, reason: 'disposed', error: 'the extension was unloaded before setup ran' }\n\n let ctx: ExtensionContext<S>\n try {\n ctx = ctxFactory(owner)\n }\n catch (cause) {\n return fail('context', `could not build the extension context: ${errorMessage(cause)}`, cause)\n }\n\n let started = false\n let thrown: { cause: unknown } | undefined\n // `teardown`: the guard tripping is one of the ways the extension gets disposed, and its cleanup must still run then.\n const runCleanup = async (cleanup: Cleanup): Promise<void> => { await guard.call('cleanup', cleanup, { teardown: true }) }\n const result = await guard.call<unknown>('setup', async () => {\n started = true\n let returned: unknown\n try {\n returned = await definition.setup(ctx)\n }\n catch (cause) {\n thrown = { cause }\n throw cause\n }\n // Settled after a timeout or an unload: nothing will register this cleanup, so run it now.\n if (owner.disposed && typeof returned === 'function')\n void runCleanup(returned as Cleanup)\n return returned\n }, { timeoutMs, fallback: NOT_SETTLED })\n\n if (!started)\n return fail('refused', 'setup was not run: the extension\\'s error budget is spent')\n if (thrown)\n return fail('threw', errorMessage(thrown.cause), thrown.cause)\n if (result === NOT_SETTLED)\n return fail('timeout', `setup timed out after ${timeoutMs}ms`)\n\n if (owner.disposed) {\n if (typeof result === 'function')\n void runCleanup(result as Cleanup)\n return { ok: false, reason: 'disposed', error: 'the extension was unloaded during setup' }\n }\n const warnings: string[] = []\n if (typeof result === 'function') {\n const cleanup = result as Cleanup\n owner.onTeardown(() => runCleanup(cleanup))\n }\n else if (result !== undefined) {\n warnings.push(`setup returned ${typeof result}; only a cleanup function or nothing is used`)\n }\n return { ok: true, warnings }\n}\n\n/**\n * Unloads an extension: disposes its owner (every registration withdrawn,\n * then `ctx.signal` aborted and the teardown cleanups run) and waits for the\n * async cleanups up to a bound. With calls in flight the teardown waits for\n * them (`owner.ts`): unload then waits only for the withdrawal and reports\n * `draining`. Calling it again is harmless.\n *\n * @param owner - The extension's root owner.\n * @param options - `timeoutMs`, default {@link UNLOAD_TIMEOUT_MS}.\n * @param options.timeoutMs - How long to wait for async cleanups.\n * @returns Whether every cleanup finished in time.\n */\nexport async function unload(owner: RuntimeOwner, options: { timeoutMs?: number } = {}): Promise<UnloadOutcome> {\n owner.dispose()\n if (owner.draining) {\n const outcome = await settleWithin(owner.withdrawn, options.timeoutMs)\n return { ...outcome, draining: true }\n }\n return settleWithin(owner.settled, options.timeoutMs)\n}\n\n/**\n * Waits for `done` up to `timeoutMs` (default {@link UNLOAD_TIMEOUT_MS}).\n *\n * @param done - Async cleanups settling.\n * @param timeoutMs - The bound.\n */\nexport async function settleWithin(done: Promise<void>, timeoutMs = UNLOAD_TIMEOUT_MS): Promise<UnloadOutcome> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<typeof NOT_SETTLED>((resolve) => {\n timer = setTimeout(resolve, timeoutMs, NOT_SETTLED)\n })\n try {\n const result = await Promise.race([done, timedOut])\n return result === NOT_SETTLED ? { ok: false, error: `cleanup still running after ${timeoutMs}ms` } : { ok: true }\n }\n finally {\n clearTimeout(timer)\n }\n}\n","/**\n * Load order from the `dependencies` field (extension API).\n *\n * Dependencies only order the loads and give install hints: a missing or\n * mismatched dependency is reported, never fatal (`ctx.use` reports it as\n * inactive at run time). The order is topological; among extensions that are\n * ready at the same time, input order wins, so the result is deterministic\n * for a deterministic discovery order. A cycle is broken at its member that\n * comes first in the input, with a warning.\n */\n\nimport { satisfiesVersionRange } from '../host-version'\n\n/** What the resolver needs of an extension. */\nexport interface LoadOrderEntry {\n /** The extension id. */\n id: string\n /** Its version, checked against the ranges that name it. */\n version?: string\n /** `{ id: semver range }`. */\n dependencies?: Readonly<Record<string, string>>\n}\n\n/** A problem the resolver reports. None of them stops a load. */\nexport type LoadOrderIssue\n = | { kind: 'missing', id: string, dependency: string, range: string }\n | { kind: 'version', id: string, dependency: string, range: string, version: string }\n | { kind: 'cycle', ids: readonly string[], brokenAt: string }\n | { kind: 'duplicate', id: string }\n\n/** What {@link resolveLoadOrder} returns. */\nexport interface LoadOrder<E extends LoadOrderEntry> {\n /** The entries in load order. A duplicate id keeps its first entry only. */\n order: readonly E[]\n /** Missing and mismatched dependencies, broken cycles, dropped duplicates. */\n issues: readonly LoadOrderIssue[]\n}\n\n/**\n * Orders `entries` so each loads after the extensions it depends on.\n *\n * @param entries - The extensions, in discovery order (the tiebreak).\n * @returns The order and the issues found.\n */\nexport function resolveLoadOrder<E extends LoadOrderEntry>(entries: readonly E[]): LoadOrder<E> {\n const issues: LoadOrderIssue[] = []\n const byId = new Map<string, { entry: E, index: number }>()\n for (const entry of entries) {\n if (byId.has(entry.id))\n issues.push({ kind: 'duplicate', id: entry.id })\n else\n byId.set(entry.id, { entry, index: byId.size })\n }\n\n // Edges to present dependencies only; the rest are reported.\n const deps = new Map<string, string[]>()\n for (const { entry } of byId.values()) {\n const present: string[] = []\n for (const [dependency, range] of Object.entries(entry.dependencies ?? {})) {\n const target = byId.get(dependency)\n if (!target) {\n issues.push({ kind: 'missing', id: entry.id, dependency, range })\n continue\n }\n if (dependency === entry.id)\n continue\n present.push(dependency)\n const version = target.entry.version\n if (version !== undefined && satisfiesVersionRange(version, range) === false)\n issues.push({ kind: 'version', id: entry.id, dependency, range, version })\n }\n deps.set(entry.id, present)\n }\n\n const loaded = new Set<string>()\n const order: E[] = []\n const pending = [...byId.values()].sort((a, b) => a.index - b.index).map(v => v.entry)\n while (pending.length > 0) {\n let next = pending.findIndex(e => deps.get(e.id)!.every(d => loaded.has(d)))\n if (next === -1) {\n // Every pending entry waits on another, so a walk from any of them ends in a cycle.\n // Break it at its member that comes first in input order.\n const cycle = findCycle(pending[0]!.id, deps, loaded)\n next = pending.findIndex(e => cycle.includes(e.id))\n issues.push({ kind: 'cycle', ids: cycle, brokenAt: pending[next]!.id })\n }\n const [entry] = pending.splice(next, 1)\n loaded.add(entry!.id)\n order.push(entry!)\n }\n return { order, issues }\n}\n\n/** The cycle reached by walking unloaded dependencies from `start`, in walk order. */\nfunction findCycle(start: string, deps: ReadonlyMap<string, readonly string[]>, loaded: ReadonlySet<string>): string[] {\n const path: string[] = []\n const seen = new Map<string, number>()\n let current: string | undefined = start\n while (current !== undefined && !seen.has(current)) {\n seen.set(current, path.length)\n path.push(current)\n current = deps.get(current)!.find(d => !loaded.has(d))\n }\n return current === undefined ? path : path.slice(seen.get(current))\n}\n","/**\n * The extension runtime of one host (extension API).\n *\n * `createExtensionRuntime` builds the shared registries once (interceptors,\n * catalogs, instructions, UI, commands, RPC, contracts, integrations) and\n * loads definitions into them: validated, in dependency order, one owner\n * and one guard per extension, storage preloaded before `setup`, everything\n * rolled back when `setup` fails. A guard whose error budget is spent\n * disables its extension (status `'failed'` with the reason) and disposes\n * its owner. Disabled extensions never run; their settings stay readable\n * from the static schema. An extension unloaded, reloaded or disposed with\n * calls in flight (a command run, a tool execute, a guarded callback) has\n * its registrations withdrawn at once and its domains torn down once those\n * calls end, at most {@link ExtensionRuntimeOptions.drainTimeoutMs} for a\n * call without a bound of its own (`owner.ts`).\n *\n * Hosts plug in through {@link RuntimePorts}; every port is optional and\n * falls back to an in-memory or \"not available\" one.\n */\n\nimport type { Logger } from '../../logger'\nimport type { OAuthRefreshHookContext } from '../../types'\nimport type { ExtensionInfo } from '../api/context'\nimport type { ExtensionHostKind, ExtensionPaths, ExtensionSource } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { HookEvents } from '../api/hooks'\nimport type { ActionSetting } from '../api/settings'\nimport type { Json } from '../api/storage'\nimport type { AgentsCatalogPort, McpCatalogPort, ModelsCatalogPort, ProvidersCatalogPort, SkillsCatalogPort, ToolsCatalogPort } from '../catalog'\nimport type { CommandHostPort, KeymapPort } from '../commands'\nimport type { HooksPort, HostEventName } from '../hooks'\nimport type { AuthStorePort, IntegrationFlowPort } from '../integrations'\nimport type { RpcRemoteBridge, RpcRemoteTransport } from '../rpc'\nimport type { SettingsDomainInstance, SettingsPort, WireSettings } from '../settings'\nimport type { MemoryRegistry, StorageArea, StorageLocation, StoragePort, StorageRuntime } from '../storage'\nimport type { ExtensionManifest, LoadedPluginRecord } from '../types'\nimport type { DialogPort, UiClientPort } from '../ui'\nimport type { OwnSettingActions } from '../ui/callbacks'\nimport type { ContextServices, DesktopPort } from './context'\nimport type { DomainDeps } from './deps'\nimport type { ArtifactKindEntry, HostRuntimePorts, PluginsPort } from './domains'\nimport type { ErrorBudget, GuardTrip, RuntimeGuard, StallMonitor, StallReport } from './guard'\nimport type { LoadOrderIssue } from './load-order'\nimport type { ExtensionRuntimeOutputs, HostEventSink } from './outputs'\nimport type { RuntimeOwner } from './owner'\nimport { basename } from 'node:path'\nimport { onProviderAccountsChange } from '../../chat/credentials'\nimport { consoleSink, createLogger } from '../../logger'\nimport { ZIDANE_VERSION } from '../../version'\nimport { createAgentsCatalog, createMcpCatalog, createModelsCatalog, createProvidersCatalog, createSkillsCatalog, createToolsCatalog, watchProviderAccounts } from '../catalog'\nimport { createCommandRegistry, createKeymap } from '../commands'\nimport { createContractRegistry } from '../contracts'\nimport { createInterceptorRegistry } from '../hooks'\nimport { createIntegrationRegistry, createMemoryAuthStore } from '../integrations'\nimport { createRpcRemoteBridge, createRpcRouter } from '../rpc'\nimport { actionScope, createSettingsDomain } from '../settings'\nimport { createMemoryRegistry, createStorageDomain } from '../storage'\nimport { createDialogRouter, createUiRegistry } from '../ui'\nimport { createExtensionContext } from './context'\nimport { createInstructionsRegistry } from './domains'\nimport { createFacetRegistry } from './facets'\nimport { createGuard, createStallMonitor } from './guard'\nimport { runSetup, settleWithin, unload as unloadOwner } from './lifecycle'\nimport { resolveLoadOrder } from './load-order'\nimport { createMemorySettingsPort, createMemoryStoragePort, EMPTY_MCP_PORT, NO_CLIENT_DIALOG_PORT, NO_INTEGRATION_FLOWS, NO_UI_CLIENT_PORT } from './memory-ports'\nimport { createOwner } from './owner'\nimport { runtimeSettingsWire } from './settings-wire'\nimport { validateDefinition } from './validate-definition'\n\n/** The agent-hook side of the hooks port. */\nexport interface RuntimeHooksPorts {\n /**\n * The agent hook bus (`Agent['hooks']`, or a fan-out over every agent).\n * Without it, observers land on a per-extension bus the registry\n * view hands to the hosts as ordinary hook handlers.\n */\n agentHooks?: HooksPort['agentHooks']\n /** See {@link HooksPort.sessionIdOf}. */\n sessionIdOf?: HooksPort['sessionIdOf']\n /**\n * The host calls `outputs.hostEvents.emit` itself. When `false` (default),\n * the registry view also exposes per-extension `runSettled` /\n * `sessionEvents` handlers so the host delivers host events through them.\n */\n emitsHostEvents?: boolean\n}\n\n/** Base data of the shared catalogs. Each falls back to an empty base. */\nexport interface RuntimeCatalogPorts {\n /** Base tools. */\n tools?: ToolsCatalogPort\n /** Base agent profiles. */\n agents?: AgentsCatalogPort\n /** Base models. */\n models?: ModelsCatalogPort\n /** Base providers. */\n providers?: ProvidersCatalogPort\n /** Base MCP servers. */\n mcp?: McpCatalogPort\n /** Base skills. */\n skills?: SkillsCatalogPort\n}\n\n/** Everything a host plugs into the runtime. Every member is optional. */\nexport interface RuntimePorts {\n /** Where `ctx.storage` keeps data. Default: in memory. */\n storage?: StoragePort\n /** Where settings values live. Default: in memory. */\n settings?: SettingsPort\n /** Where integration connections persist. Default: in memory. */\n authStore?: AuthStorePort\n /** How integration sign-in flows show their UI. Default: refuses. */\n integrationFlows?: IntegrationFlowPort\n /** Agent hooks and host events. */\n hooks?: RuntimeHooksPorts\n /** Catalog bases. */\n catalogs?: RuntimeCatalogPorts\n /** Built-in commands, slash submission and session-bound invocation members. */\n commands?: CommandHostPort\n /** User keybinding overrides. */\n keymap?: KeymapPort\n /** Clients and dialogs. Default: no client (dialogs reject with `NoUiError`). */\n dialogs?: DialogPort\n /** Panels, navigation, composer and notifications on a client. */\n uiClient?: UiClientPort\n /** Where RPC events go to remote clients. With it, the runtime exposes `rpcBridge`. */\n rpcTransport?: RpcRemoteTransport\n /** The desktop app's main-process handle; `ctx.desktop` is undefined without it. */\n desktop?: DesktopPort\n /**\n * Session, generate, workspace, artifacts and plugins ports. A missing one\n * makes that domain reject, except `plugins`, which defaults to the\n * runtime's own catalogs.\n */\n host?: HostRuntimePorts\n /** The session the current call runs for (default of `'session'` storage). */\n currentSessionId?: () => string | undefined\n}\n\n/** One extension to load. */\nexport interface RuntimeEntry {\n /** The module's default export; validated before use. */\n definition: unknown\n /** Where the extension was found. */\n source: ExtensionSource\n /** The extension's folder. Its name must equal the id. */\n dir?: string\n /** `false`: discovered but turned off. Not run; settings stay readable. Default `true`. */\n enabled?: boolean\n /** Its manifest (`extension.json`, `package.json#zidane`): the display name and icon when the definition has none. */\n manifest?: ExtensionManifest\n /**\n * Why the module could not be imported (a syntax error, no definition). The\n * entry is listed as `failed` with this error and never validated, so a\n * later {@link ExtensionRuntime.reload} of its folder can bring it up.\n */\n error?: string\n}\n\n/** Options of {@link createExtensionRuntime}. */\nexport interface ExtensionRuntimeOptions {\n /** The host process. */\n host: ExtensionHostKind\n /** Paths handed to every extension. */\n paths: ExtensionPaths\n /** Host ports. */\n ports?: RuntimePorts\n /** Base logger; each extension logs through `logger.with({ extension })`. Default: warnings to stderr. */\n logger?: Logger\n /** Process-wide `ctx.storage.memory`. Default: one registry per process. */\n memory?: MemoryRegistry\n /** Error budget of each guard. `false` never trips. */\n budget?: Partial<ErrorBudget> | false\n /** Default bound of guarded callbacks, in ms. */\n callbackTimeoutMs?: number\n /** Bound of `setup`, in ms. */\n setupTimeoutMs?: number\n /**\n * How long an unloaded extension's teardown waits for a call in flight that\n * has no bound of its own (a command run, a tool execute), in ms. Default\n * `DEFAULT_DRAIN_MS` (`owner.ts`): 30 minutes.\n */\n drainTimeoutMs?: number\n /**\n * Imports an entry's module again for {@link ExtensionRuntime.reload}.\n * Default: entries with a folder (`project`, `user`, `config`) are\n * imported fresh from it (`loadExtensionFolder`, module graph evicted\n * first); `inline` and `builtin` entries keep their definition.\n */\n reimport?: (entry: RuntimeEntry) => Promise<RuntimeEntry>\n /** Receives event-loop stalls (after they are logged). */\n onStall?: (report: StallReport) => void\n /** Called after an extension's status changed (loaded, failed, disabled by its guard, unloaded). */\n onChange?: (info: ExtensionInfo | { id: string, status: 'unloaded' }) => void\n /** zidane version for `ctx.app`. Default: this package's. */\n version?: string\n /** Platform for `ctx.app` and keymap `mod`. Default `process.platform`. */\n platform?: string\n /**\n * Receives the promise of every async guarded callback (observers, RPC\n * handlers, panel loads). A test seam: the testing kit waits on them so a\n * fired event has been handled before it returns.\n */\n trackCalls?: (pending: Promise<unknown>) => void\n}\n\n/** The loaded state of one extension, for hosts and the registry view. */\nexport interface RuntimeExtension {\n /** The extension id. */\n readonly id: string\n /** The entry it was loaded from. */\n readonly entry: RuntimeEntry\n /** The validated definition; absent when validation failed. */\n readonly definition?: ExtensionDefinition\n /** Status and metadata, as `ctx.extensions` shows it. */\n readonly info: ExtensionInfo\n /** Present while active. */\n readonly guard?: RuntimeGuard\n /** Present while active. */\n readonly settings?: SettingsDomainInstance\n /** Validation warnings and load-order issues about this extension. */\n readonly warnings: readonly string[]\n}\n\n/** Handlers an extension put on its own agent-hook bus and host events (when the host gave no agent hooks). */\nexport interface ExtensionHookHandlers {\n /** Agent-hook handlers, by hook name. */\n readonly agent: ReadonlyMap<string, ReadonlySet<(...args: unknown[]) => unknown>>\n /** Host-event handlers, by event name. */\n readonly host: ReadonlyMap<HostEventName, ReadonlySet<(event: never) => void>>\n}\n\n/** What {@link createExtensionRuntime} returns. */\nexport interface ExtensionRuntime {\n /** Loads entries (in dependency order, after those already loaded). Never rejects. */\n load: (entries: readonly RuntimeEntry[]) => Promise<readonly ExtensionInfo[]>\n /** Unloads an extension and forgets it. `forget: true` also clears its `ctx.storage.memory`. */\n unload: (id: string, opts?: { forget?: boolean }) => Promise<void>\n /**\n * Reloads one extension in place: its owner is disposed (registrations\n * withdrawn, cleanups run), its module imported again from its folder\n * (`options.reimport`), and `setup` runs again at the same load-order\n * position. Other extensions are untouched; `ctx.storage.memory`\n * survives. `opts.entry` replaces the entry instead of re-importing.\n * Resolves with the new status, or `undefined` for an unknown id.\n */\n reload: (id: string, opts?: { entry?: RuntimeEntry }) => Promise<ExtensionInfo | undefined>\n /** The id of the extension loaded from `dir`, if any. */\n idOfDir: (dir: string) => string | undefined\n /** The shared registries. */\n readonly outputs: ExtensionRuntimeOutputs\n /** Every known extension, in load order. */\n extensions: () => ExtensionInfo[]\n /** One extension's state. */\n get: (id: string) => RuntimeExtension | undefined\n /** Settings of every known extension (active and disabled) in the Settings wire format. */\n settingsWire: () => WireSettings\n /** Loads `'session'` storage of every active extension for a run. Failures are logged. */\n preloadSession: (sessionId: string) => Promise<void>\n /**\n * Checks a client's write to an extension's storage against what the\n * extension holds (a store's version and schema): why it is refused, or\n * `undefined` (also for an extension that is not active).\n */\n checkStorageWrite: (loc: StorageLocation, area: StorageArea, key: string, value: Json | undefined) => Promise<string | undefined>\n /** An extension's own agent-hook and host-event handlers. */\n hookHandlers: (id: string) => ExtensionHookHandlers\n /** Artifact kinds an extension registered (`ctx.artifacts.kinds.register`), callbacks guarded. */\n artifactKinds: (id: string) => readonly ArtifactKindEntry[]\n /** Agent Plugins an extension loaded (`ctx.plugins.load`). */\n plugins: (id: string) => readonly LoadedPluginRecord[]\n /**\n * Calls `listener` after an extension's status changed (loaded, failed,\n * disabled by its guard, unloaded) or it registered or released an\n * artifact kind, an Agent Plugin or the first observer of an agent hook.\n * The registry view re-reads on it. Returns the unsubscribe.\n */\n subscribe: (listener: () => void) => () => void\n /** Whether the host gave its own agent hooks / emits host events (the registry view skips those parts). */\n readonly hostWired: { agentHooks: boolean, hostEvents: boolean }\n /** The protocol side of RPC, when the host gave a transport. */\n readonly rpcBridge?: RpcRemoteBridge\n /** Load-order issues of the last `load`. */\n readonly issues: readonly LoadOrderIssue[]\n /** Unloads everything and releases the registries. */\n dispose: () => Promise<void>\n}\n\n/** One per process: `ctx.storage.memory` survives reloads and registry rebuilds. */\nconst processMemory = createMemoryRegistry()\n\ninterface MutableRecord {\n id: string\n entry: RuntimeEntry\n definition?: ExtensionDefinition\n info: ExtensionInfo\n guard?: RuntimeGuard\n owner?: RuntimeOwner\n settings?: SettingsDomainInstance\n storage?: StorageRuntime\n warnings: string[]\n /** The running {@link deactivateRecord} of the last active owner, so a later unload waits for a teardown the guard started. */\n deactivating?: Promise<void>\n /** Set when that owner was unloaded with calls in flight: its teardown, once they ended. Runtime dispose waits for it. */\n teardown?: Promise<void>\n agent: Map<string, Set<(...args: unknown[]) => unknown>>\n host: Map<HostEventName, Set<(event: never) => void>>\n}\n\n/** Live entries kept per extension; a Disposable takes its entry out. */\n/** An extension's own settings actions, as the UI registry runs them for `setting.action` with its id as page id. */\nfunction ownSettingActions(settings: SettingsDomainInstance | undefined): OwnSettingActions | undefined {\n if (!settings)\n return undefined\n const action = (key: string): ActionSetting | undefined => {\n const item = Object.hasOwn(settings.schema.items, key) ? settings.schema.items[key] : undefined\n return item?.type === 'action' ? item : undefined\n }\n return {\n run: async (key, signal) => action(key) ? { message: (await settings.runAction(key, { signal })).message } : undefined,\n status: key => settings.actionStatus(key),\n scope: (key) => {\n const item = action(key)\n return item ? actionScope(item) : undefined\n },\n }\n}\n\nfunction keep<T>(list: T[], item: T): { dispose: () => void } {\n list.push(item)\n return {\n dispose: () => {\n const at = list.indexOf(item)\n if (at >= 0)\n list.splice(at, 1)\n },\n }\n}\n\nfunction issueText(issue: LoadOrderIssue): string {\n switch (issue.kind) {\n case 'missing': return `dependency \"${issue.dependency}\" (${issue.range}) is not installed`\n case 'version': return `dependency \"${issue.dependency}\" is ${issue.version}, needs ${issue.range}`\n case 'cycle': return `dependency cycle ${issue.ids.join(' → ')}; loaded \"${issue.brokenAt}\" first`\n case 'duplicate': return `another extension with id \"${issue.id}\" was loaded first`\n }\n}\n\nfunction idOf(entry: RuntimeEntry): string {\n const def = entry.definition as { id?: unknown, name?: unknown } | undefined\n if (def && typeof def.id === 'string' && def.id)\n return def.id\n if (entry.dir)\n return basename(entry.dir)\n // A definition that fails validation for lack of an `id` may still say what it is called.\n return def && typeof def.name === 'string' && def.name ? def.name : '(unknown)'\n}\n\n/** The registries and host ports one runtime shares across its extensions. */\ninterface Shared {\n outputs: ExtensionRuntimeOutputs\n services: ContextServices\n hostListeners: Set<HostListener>\n /** `oauth:refresh` observers, also told of integration refreshes (which run outside any agent). */\n refreshObservers: Set<(event: OAuthRefreshHookContext) => void>\n artifactKinds: ArtifactKindEntry[]\n pluginRecords: LoadedPluginRecord[]\n /** Tells {@link ExtensionRuntime.subscribe} listeners. */\n changed: () => void\n /** Tells `options.onChange`, then the {@link ExtensionRuntime.subscribe} listeners. */\n statusChanged: (info: ExtensionInfo | { id: string, status: 'unloaded' }) => void\n /** {@link ExtensionRuntime.subscribe}. */\n subscribe: (listener: () => void) => () => void\n /** The listeners of {@link ExtensionRuntime.subscribe}. */\n changeListeners: Set<() => void>\n rpcBridge?: RpcRemoteBridge\n /** Releases what the shared registries hold (RPC bridge, commands, buffered toasts). */\n release: () => void\n /** Counts one withdrawal ({@link ExtensionRuntimeOutputs.withdrawals}). */\n withdrawn: () => void\n}\n\ninterface HostListener { name: HostEventName, fn: (event: never) => void, ext: string }\n\n/** Builds the shared registries over the host's ports (or their in-memory fallbacks). */\nfunction createShared(options: ExtensionRuntimeOptions, ports: RuntimePorts, baseLogger: Logger, records: ReadonlyMap<string, MutableRecord>, order: readonly string[], rank: (id: string) => number): Shared {\n const loadOrder = { order: rank }\n const hostListeners = new Set<HostListener>()\n const refreshObservers = new Set<(event: OAuthRefreshHookContext) => void>()\n const hostEvents: HostEventSink = {\n emit: (name, event) => {\n for (const l of [...hostListeners]) {\n if (l.name === name)\n l.fn(event as never)\n }\n },\n }\n\n const commands = createCommandRegistry({\n ...(ports.commands ? { port: ports.commands } : {}),\n keymap: createKeymap({ ...(ports.keymap ? { port: ports.keymap } : {}), ...(options.platform ? { platform: options.platform } : {}), logger: baseLogger }),\n logger: baseLogger,\n })\n const ui = createUiRegistry({ logger: baseLogger, settingsAccess: id => records.get(id)?.settings?.actionAccess, ownActions: id => ownSettingActions(records.get(id)?.settings), commands: { has: id => commands.get(id) !== undefined, subscribe: listener => commands.subscribe(listener) } })\n const rpc = createRpcRouter()\n const instructions = createInstructionsRegistry({ order: rank })\n // The host computes them: handed to its session control once an extension uses them.\n const facets: ReturnType<typeof createFacetRegistry> = createFacetRegistry({ order: rank, attachHost: registry => ports.host?.sessions?.sessionControl()?.attachFacets?.(registry) })\n const artifactKinds: ArtifactKindEntry[] = []\n const pluginRecords: LoadedPluginRecord[] = []\n const changeListeners = new Set<() => void>()\n const changed = (): void => {\n for (const listener of [...changeListeners]) {\n try {\n listener()\n }\n catch {}\n }\n }\n const statusChanged = (info: ExtensionInfo | { id: string, status: 'unloaded' }): void => {\n try {\n options.onChange?.(info)\n }\n catch {}\n changed()\n }\n const subscribe = (listener: () => void): (() => void) => {\n changeListeners.add(listener)\n return () => {\n changeListeners.delete(listener)\n }\n }\n let withdrawals = 0\n const outputs: ExtensionRuntimeOutputs = {\n withdrawals: () => withdrawals,\n interceptors: createInterceptorRegistry({ loadOrder: rank }),\n catalogs: {\n tools: createToolsCatalog(ports.catalogs?.tools ?? { base: () => [] }, loadOrder),\n agents: createAgentsCatalog(ports.catalogs?.agents ?? { profiles: () => [] }, loadOrder),\n models: createModelsCatalog(ports.catalogs?.models ?? { models: () => [] }, loadOrder),\n providers: createProvidersCatalog(ports.catalogs?.providers ?? { providers: () => [] }, loadOrder),\n mcp: createMcpCatalog(ports.catalogs?.mcp ?? EMPTY_MCP_PORT, loadOrder),\n skills: createSkillsCatalog(ports.catalogs?.skills ?? { skills: () => [] }, loadOrder),\n },\n instructions,\n ui,\n commands,\n rpc,\n contracts: createContractRegistry({ loadOrder: id => (order.includes(id) ? rank(id) : undefined) }),\n integrations: createIntegrationRegistry({\n store: ports.authStore ?? createMemoryAuthStore(),\n logger: baseLogger,\n onRefresh: (event) => {\n for (const fn of [...refreshObservers])\n fn(structuredClone(event))\n },\n }),\n hostEvents,\n facets,\n }\n const rpcBridge = ports.rpcTransport ? createRpcRemoteBridge(rpc, ports.rpcTransport) : undefined\n // Provider transforms read accounts (per-account model lists): re-run them when an integration connection or a stored provider account changes.\n const unwatchAccounts = watchProviderAccounts(outputs.catalogs.providers, outputs.integrations, [onProviderAccountsChange])\n\n const hostPorts: HostRuntimePorts = { ...ports.host }\n const hostArtifacts = ports.host?.artifacts\n if (hostArtifacts) {\n hostPorts.artifacts = {\n ...hostArtifacts,\n registerKind: (entry) => {\n const kept = keep(artifactKinds, entry)\n const forwarded = hostArtifacts.registerKind?.(entry)\n changed()\n return {\n dispose: () => {\n kept.dispose()\n forwarded?.dispose()\n changed()\n },\n }\n },\n }\n }\n const hostPlugins = ports.host?.plugins\n const defaultPlugins: PluginsPort = {\n extension: (id) => {\n const r = records.get(id)\n return r ? { ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}), source: r.entry.source, paths: options.paths, ...(r.storage ? { storagePath: r.storage.storage.path } : {}) } : undefined\n },\n registerSkill: (skill, origin) => outputs.catalogs.skills.register(skill, origin),\n registerMcpServer: (server, origin) => outputs.catalogs.mcp.register(server, origin),\n }\n const basePlugins = hostPlugins ?? defaultPlugins\n hostPorts.plugins = {\n ...basePlugins,\n recordPlugin: (record) => {\n const kept = keep(pluginRecords, record)\n const forwarded = basePlugins.recordPlugin?.(record)\n changed()\n return {\n dispose: () => {\n kept.dispose()\n forwarded?.dispose()\n changed()\n },\n }\n },\n }\n\n const services: ContextServices = {\n app: { name: 'zidane', version: options.version ?? ZIDANE_VERSION, host: options.host, platform: options.platform ?? process.platform },\n interceptors: outputs.interceptors,\n catalogs: outputs.catalogs,\n instructions,\n facets,\n ui,\n dialogs: createDialogRouter(ports.dialogs ?? NO_CLIENT_DIALOG_PORT),\n uiClient: ports.uiClient ?? NO_UI_CLIENT_PORT,\n commands,\n rpc,\n contracts: outputs.contracts,\n integrations: outputs.integrations,\n integrationFlows: ports.integrationFlows ?? NO_INTEGRATION_FLOWS,\n host: hostPorts,\n ...(ports.desktop ? { desktop: ports.desktop } : {}),\n ...(options.platform ? { platform: options.platform } : {}),\n extensions: {\n list: () => order.map(id => records.get(id)).filter((r): r is MutableRecord => !!r).map(r => r.info),\n get: (id) => {\n const r = records.get(id)\n return r?.info\n },\n },\n }\n\n const release = (): void => {\n unwatchAccounts()\n rpcBridge?.dispose()\n commands.dispose()\n services.dialogs.dispose()\n }\n\n const withdrawn = (): void => {\n withdrawals++\n }\n\n return { outputs, services, hostListeners, refreshObservers, artifactKinds, pluginRecords, changed, statusChanged, subscribe, changeListeners, ...(rpcBridge ? { rpcBridge } : {}), release, withdrawn }\n}\n\n/** The per-extension hooks port: the host's bus when given, else the extension's own. */\nfunction createHooksPort(r: MutableRecord, ports: RuntimePorts, hostListeners: Set<HostListener>, refreshObservers: Set<(event: OAuthRefreshHookContext) => void>, changed: () => void): HooksPort {\n const bus: HooksPort['agentHooks'] = ports.hooks?.agentHooks ?? {\n hook: ((name: string, fn: (...args: unknown[]) => unknown) => {\n let set = r.agent.get(name)\n const first = !set\n if (!set) {\n set = new Set()\n r.agent.set(name, set)\n }\n set.add(fn)\n // The registry view hands out one dispatcher per hook name: a new name needs a new read.\n if (first)\n changed()\n return () => { set.delete(fn) }\n }) as HooksPort['agentHooks']['hook'],\n }\n // `oauth:refresh` observers also hear integration refreshes, which no agent bus carries.\n const agentHooks: HooksPort['agentHooks'] = {\n hook: ((name: string, fn: (...args: unknown[]) => unknown) => {\n const off = (bus.hook as (name: string, fn: (...args: unknown[]) => unknown) => () => void)(name, fn)\n if (name !== 'oauth:refresh')\n return off\n const observer = fn as (event: OAuthRefreshHookContext) => void\n refreshObservers.add(observer)\n return () => {\n refreshObservers.delete(observer)\n off()\n }\n }) as HooksPort['agentHooks']['hook'],\n }\n return {\n agentHooks,\n hostEvents: {\n on: <K extends HostEventName>(name: K, fn: (event: HookEvents[K]) => void) => {\n const listener = { name, fn: fn as (event: never) => void, ext: r.id }\n hostListeners.add(listener)\n let set = r.host.get(name)\n if (!set) {\n set = new Set()\n r.host.set(name, set)\n }\n set.add(listener.fn)\n return () => {\n hostListeners.delete(listener)\n set.delete(listener.fn)\n }\n },\n },\n ...(ports.hooks?.sessionIdOf ? { sessionIdOf: ports.hooks.sessionIdOf } : {}),\n }\n}\n\n/** Validates new entries and orders the loadable ones after the known ones. Pure apart from the records it makes. */\nfunction prepareLoad(entries: readonly RuntimeEntry[], known: readonly MutableRecord[], status: (r: MutableRecord, status: ExtensionInfo['status'], error?: string) => void, logger: Logger): { fresh: MutableRecord[], sequence: MutableRecord[], issues: readonly LoadOrderIssue[] } {\n const taken = new Set(known.map(r => r.id))\n const fresh: MutableRecord[] = []\n for (const entry of entries) {\n const id = idOf(entry)\n const r: MutableRecord = { id, entry, info: { id, displayName: id, source: entry.source, status: 'failed' }, warnings: [], agent: new Map(), host: new Map() }\n fresh.push(r)\n if (entry.error !== undefined) {\n status(r, 'failed', entry.error)\n continue\n }\n const folderName = entry.dir && entry.source !== 'inline' && entry.source !== 'builtin' ? basename(entry.dir) : undefined\n const result = validateDefinition(entry.definition, folderName !== undefined ? { folderName } : {})\n r.warnings.push(...result.warnings.map(w => (w.path ? `${w.path}: ${w.message}` : w.message)))\n if (!result.ok) {\n status(r, 'failed', result.errors.map(e => (e.path ? `${e.path}: ${e.message}` : e.message)).join('; '))\n continue\n }\n r.definition = result.definition\n if (taken.has(id)) {\n status(r, 'failed', `Duplicate extension id \"${id}\" ignored; the earlier one wins.`)\n continue\n }\n taken.add(id)\n }\n const loadable = fresh.filter(r => r.definition && r.info.error === undefined)\n const resolved = resolveLoadOrder([...known.filter(r => r.definition), ...loadable].map(r => ({\n id: r.id,\n ...(r.definition!.version !== undefined ? { version: r.definition!.version } : {}),\n ...(r.definition!.dependencies ? { dependencies: r.definition!.dependencies } : {}),\n r,\n })))\n for (const issue of resolved.issues) {\n const about = issue.kind === 'cycle' ? issue.brokenAt : issue.id\n const r = loadable.find(x => x.id === about)\n if (r && issue.kind !== 'duplicate') {\n r.warnings.push(issueText(issue))\n logger.warn(issueText(issue), { extension: about })\n }\n }\n const loadIds = new Set(loadable.map(r => r.id))\n return { fresh, sequence: resolved.order.filter(e => loadIds.has(e.id)).map(e => e.r), issues: resolved.issues }\n}\n\n/** A record as hosts see it. */\nfunction view(r: MutableRecord): RuntimeExtension {\n return {\n id: r.id,\n entry: r.entry,\n ...(r.definition ? { definition: r.definition } : {}),\n info: r.info,\n ...(r.guard ? { guard: r.guard } : {}),\n ...(r.settings ? { settings: r.settings } : {}),\n warnings: r.warnings,\n }\n}\n\n/** Loads one session's storage for every active record; failures are logged. */\nasync function preloadSessions(records: readonly MutableRecord[], sessionId: string, logger: Logger): Promise<void> {\n await Promise.all(records.map(async (r) => {\n try {\n await r.storage?.preload('session', sessionId)\n }\n catch (error) {\n logger.warn('session storage could not be loaded', { extension: r.id, sessionId, error: String(error) })\n }\n }))\n}\n\n/**\n * Ends a record's active state: its owner is disposed (registrations\n * withdrawn, cleanups run) and its async cleanups get the unload bound; one\n * still running then is logged and left alone. Called again while that runs\n * (an unload after the guard tripped), it waits for the same teardown.\n * `withdrawn` is told before an active owner's registrations go.\n */\nfunction deactivateRecord(r: MutableRecord, logger: Logger, withdrawn: () => void): Promise<void> {\n const owner = r.owner\n r.owner = undefined\n r.guard = undefined\n r.settings = undefined\n r.storage = undefined\n if (!owner) {\n r.agent.clear()\n r.host.clear()\n return r.deactivating ?? Promise.resolve()\n }\n withdrawn()\n owner.dispose()\n // Calls in flight: the teardown comes once they end. A reload goes on now; a runtime dispose waits for it.\n if (owner.draining)\n r.teardown = awaitTeardown(owner, r.id, logger)\n r.deactivating = (async () => {\n const outcome = await unloadOwner(owner)\n if (!outcome.ok)\n logger.warn(`unload: ${outcome.error}`, { extension: r.id })\n r.agent.clear()\n r.host.clear()\n })()\n return r.deactivating\n}\n\n/**\n * Waits for a draining owner's teardown: it runs once its calls in flight\n * ended (bounded by the drain bound), then its async cleanups get the unload bound.\n */\nfunction awaitTeardown(owner: RuntimeOwner, id: string, logger: Logger): Promise<void> {\n return new Promise((resolve) => {\n // The unload bound starts with the teardown (the owner aborts its signal then), not later.\n const started = (): void => {\n void settleWithin(owner.settled).then((outcome) => {\n if (!outcome.ok)\n logger.warn(`unload: ${outcome.error}`, { extension: id })\n resolve()\n })\n }\n if (owner.tornDown)\n started()\n else\n owner.signal.addEventListener('abort', started, { once: true })\n })\n}\n\n/**\n * One extension's guard and root owner. Every guarded call holds a lease on\n * the owner, and the owner logs a deferred teardown on the extension's logger.\n */\nfunction createGuardedOwner(id: string, logger: Logger, stalls: StallMonitor, options: ExtensionRuntimeOptions, onTrip: (trip: GuardTrip, guard: RuntimeGuard) => void): { guard: RuntimeGuard, owner: RuntimeOwner } {\n let owner: RuntimeOwner | undefined\n const guard: RuntimeGuard = createGuard({\n extensionId: id,\n logger,\n stalls,\n ...(options.budget !== undefined ? { budget: options.budget } : {}),\n ...(options.callbackTimeoutMs !== undefined ? { timeoutMs: options.callbackTimeoutMs } : {}),\n // Set below, before any callback runs.\n lease: (label, leaseOpts) => owner!.lease(label, leaseOpts),\n onTrip: trip => onTrip(trip, guard),\n })\n const track = options.trackCalls\n if (track) {\n const call = guard.call\n guard.call = (label, fn, opts) => {\n const pending = call(label, fn, opts)\n track(pending)\n return pending\n }\n }\n owner = createOwner(undefined, {\n onError: (error, label) => guard.report(label, error),\n label: id,\n ...(options.drainTimeoutMs !== undefined ? { drainMs: options.drainTimeoutMs } : {}),\n onDrain: ({ active, ms }) => logger.warn(`unloaded with ${active.length} call${active.length === 1 ? '' : 's'} in flight (${active.join(', ')}): its registrations are withdrawn, the rest is torn down once they finish (at most ${Math.round(ms / 1000)}s)`, { active, boundMs: ms }),\n onDrainTimeout: ({ active, ms }) => logger.warn(`calls still running ${Math.round(ms / 1000)}s after unload (${active.join(', ')}): tearing down now`, { active }),\n })\n return { guard, owner }\n}\n\n/** Runs async work one at a time, in call order; a failure does not stop the next. */\nfunction createSerial(): <T>(work: () => Promise<T>) => Promise<T> {\n let queue: Promise<unknown> = Promise.resolve()\n return <T>(work: () => Promise<T>): Promise<T> => {\n const next = queue.then(work, work)\n queue = next.catch(() => undefined)\n return next\n }\n}\n\n/** What {@link reloadInPlace} needs of the runtime. */\ninterface ReloadContext {\n records: Map<string, MutableRecord>\n order: readonly string[]\n removeUi: (id: string) => void\n logger: Logger\n reimport: (entry: RuntimeEntry) => Promise<RuntimeEntry>\n disposed: () => boolean\n withdrawn: () => void\n setStatus: (r: MutableRecord, status: ExtensionInfo['status'], error?: string) => void\n activate: (r: MutableRecord) => Promise<void>\n unload: (id: string) => Promise<void>\n load: (entries: readonly RuntimeEntry[]) => Promise<readonly ExtensionInfo[]>\n}\n\n/** {@link ExtensionRuntime.reload}: the record is replaced at its place in the load order. */\nasync function reloadInPlace(c: ReloadContext, id: string, opts: { entry?: RuntimeEntry }): Promise<ExtensionInfo | undefined> {\n const r = c.records.get(id)\n if (!r || c.disposed())\n return undefined\n let entry = opts.entry\n if (!entry) {\n try {\n entry = await c.reimport(r.entry)\n }\n catch (error) {\n entry = { ...r.entry, definition: undefined, error: `Failed to import: ${error instanceof Error ? error.message : String(error)}` }\n }\n }\n if (entry.enabled === undefined && r.entry.enabled !== undefined)\n entry = { ...entry, enabled: r.entry.enabled }\n await deactivateRecord(r, c.logger, c.withdrawn)\n c.removeUi(id)\n if (c.disposed() || c.records.get(id) !== r)\n return undefined\n const known = c.order.filter(other => other !== id).map(other => c.records.get(other)!)\n const prepared = prepareLoad([entry], known, c.setStatus, c.logger)\n const next = prepared.fresh[0]!\n if (next.id !== id) {\n // The module now declares another id: the old one goes, the new one loads after the others.\n await c.unload(id)\n const [info] = await c.load([entry])\n return info\n }\n c.records.set(id, next)\n if (!prepared.sequence.includes(next))\n return next.info\n for (const warning of next.warnings)\n c.logger.warn(warning, { extension: id })\n if (entry.enabled === false) {\n c.setStatus(next, 'disabled')\n return next.info\n }\n await c.activate(next)\n return next.info\n}\n\n/**\n * The default {@link ExtensionRuntimeOptions.reimport}: an entry with a\n * folder is imported fresh from it; any other keeps its definition.\n * Discovery is loaded on first use, so a host that never reloads never\n * pays for it.\n */\nfunction defaultReimport(): (entry: RuntimeEntry) => Promise<RuntimeEntry> {\n return async (entry) => {\n if (entry.dir === undefined || entry.source === 'inline' || entry.source === 'builtin')\n return entry\n const [{ loadExtensionFolder }, { runtimeEntryOf }] = await Promise.all([import('../discovery'), import('./loaded-entry')])\n const loaded = await loadExtensionFolder(entry.dir, { source: entry.source === 'project' ? 'project' : 'user' })\n return { ...runtimeEntryOf(loaded, entry.enabled), source: entry.source }\n }\n}\n\n/**\n * Creates the extension runtime of one host.\n *\n * @param options - Host kind, paths, ports and guard settings.\n * @returns The runtime.\n */\nexport function createExtensionRuntime(options: ExtensionRuntimeOptions): ExtensionRuntime {\n const ports = options.ports ?? {}\n const baseLogger = options.logger ?? createLogger(consoleSink({ minLevel: 'warn' }))\n const memory = options.memory ?? processMemory\n const storagePort = ports.storage ?? createMemoryStoragePort()\n const settingsPort = ports.settings ?? createMemorySettingsPort()\n const records = new Map<string, MutableRecord>()\n const order: string[] = []\n let issues: readonly LoadOrderIssue[] = []\n let disposed = false\n\n const rank = (id: string): number => {\n const at = order.indexOf(id)\n return at === -1 ? Number.MAX_SAFE_INTEGER : at\n }\n\n const { outputs, services, hostListeners, refreshObservers, artifactKinds, pluginRecords, changed, statusChanged, subscribe, changeListeners, rpcBridge, release, withdrawn } = createShared(options, ports, baseLogger, records, order, rank)\n const { ui } = outputs\n\n const stalls = createStallMonitor({\n onStall: (report) => {\n baseLogger.warn(`${report.label} blocked the event loop for ${Math.round(report.durationMs)}ms`, { extension: report.extensionId, label: report.label, durationMs: report.durationMs })\n options.onStall?.(report)\n },\n })\n\n const setStatus = (r: MutableRecord, status: ExtensionInfo['status'], error?: string): void => {\n const def = r.definition\n const manifest = r.entry.manifest\n const icon = def?.icon ?? manifest?.icon\n r.info = {\n id: r.id,\n displayName: def?.displayName ?? manifest?.displayName ?? r.id,\n ...(icon !== undefined ? { icon: { ...icon } } : {}),\n ...(def?.version !== undefined ? { version: def.version } : {}),\n source: r.entry.source,\n status,\n ...(error !== undefined ? { error } : {}),\n }\n statusChanged(r.info)\n }\n\n const activate = async (r: MutableRecord): Promise<void> => {\n const def = r.definition!\n const logger = baseLogger.with({ extension: r.id })\n const { guard, owner } = createGuardedOwner(r.id, logger, stalls, options, (trip, tripped) => {\n if (r.guard !== tripped)\n return\n setStatus(r, 'failed', `Disabled: ${trip.reason}`)\n void deactivateRecord(r, baseLogger, withdrawn)\n })\n const deps: DomainDeps = { extensionId: r.id, owner, guard, logger }\n const settings = createSettingsDomain(deps, settingsPort, def.settings)\n const storage = createStorageDomain(deps, storagePort, {\n paths: options.paths,\n ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}),\n memory,\n ...(ports.currentSessionId ? { currentSessionId: ports.currentSessionId } : {}),\n })\n r.guard = guard\n r.owner = owner\n r.settings = settings\n r.storage = storage\n const preloaded = await Promise.allSettled([storage.preload('user'), storage.preload('project')])\n for (const result of preloaded) {\n if (result.status === 'rejected')\n logger.warn('storage could not be loaded before setup; reads start empty', { error: String(result.reason) })\n }\n const hooks = createHooksPort(r, ports, hostListeners, refreshObservers, changed)\n const input = {\n definition: def,\n source: r.entry.source,\n ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}),\n paths: options.paths,\n logger,\n guard,\n hooks,\n storage,\n settings,\n }\n const outcome = await runSetup(def, o => createExtensionContext(input, services, o), owner, guard, {\n ...(options.setupTimeoutMs !== undefined ? { timeoutMs: options.setupTimeoutMs } : {}),\n })\n if (r.owner !== owner)\n return\n if (!outcome.ok) {\n logger.error('setup failed', { reason: outcome.reason, error: outcome.error })\n r.owner = undefined\n r.guard = undefined\n r.settings = undefined\n r.storage = undefined\n r.agent.clear()\n r.host.clear()\n setStatus(r, 'failed', outcome.error)\n return\n }\n for (const warning of outcome.warnings)\n logger.warn(warning)\n if (guard.tripped)\n return\n setStatus(r, 'active')\n }\n\n // load, unload and reload run one at a time: a reload racing a load would see half-built records.\n const serial = createSerial()\n\n const loadNow = async (entries: readonly RuntimeEntry[]): Promise<readonly ExtensionInfo[]> => {\n if (disposed)\n return []\n const prepared = prepareLoad(entries, order.map(id => records.get(id)!), setStatus, baseLogger)\n const { fresh, sequence } = prepared\n issues = prepared.issues\n\n // Failed records are listed too (Settings shows them), after the loadable ones.\n for (const r of sequence) {\n records.set(r.id, r)\n order.push(r.id)\n }\n for (const r of fresh) {\n if (!sequence.includes(r) && !records.has(r.id)) {\n records.set(r.id, r)\n order.push(r.id)\n }\n }\n for (const r of sequence) {\n if (disposed)\n break\n for (const warning of r.warnings)\n baseLogger.warn(warning, { extension: r.id })\n if (r.entry.enabled === false) {\n setStatus(r, 'disabled')\n continue\n }\n await activate(r)\n }\n return fresh.map(r => r.info)\n }\n\n const unloadNow = async (id: string, opts: { forget?: boolean } = {}): Promise<void> => {\n const r = records.get(id)\n if (!r)\n return\n records.delete(id)\n order.splice(order.indexOf(id), 1)\n await deactivateRecord(r, baseLogger, withdrawn)\n ui.removeExtension(id)\n if (opts.forget) {\n memory.clear(id)\n // Uninstalled: hosts delete its stored facet values (a plain unload keeps them).\n services.facets.forget(id)\n }\n statusChanged({ id, status: 'unloaded' })\n }\n\n const reimport = options.reimport ?? defaultReimport()\n const reloadContext: ReloadContext = { records, order, removeUi: id => ui.removeExtension(id), logger: baseLogger, reimport, disposed: () => disposed, withdrawn, setStatus, activate, unload: unloadNow, load: loadNow }\n\n return {\n load: entries => serial(() => loadNow(entries)),\n unload: (id, opts) => serial(() => unloadNow(id, opts)),\n reload: (id, opts) => serial(() => reloadInPlace(reloadContext, id, opts ?? {})),\n idOfDir: dir => order.find(id => records.get(id)?.entry.dir === dir),\n outputs,\n extensions: () => services.extensions.list().slice(),\n get: (id) => {\n const r = records.get(id)\n return r ? view(r) : undefined\n },\n settingsWire: () => runtimeSettingsWire({ extensions: () => order.map(id => ({ id })), get: id => records.get(id), outputs }),\n preloadSession: sessionId => preloadSessions(order.map(id => records.get(id)!), sessionId, baseLogger),\n checkStorageWrite: async (loc, area, key, value) => records.get(loc.extensionId)?.storage?.checkWrite(loc, area, key, value),\n hookHandlers: (id) => {\n const r = records.get(id)\n return { agent: r?.agent ?? new Map(), host: r?.host ?? new Map() }\n },\n artifactKinds: id => artifactKinds.filter(e => e.extensionId === id),\n plugins: id => pluginRecords.filter(p => p.extensionName === id),\n subscribe,\n hostWired: { agentHooks: ports.hooks?.agentHooks !== undefined, hostEvents: ports.hooks?.emitsHostEvents === true },\n ...(rpcBridge ? { rpcBridge } : {}),\n get issues() { return issues },\n dispose: async () => {\n if (disposed)\n return\n disposed = true\n withdrawn()\n // Before the extensions go: their facets withdrawn by a dispose must not read as withdrawn by the extension (the host would prune their values).\n services.facets.close()\n const all = [...order].reverse().map(id => records.get(id)!)\n await Promise.all(all.map(r => deactivateRecord(r, baseLogger, withdrawn)))\n for (const r of all)\n ui.removeExtension(r.id)\n records.clear()\n order.length = 0\n changeListeners.clear()\n // The shared registries (dialogs, commands, RPC) serve the calls still in flight: released once every extension tore down.\n await Promise.all(all.map(r => r.teardown))\n release()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,YAAY,IAAI,kBAA+B;;;;;;;;;AAUrD,SAAgB,cAAiB,QAAiC,IAAgB;CAChF,OAAO,OAAO,WAAW,aAAa,UAAU,IAAI,QAAQ,EAAE,IAAI,GAAG;AACvE;;AAGA,SAAgB,mBAA4C;CAC1D,OAAO,UAAU,SAAS;AAC5B;;;;ACXA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,MAAM,6BAA2C,IAAI,IAAqB,CAAC,gBAAgB,CAAC;;;;;;;AAQ5F,SAAgB,kBAAkB,MAAuC;CACvE,OAAQ,kBAAwC,SAAS,IAAI;AAC/D;;;;;;;AAQA,SAAgB,kBAAkB,MAAoD;CACpF,OAAO,WAAW,IAAI,IAAI;AAC5B;;AAKA,MAAM,YAAwB;CAC5B,cAAa,UAAS,MAAM;CAC5B,gBAAe,UAAS,MAAM;CAC9B,iBAAgB,UAAS,MAAM;CAC/B,kBAAiB,UAAS,MAAM;CAChC,aAAY,UAAS,MAAM,WAAW;CACtC,cAAa,UAAS,MAAM;AAC9B;;;;;;;AAQA,SAAgB,cAAc,MAAgC;CAC5D,OAAO,UAAU,UAAU,KAAA;AAC7B;;;;;;AAOA,MAAa,6BAAgD,CAAC;;;;;;;;;AAU9D,SAAgB,qBAAqB,MAAuB,OAAgD;CAC1G,IAAK,SAAS,kBAAkB,SAAS,mBAAoB,CAAC,OAC5D,OAAO,CAAC;CACV,OAAO,MAAM,QAAO,aAAY,2BAA2B,SAAS,QAAQ,CAAC;AAC/E;;AAKA,MAAM,QAAiB;CACrB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I,WAAW,CAAC,EAAE,SAAS,WAAW,KAAK,MAAM,KAAK,KAAK;EAC3H,eAAe,OAAO;GACpB,MAAM,IAAI,QAAQ,IAAI,EAAE;GACxB,OAAO;IAAE,OAAO,GAAG,yBAAS,IAAI,IAAI;IAAG,MAAM,GAAG,wBAAQ,IAAI,IAAI;GAAE;EACpE;EACA,gBAAe,OAAM,cAAc,QAAO,MAAK,EAAE,gBAAgB,EAAE;EACnE,UAAS,OAAM,cAAc,QAAO,MAAK,EAAE,kBAAkB,EAAE;EAC/D;EACA,WAAW;GAAE,YAAY,MAAM,OAAO,eAAe,KAAA;GAAW,YAAY,MAAM,OAAO,oBAAoB;EAAK;EAClH,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;EACjC,IAAI,SAAS;GAAE,OAAO;EAAO;EAC7B,SAAS,YAAY;GACnB,IAAI,UACF;GACF,WAAW;GACX,UAAU;GAEV,SAAS,OAAO,MAAM;GACtB,MAAM,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,KAAI,OAAM,QAAQ,IAAI,EAAE,CAAE;GAC3D,MAAM,QAAQ,IAAI,IAAI,KAAI,MAAK,iBAAiB,GAAG,YAAY,SAAS,CAAC,CAAC;GAC1E,KAAK,MAAM,KAAK,KACd,GAAG,gBAAgB,EAAE,EAAE;GACzB,QAAQ,MAAM;GACd,MAAM,SAAS;GACf,gBAAgB,MAAM;GAEtB,MAAM,QAAQ,IAAI,IAAI,KAAI,MAAK,EAAE,QAAQ,CAAC;GAC1C,QAAQ;EACV;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"host-uP3t08w8.js","names":["isThenable","isThenable","failure","errorMessage","errorMessage","unloadOwner"],"sources":["../src/decisions/run-scope.ts","../src/extensions/hooks/registry.ts","../src/extensions/hooks/domain.ts","../src/extensions/integrations/domain.ts","../src/extensions/integrations/store.ts","../src/extensions/ui/dialogs.ts","../src/extensions/ui/domain.ts","../src/extensions/commands/domain.ts","../src/extensions/commands/registry.ts","../src/extensions/rpc/bridge.ts","../src/extensions/contracts/ids.ts","../src/extensions/contracts/owned.ts","../src/extensions/rpc/router.ts","../src/extensions/rpc/domain.ts","../src/extensions/runtime/guard.ts","../src/extensions/catalog/agents.ts","../src/extensions/catalog/mcp.ts","../src/extensions/catalog/skills.ts","../src/extensions/catalog/tools.ts","../src/extensions/contracts/domain.ts","../src/extensions/contracts/registry.ts","../src/extensions/runtime/domains/artifacts.ts","../src/extensions/runtime/domains/generate.ts","../src/extensions/runtime/domains/instructions.ts","../src/extensions/runtime/domains/plugins.ts","../src/extensions/runtime/domains/workspace.ts","../src/extensions/runtime/context.ts","../src/extensions/runtime/lifecycle.ts","../src/extensions/runtime/load-order.ts","../src/extensions/runtime/host.ts"],"sourcesContent":["/**\n * The run a decision belongs to, for decisions made away from the hook\n * context that carries `ctx.decide` (an extension's `ctx.generate.decide`\n * called from a hook observer).\n *\n * An agent binds `decide` to each hook context of a run: decisions made\n * through it fire `decision:start` / `decision:end` on that agent's bus\n * (with the `runId`), are cancelled with the run, and in a replay-mode run\n * are journaled as steps, so a replay takes the branch the live attempt\n * took. A host that runs an observer inside {@link withRunDecide} with that\n * binding lets other callers in the observer reach the same decider through\n * {@link currentRunDecide}.\n */\n\nimport type { AgentDecide } from './types'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nconst runDecide = new AsyncLocalStorage<AgentDecide>()\n\n/**\n * Runs `fn` (and every async continuation it starts) with `decide` as the\n * current run's decider. `undefined`: `fn` runs without one.\n *\n * @param decide - The run-bound decider of the hook context (`ctx.decide`).\n * @param fn - The work.\n * @returns What `fn` returns.\n */\nexport function withRunDecide<T>(decide: AgentDecide | undefined, fn: () => T): T {\n return typeof decide === 'function' ? runDecide.run(decide, fn) : fn()\n}\n\n/** The decider bound by {@link withRunDecide} for the current async context, if any. */\nexport function currentRunDecide(): AgentDecide | undefined {\n return runDecide.getStore()\n}\n","/**\n * The interceptor chain shared by every extension. One registry per\n * runtime: each extension's `ctx.hooks.intercept` registers into it, and\n * the agent call sites (or the legacy-hook bridges) run it.\n *\n * Order: extension load order, then `priority` (higher first), then\n * registration order. Each handler gets the input and the result so far and\n * returns a replacement or `undefined` to keep it. A handler runs through\n * its extension's guard: a throw or a timeout is attributed to the\n * extension and skipped.\n */\n\nimport type { InterceptOptions, InterceptorHandler, Interceptors, SyncInterceptorName } from '../api/hooks'\nimport type { Guard } from '../runtime/deps'\nimport { readonlyView, unwrapReadonly } from './readonly'\n\n/** Name of an interceptor. */\nexport type InterceptorName = keyof Interceptors\n\n/** Interceptors run with `runInterceptors` (every one except the synchronous ones). */\nexport type AsyncInterceptorName = Exclude<InterceptorName, SyncInterceptorName>\n\n/** Every interceptor name, at runtime. Kept exhaustive at compile time. */\nexport const INTERCEPTOR_NAMES = [\n 'run',\n 'behavior',\n 'prompt',\n 'system',\n 'context',\n 'tool.call',\n 'tool.result',\n 'validation',\n 'skills.activate',\n 'mcp.tools',\n 'provider',\n 'retry',\n 'compaction',\n 'title',\n 'shell.env',\n 'http.request',\n 'http.response',\n 'tracing.redact',\n 'content-ref.resolve',\n] as const satisfies readonly InterceptorName[]\n\ntype MissingInterceptorNames = Exclude<InterceptorName, (typeof INTERCEPTOR_NAMES)[number]>\n// Fails to compile when an `Interceptors` key is absent from `INTERCEPTOR_NAMES`.\nconst _interceptorNamesExhaustive: MissingInterceptorNames extends never ? true : MissingInterceptorNames = true\nvoid _interceptorNamesExhaustive\n\nconst SYNC_NAMES: ReadonlySet<InterceptorName> = new Set<InterceptorName>(['tracing.redact'])\n\n/**\n * Whether `name` is an interceptor this runtime knows.\n *\n * @param name - Any string, from an extension.\n * @returns `true` for a key of {@link Interceptors}.\n */\nexport function isInterceptorName(name: string): name is InterceptorName {\n return (INTERCEPTOR_NAMES as readonly string[]).includes(name)\n}\n\n/**\n * Whether `name` runs on a synchronous path (`runInterceptorsSync`).\n *\n * @param name - An interceptor name.\n * @returns `true` for {@link SyncInterceptorName}.\n */\nexport function isSyncInterceptor(name: InterceptorName): name is SyncInterceptorName {\n return SYNC_NAMES.has(name)\n}\n\ntype MatchKeyOf = { [K in InterceptorName]?: (input: Interceptors[K][0]) => string | undefined }\n\n/** What `match` compares against, per interceptor. Interceptors not listed ignore `match`. */\nconst MATCH_KEY: MatchKeyOf = {\n 'tool.call': input => input.tool,\n 'tool.result': input => input.tool,\n 'http.request': input => input.provider,\n 'http.response': input => input.provider,\n 'provider': input => input.descriptor.key,\n 'mcp.tools': input => input.server,\n}\n\n/**\n * Whether interceptor `name` honours `InterceptOptions.match`.\n *\n * @param name - An interceptor name.\n * @returns `true` when the chain filters handlers by `match`.\n */\nexport function supportsMatch(name: InterceptorName): boolean {\n return MATCH_KEY[name] !== undefined\n}\n\n/**\n * Providers whose transport takes no custom fetch: `http.request` /\n * `http.response` never run for them. None today: every built-in provider\n * sends through the fetch the interceptors wrap.\n */\nexport const HTTP_UNSUPPORTED_PROVIDERS: readonly string[] = []\n\n/**\n * The providers in an `http.*` interceptor's `match` that its chain never\n * runs for (see {@link HTTP_UNSUPPORTED_PROVIDERS}).\n *\n * @param name - The interceptor name.\n * @param match - Its `match` option.\n * @returns The unsupported providers it names; empty for any other interceptor.\n */\nexport function unsupportedHttpMatch(name: InterceptorName, match: readonly string[] | undefined): string[] {\n if ((name !== 'http.request' && name !== 'http.response') || !match)\n return []\n return match.filter(provider => HTTP_UNSUPPORTED_PROVIDERS.includes(provider))\n}\n\ntype FinalOf = { [K in InterceptorName]?: (result: Interceptors[K][1]) => boolean }\n\n/** Results that end a chain: later handlers do not run. */\nconst FINAL: FinalOf = {\n 'tool.call': d => typeof d === 'object' && ('block' in d || 'result' in d),\n 'prompt': r => 'handled' in r && r.handled === true,\n}\n\ntype MergeOf = { [K in InterceptorName]?: (previous: Interceptors[K][1], next: Interceptors[K][1]) => Interceptors[K][1] }\n\n/** How a handler's result joins the result so far, where a plain replacement would lose data. */\nconst MERGE: MergeOf = {\n // Metadata namespaces accumulate along the chain: a later handler that returns only `{ result, isError }` keeps them.\n 'tool.result': (previous, next) => {\n if (!previous.metadata || next.metadata === previous.metadata)\n return next\n return { ...next, metadata: { ...previous.metadata, ...next.metadata } }\n },\n}\n\n/** Who registers an interceptor: the extension and the guard its handler runs through. */\nexport interface InterceptorRegistration extends InterceptOptions {\n /** The extension that owns the handler. Sets its place in the load order. */\n extensionId: string\n /** The extension's guard. Bounds and attributes each call. */\n guard: Guard\n}\n\n/** A registered interceptor, as `list` reports it. */\nexport interface InterceptorInfo {\n name: InterceptorName\n extensionId: string\n priority: number\n match?: readonly string[]\n}\n\n/** Options of one chain run. */\nexport interface RunInterceptorsOptions {\n /** Overrides the key `match` filters on (by default read from the input). */\n matchKey?: string\n}\n\n/** Options of {@link createInterceptorRegistry}. */\nexport interface InterceptorRegistryOptions {\n /** Position of an extension in the load order (lower runs first). Default: the order extensions first registered in. */\n loadOrder?: (extensionId: string) => number\n /** Time bound of one handler call, in ms. Default 5000. */\n timeoutMs?: number\n /** Per-interceptor time bounds, overriding `timeoutMs`. */\n timeouts?: Partial<Record<InterceptorName, number>>\n /** Hand handlers shallow read-only views of `input` and `current`. Default `true`. */\n readonlyViews?: boolean\n}\n\n/** The shared interceptor chain. */\nexport interface InterceptorRegistry {\n /**\n * Adds a handler to chain `name`.\n *\n * @returns The unregister function. Calling it twice is a no-op.\n */\n register: <K extends InterceptorName>(name: K, handler: InterceptorHandler<K>, registration: InterceptorRegistration) => () => void\n /**\n * Runs chain `name`: threads `initial` through every matching handler\n * in order and resolves to the final result.\n */\n runInterceptors: <K extends AsyncInterceptorName>(name: K, input: Interceptors[K][0], initial: Interceptors[K][1], opts?: RunInterceptorsOptions) => Promise<Interceptors[K][1]>\n /**\n * Runs a synchronous chain. A handler that returns a promise is counted as\n * an error against its extension and skipped.\n */\n runInterceptorsSync: <K extends SyncInterceptorName>(name: K, input: Interceptors[K][0], initial: Interceptors[K][1], opts?: RunInterceptorsOptions) => Interceptors[K][1]\n /** Whether chain `name` has a handler (that matches `matchKey`, when given). Lets call sites skip building inputs. */\n has: (name: InterceptorName, matchKey?: string) => boolean\n /** The registered handlers, in run order. */\n list: (name?: InterceptorName) => readonly InterceptorInfo[]\n}\n\ninterface Entry {\n name: InterceptorName\n handler: (input: unknown, current: unknown) => unknown\n extensionId: string\n guard: Guard\n priority: number\n match?: ReadonlySet<string>\n matchList?: readonly string[]\n seq: number\n active: boolean\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof (value as { then?: unknown }).then === 'function'\n}\n\n/**\n * Creates the interceptor registry. The runtime makes one and hands it to\n * every extension's hooks domain and to the agent call sites.\n *\n * @param options - Load order, time bounds, read-only views.\n * @returns An empty registry.\n */\nexport function createInterceptorRegistry(options: InterceptorRegistryOptions = {}): InterceptorRegistry {\n const chains = new Map<InterceptorName, Entry[]>()\n const firstSeen = new Map<string, number>()\n const views = options.readonlyViews !== false\n let seq = 0\n\n const orderOf = (extensionId: string): number => {\n if (options.loadOrder)\n return options.loadOrder(extensionId)\n let order = firstSeen.get(extensionId)\n if (order === undefined) {\n order = firstSeen.size\n firstSeen.set(extensionId, order)\n }\n return order\n }\n\n const compare = (a: Entry, b: Entry): number =>\n orderOf(a.extensionId) - orderOf(b.extensionId) || b.priority - a.priority || a.seq - b.seq\n\n const timeoutOf = (name: InterceptorName): number => options.timeouts?.[name] ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const keyOf = (name: InterceptorName, input: unknown, opts?: RunInterceptorsOptions): string | undefined => {\n if (opts?.matchKey !== undefined)\n return opts.matchKey\n const read = MATCH_KEY[name] as ((input: unknown) => string | undefined) | undefined\n return read?.(input)\n }\n\n const matching = (name: InterceptorName, key: string | undefined): Entry[] => {\n const chain = chains.get(name)\n if (!chain)\n return []\n const filters = supportsMatch(name)\n return chain.filter(e => !filters || !e.match || (key !== undefined && e.match.has(key)))\n }\n\n const isFinal = (name: InterceptorName, result: unknown): boolean => {\n const check = FINAL[name] as ((r: unknown) => boolean) | undefined\n return result !== undefined && check !== undefined && check(result)\n }\n\n const merge = (name: InterceptorName, previous: unknown, next: unknown): unknown => {\n const join = MERGE[name] as ((p: unknown, n: unknown) => unknown) | undefined\n return join ? join(previous, next) : next\n }\n\n const view = <T>(value: T): T => views ? readonlyView(value) : value\n const label = (e: Entry): string => `hooks.intercept('${e.name}')`\n\n return {\n register(name, handler, registration) {\n if (!isInterceptorName(name))\n throw new TypeError(`hooks.intercept: unknown interceptor \"${String(name)}\"`)\n if (typeof handler !== 'function')\n throw new TypeError(`hooks.intercept('${name}'): handler must be a function`)\n const match = registration.match ? [...registration.match] : undefined\n const entry: Entry = {\n name,\n handler: handler as Entry['handler'],\n extensionId: registration.extensionId,\n guard: registration.guard,\n priority: registration.priority ?? 0,\n ...(match ? { match: new Set(match), matchList: match } : {}),\n seq: seq++,\n active: true,\n }\n orderOf(entry.extensionId)\n const chain = chains.get(name) ?? []\n chain.push(entry)\n chain.sort(compare)\n chains.set(name, chain)\n return () => {\n if (!entry.active)\n return\n entry.active = false\n const current = chains.get(name)\n const i = current?.indexOf(entry) ?? -1\n if (current && i >= 0)\n current.splice(i, 1)\n }\n },\n\n async runInterceptors(name, input, initial, opts) {\n let current = initial\n for (const e of matching(name, keyOf(name, input, opts))) {\n if (!e.active)\n continue\n const next = await e.guard.call(label(e), () => e.handler(view(input), view(current)), { timeoutMs: timeoutOf(name) })\n if (next !== undefined)\n current = merge(name, current, unwrapReadonly(next)) as typeof current\n if (isFinal(name, current))\n break\n }\n return current\n },\n\n runInterceptorsSync(name, input, initial, opts) {\n let current = initial\n for (const e of matching(name, keyOf(name, input, opts))) {\n if (!e.active)\n continue\n const next = e.guard.callSync(label(e), () => {\n const out = e.handler(view(input), view(current))\n if (isThenable(out)) {\n // Settle it quietly: its value is never used.\n void Promise.resolve(out).catch(() => {})\n throw new TypeError(`${label(e)} must return synchronously, not a promise`)\n }\n return out\n })\n if (next !== undefined)\n current = unwrapReadonly(next) as typeof current\n if (isFinal(name, current))\n break\n }\n return current\n },\n\n has(name, matchKey) {\n const chain = chains.get(name)\n if (!chain?.length)\n return false\n return matchKey === undefined || matching(name, matchKey).length > 0\n },\n\n list(name) {\n const names = name ? [name] : [...chains.keys()]\n return names.flatMap(n => (chains.get(n) ?? []).map(e => ({\n name: e.name,\n extensionId: e.extensionId,\n priority: e.priority,\n ...(e.matchList ? { match: e.matchList } : {}),\n })))\n },\n }\n}\n","/**\n * `ctx.hooks` for one extension. `on` observes agent hooks and host\n * events through a read-only view; `intercept` joins the shared\n * {@link InterceptorRegistry}. Every registration belongs to the\n * extension's owner and goes when it is disposed.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../../agent'\nimport type { AgentDecide } from '../../decisions/types'\nimport type { Disposable } from '../api/core'\nimport type { HookEvents, HooksDomain, OnOptions } from '../api/hooks'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { InterceptorRegistry } from './registry'\nimport { isKnownHookEvent } from '../../agent-hooks'\nimport { withRunDecide } from '../../decisions/run-scope'\nimport { DisposedError } from '../api/core'\nimport { readonlyView } from './readonly'\nimport { supportsMatch, unsupportedHttpMatch } from './registry'\n\n/** Events the host reports, beside the agent hooks. */\nexport type HostEventName = 'run:settled' | 'session:event'\n\n/** The host events, at runtime. */\nexport const HOST_EVENT_NAMES = ['run:settled', 'session:event'] as const satisfies readonly HostEventName[]\n\n/** What the host gives the hooks domain. */\nexport interface HooksPort {\n /**\n * The agent hook bus: `Agent['hooks']` for a single agent, or a fan-out\n * over every agent the host runs. Handlers must be called with the hook's\n * context object.\n */\n agentHooks: Pick<Hookable<AgentHooks>, 'hook'>\n /** Host events: `run:settled` after each run, `session:event` for done, error and needs-attention. */\n hostEvents: {\n on: <K extends HostEventName>(name: K, fn: (event: HookEvents[K]) => void) => () => void\n }\n /**\n * The session an event belongs to. Called for `on(…, { sessionId })`\n * filtering; when it returns `undefined` the domain reads\n * `event.sessionId` or `event.session.id`. A host with one agent per\n * session answers from the bus the event came from.\n */\n sessionIdOf?: (name: keyof HookEvents, event: unknown) => string | undefined\n}\n\n/** Runtime options of {@link createHooksDomain}. */\nexport interface HooksDomainOptions {\n /** The registry every extension's interceptors join. */\n interceptors: InterceptorRegistry\n /** Time bound of one observer call, in ms. Default 5000. */\n observerTimeoutMs?: number\n /** Hand observers a shallow read-only view of the event. Default `true`. */\n readonlyEvents?: boolean\n}\n\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 5000\n\nfunction isHostEvent(name: string): name is HostEventName {\n return (HOST_EVENT_NAMES as readonly string[]).includes(name)\n}\n\n/**\n * The session id an event carries: `sessionId`, else `session.id`.\n *\n * @param event - A hook payload.\n * @returns The id, or `undefined` when the event names no session.\n */\nexport function sessionIdFromEvent(event: unknown): string | undefined {\n if (event === null || typeof event !== 'object')\n return undefined\n const { sessionId, session } = event as { sessionId?: unknown, session?: { id?: unknown } }\n if (typeof sessionId === 'string')\n return sessionId\n if (session && typeof session === 'object' && typeof session.id === 'string')\n return session.id\n return undefined\n}\n\n/**\n * Builds `ctx.hooks` for one extension.\n *\n * Observers never hold up the agent: each runs through the guard, bounded by\n * `observerTimeoutMs`, and the hook returns without waiting for it.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's agent hook bus and host events.\n * @param options - The shared interceptor registry and time bounds.\n * @returns The extension's hooks domain.\n */\nexport function createHooksDomain(deps: DomainDeps, port: HooksPort, options: HooksDomainOptions): HooksDomain {\n const { owner, guard, logger, extensionId } = deps\n const observerTimeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS\n const readonlyEvents = options.readonlyEvents !== false\n\n const track = (what: string, unregister: () => void): Disposable => {\n let done = false\n let fromOwner = false\n const cleanup = owner.onCleanup(() => {\n fromOwner = true\n dispose()\n })\n function dispose(): void {\n if (done)\n return\n done = true\n if (!fromOwner)\n cleanup.dispose()\n try {\n unregister()\n }\n catch (err) {\n logger.warn(`${what}: unregister failed`, { extensionId, error: String(err) })\n }\n }\n return { dispose }\n }\n\n const on: HooksDomain['on'] = (event, handler, opts?: OnOptions) => {\n const what = `hooks.on('${String(event)}')`\n if (owner.disposed)\n throw new DisposedError(what)\n if (typeof event !== 'string' || (!isHostEvent(event) && !isKnownHookEvent(event)))\n throw new TypeError(`hooks.on: unknown event \"${String(event)}\"`)\n if (typeof handler !== 'function')\n throw new TypeError(`${what}: handler must be a function`)\n const wanted = opts?.sessionId\n const observe = (payload: unknown): void => {\n if (wanted !== undefined && (port.sessionIdOf?.(event, payload) ?? sessionIdFromEvent(payload)) !== wanted)\n return\n const view = readonlyEvents ? readonlyView(payload) : payload\n // The run's decider (`ctx.decide` on the event): `ctx.generate.decide` in the observer goes through it.\n const decide = payload !== null && typeof payload === 'object' ? (payload as { decide?: AgentDecide }).decide : undefined\n void guard.call(what, () => withRunDecide(decide, () => (handler as (e: unknown) => void | Promise<void>)(view)), { timeoutMs: observerTimeoutMs })\n }\n const unregister = isHostEvent(event)\n ? port.hostEvents.on(event, observe)\n : port.agentHooks.hook(event as keyof AgentHooks, observe as AgentHooks[keyof AgentHooks])\n return track(what, unregister)\n }\n\n const intercept: HooksDomain['intercept'] = (name, handler, opts) => {\n const what = `hooks.intercept('${String(name)}')`\n if (owner.disposed)\n throw new DisposedError(what)\n const unregister = options.interceptors.register(name, handler, { ...opts, extensionId, guard })\n if (opts?.match && !supportsMatch(name))\n logger.warn(`${what}: \\`match\\` is ignored by this interceptor`, { extensionId })\n const unsupported = unsupportedHttpMatch(name, opts?.match)\n if (unsupported.length > 0)\n logger.warn(`${what}: never runs for ${unsupported.join(', ')}: that transport takes no custom fetch`, { extensionId, providers: unsupported })\n return track(what, unregister)\n }\n\n return { on, intercept }\n}\n","/**\n * `ctx.integrations` for one extension: a view on the process-wide\n * {@link IntegrationRegistry}. Registrations and `onChange` listeners belong\n * to the extension's owner and go when it is disposed; a connect flow\n * started through it aborts then too. Connections are shared: any extension\n * reads, resolves or disconnects any integration's connections.\n */\n\nimport type { IntegrationsDomain } from '../api/sessions'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { IntegrationFlowPort } from './connect'\nimport type { IntegrationRegistry } from './registry'\nimport { assertAlive, track } from '../runtime/owner'\nimport { integrationRegistry } from './registry'\n\n/** What a host provides to `ctx.integrations`: how connect flows show their UI and run commands. */\nexport type IntegrationsHostPort = IntegrationFlowPort\n\n/**\n * Builds `ctx.integrations`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's flow UI and command runner.\n * @param registry - The registry to use. Defaults to the one the host installed (`installIntegrationRegistry`); calls reject when there is none.\n */\nexport function createIntegrationsDomain(deps: DomainDeps, port: IntegrationsHostPort, registry?: IntegrationRegistry): IntegrationsDomain {\n const reg = (): IntegrationRegistry => {\n const found = registry ?? integrationRegistry()\n if (!found)\n throw new Error('Integrations are not available in this host.')\n return found\n }\n const call = async <T>(what: string, fn: () => Promise<T>): Promise<T> => {\n assertAlive(deps.owner, `integrations.${what}`)\n return fn()\n }\n\n return {\n register(spec) {\n assertAlive(deps.owner, 'integrations.register')\n const registration = reg().register(spec, { extensionId: deps.extensionId, guard: deps.guard })\n if (!registration) {\n deps.logger.warn(`integrations.register: \"${spec.id}\" is already registered by another extension; this one is ignored`)\n return { dispose: () => {}, update: () => {} }\n }\n const tracked = track(deps.owner, registration)\n return {\n dispose: () => tracked.dispose(),\n update: (patch) => {\n assertAlive(deps.owner, 'integrations.update')\n registration.update(patch)\n },\n }\n },\n\n connections: id => reg().connections(id),\n\n connection: (id, opts) => reg().connection(id, opts?.account),\n\n setDefault: (id, account) => call('setDefault', () => reg().setDefault(id, account)),\n\n resolve: connection => call('resolve', () => reg().resolve(connection)),\n\n connect: {\n key: (id, key) => call('connect.key', () => reg().connectKey(id, key)),\n start: (id, methodId, opts) => call('connect.start', () => {\n const signal = opts?.signal ? AbortSignal.any([opts.signal, deps.owner.signal]) : deps.owner.signal\n return reg().start(id, methodId, port, { signal })\n }),\n },\n\n disconnect: (id, opts) => call('disconnect', () => reg().disconnect(id, opts?.account)),\n\n onChange(id, listener) {\n assertAlive(deps.owner, 'integrations.onChange')\n const off = reg().onChange(id, (connection) => {\n deps.guard.callSync(`integrations.onChange(${id})`, () => listener(connection))\n })\n return track(deps.owner, { dispose: off })\n },\n }\n}\n","/**\n * Where integration connections persist. The registry reads and writes one\n * record per integration (every connection of it, the default first)\n * through an {@link AuthStorePort}; hosts back it with the credentials file\n * (`./auth-store-port`), tests and SDK embeds with {@link createMemoryAuthStore}.\n */\n\nimport type { Connection, Credential } from '../api/sessions'\n\n/** One stored connection. */\nexport interface StoredIntegration {\n /** What Settings shows and `connection()` returns (`isDefault` is not stored: it is the list's order). */\n connection: Connection\n /** The credential `resolve()` hands out (never with `refreshToken`). */\n credential: Credential\n /** OAuth refresh token. Kept in the store, never handed to extensions. */\n refreshToken?: string\n}\n\n/** A legacy provider sign-in an integration may adopt (`IntegrationSpec.legacyCredentialKey`). */\nexport interface LegacyGrant {\n credential: Credential\n refreshToken?: string\n /** The account the entry names, if any. */\n account?: string\n /** A label the entry carries, if any. */\n label?: string\n}\n\n/**\n * Persistence for integration connections. Synchronous: `connection()` is\n * synchronous, and the file store is too. `read` returns `undefined` for\n * a missing or unreadable record; the first connection is the default.\n * `write(id, undefined)` (or an empty list) deletes.\n */\nexport interface AuthStorePort {\n /** Every stored connection of an integration, the default first. (A single record, from a port written before several connections, reads as the only one.) */\n read: (integrationId: string) => StoredIntegration[] | undefined\n /** Stores the connections of an integration (the default first), or deletes them. */\n write: (integrationId: string, value: readonly StoredIntegration[] | undefined) => void\n /** A legacy sign-in under `key` not adopted yet. Optional: stores without legacy entries omit it. */\n readLegacy?: (key: string) => LegacyGrant | undefined\n /** Marks the legacy entry under `key` adopted by `integrationId`, leaving its tokens in place. */\n markLegacy?: (key: string, integrationId: string) => void\n}\n\n/**\n * An in-memory {@link AuthStorePort}. Nothing survives the process. Records\n * are cloned in and out, like a real store.\n *\n * @param initial - Records to start with, keyed by integration id: one connection or a list (default first).\n * @param legacy - Legacy sign-ins to offer for adoption, keyed by their old key.\n */\nexport function createMemoryAuthStore(initial: Readonly<Record<string, StoredIntegration | readonly StoredIntegration[]>> = {}, legacy: Readonly<Record<string, LegacyGrant>> = {}): AuthStorePort {\n const records = new Map<string, StoredIntegration[]>(Object.entries(structuredClone(initial)).map(([id, v]) => [id, Array.isArray(v) ? v : [v as StoredIntegration]]))\n const grants = new Map<string, LegacyGrant>(Object.entries(structuredClone(legacy)))\n return {\n read: id => structuredClone(records.get(id)),\n write: (id, value) => {\n if (!value?.length)\n records.delete(id)\n else\n records.set(id, structuredClone([...value]))\n },\n readLegacy: key => structuredClone(grants.get(key)),\n markLegacy: (key) => {\n grants.delete(key)\n },\n }\n}\n","/**\n * The dialog router: `ctx.ui` dialogs and toasts go to one client. The\n * client viewing the session wins (the most recently active of them); with\n * no session, or nobody viewing it, the last active client. No client:\n * {@link NoUiError}. Timeouts and abort signals end the dialog on the\n * client too (the port's signal aborts).\n *\n * Toasts and OS notifications are fire-and-forget, so before any client\n * attaches they wait in a small buffer ({@link PENDING_UI_LIMIT} entries,\n * each dropped after {@link PENDING_UI_TTL_MS}) and go, in order, to the\n * first client that can show them: when the port reports a client change\n * (`onClientsChange`), or at the next call that finds one.\n *\n * The router only routes and bounds; it does not interpret answers. The\n * `coerce*` helpers turn a client's answer into the type `ctx.ui` promises.\n */\n\nimport type { PlanPayload, PlanResponse, QuestionPayload, QuestionResponse } from '../../chat/interactions'\nimport type { DialogOptions, SelectOption } from '../api/ui'\nimport type { WireSettings } from '../settings'\nimport type { UiClock } from './clock'\nimport { DialogTimeoutError, NoUiError } from '../api/ui'\nimport { systemClock } from './clock'\n\n/** A connected client as the host reports it. */\nexport interface UiClientInfo {\n /** Unique per connected client (a window, a TUI, a protocol connection). */\n id: string\n /** Sessions it shows now. */\n viewing: readonly string[]\n /** When the user last acted in it (input, focus), epoch ms. */\n lastActiveAt: number\n /** `false`: it cannot show dialogs (a headless protocol client). Default `true`. */\n dialogs?: boolean\n}\n\n/** A dialog on the wire, by kind. */\nexport type DialogRequest\n = | { kind: 'confirm', title: string, message?: string, confirmLabel?: string, danger?: boolean }\n | { kind: 'prompt', title: string, message?: string, placeholder?: string, initial?: string, secret?: boolean }\n | { kind: 'select', title: string, options: readonly SelectOption[], multi?: boolean, placeholder?: string, actions?: readonly { id: string, label: string }[] }\n /** `settings` is the settings renderer's wire format, initial values included. The answer is a value per key. */\n | { kind: 'form', title: string, settings: WireSettings }\n | { kind: 'askUser', payload: QuestionPayload }\n | { kind: 'presentPlan', payload: PlanPayload }\n | { kind: 'toast', text: string, tone: 'info' | 'success' | 'warn' | 'error', actions?: readonly { id: string, label: string }[], timeoutMs?: number }\n\n/** The kinds of {@link DialogRequest}. */\nexport type DialogKind = DialogRequest['kind']\n\n/** What the port gets beside the request. */\nexport interface DialogShowContext {\n /** Aborts when the dialog times out, the caller aborts, or the extension unloads: close it. */\n signal: AbortSignal\n /** The extension asking. */\n extensionId: string\n /** The session it is about, when given. */\n sessionId?: string\n /** Form dialogs: checks one value with the schema (including its `validate`). An error message, or `undefined`. */\n validate?: (key: string, value: unknown) => string | undefined\n}\n\n/** The host side of dialogs: which clients exist, and showing a dialog on one. */\nexport interface DialogPort {\n /** The connected clients now. */\n clients: () => readonly UiClientInfo[]\n /** Shows `request` on `clientId` and resolves with the client's raw answer. */\n show: (clientId: string, request: DialogRequest, ctx: DialogShowContext) => Promise<unknown>\n /**\n * Calls `listener` after a client attached, detached or changed. Returns\n * the unsubscribe. Optional: without it, buffered toasts and\n * notifications go out at the next `ctx.ui` call that finds a client.\n */\n onClientsChange?: (listener: () => void) => () => void\n}\n\n/** Most toasts and notifications kept while no client is attached. The oldest goes first. */\nexport const PENDING_UI_LIMIT = 20\n\n/** How long a buffered toast or notification waits for a client, in ms. */\nexport const PENDING_UI_TTL_MS = 60_000\n\n/** Options of one {@link DialogRouter.open} call. */\nexport interface DialogOpenOptions extends DialogOptions {\n extensionId: string\n /** On timeout: reject with {@link DialogTimeoutError} (default), or resolve `undefined` (toasts). */\n onTimeout?: 'reject' | 'resolve'\n /**\n * With no client: wait in the buffer for one instead of rejecting with\n * {@link NoUiError} (toasts). Resolves `undefined` when dropped (buffer\n * full, {@link PENDING_UI_TTL_MS} passed, aborted, router disposed). The\n * dialog's `timeoutMs` starts once it is shown.\n */\n buffer?: boolean\n /** Form dialogs: see {@link DialogShowContext.validate}. */\n validate?: (key: string, value: unknown) => string | undefined\n}\n\n/** Routes dialogs to clients. */\nexport interface DialogRouter {\n /**\n * The client a call about `sessionId` goes to, or `undefined`.\n * `opts.dialogs` (default `true`) skips clients that cannot show dialogs.\n */\n route: (sessionId?: string, opts?: { dialogs?: boolean }) => UiClientInfo | undefined\n /** Shows `request` on the routed client and resolves with its raw answer. */\n open: (request: DialogRequest, opts: DialogOpenOptions) => Promise<unknown>\n /**\n * Runs `deliver` on the client a fire-and-forget call about `sessionId`\n * goes to (any client, dialogs or not), now or, with no client yet, once\n * one attaches (buffered as for {@link DialogOpenOptions.buffer}).\n */\n deliver: (deliver: (client: UiClientInfo) => void, opts?: { sessionId?: string, signal?: AbortSignal }) => void\n /** Drops what is buffered (toasts resolve `undefined`) and stops listening to the port. */\n dispose: () => void\n}\n\n/** Options for {@link createDialogRouter}. */\nexport interface DialogRouterOptions {\n /** Timer for `timeoutMs`. Default: the real clock. */\n clock?: UiClock\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? Object.assign(new Error('The dialog was aborted'), { name: 'AbortError' })\n}\n\n/**\n * Creates a dialog router over a host port.\n *\n * @param port - Lists clients and shows dialogs on them.\n * @param options - Clock.\n */\nexport function createDialogRouter(port: DialogPort, options: DialogRouterOptions = {}): DialogRouter {\n const clock = options.clock ?? systemClock\n\n const route: DialogRouter['route'] = (sessionId, opts = {}) => {\n const wantDialogs = opts.dialogs ?? true\n const clients = port.clients().filter(c => !wantDialogs || c.dialogs !== false)\n const latest = (list: readonly UiClientInfo[]): UiClientInfo | undefined =>\n list.reduce<UiClientInfo | undefined>((best, c) => (!best || c.lastActiveAt > best.lastActiveAt ? c : best), undefined)\n if (sessionId) {\n const viewing = latest(clients.filter(c => c.viewing.includes(sessionId)))\n if (viewing)\n return viewing\n }\n return latest(clients)\n }\n\n /** A toast or notification waiting for a client. */\n interface Pending {\n sessionId?: string\n /** Needs a client that shows dialogs (toasts). */\n dialogs: boolean\n timer: unknown\n signal?: AbortSignal\n onAbort?: () => void\n deliver: (client: UiClientInfo) => void\n drop: () => void\n }\n const pending: Pending[] = []\n\n const take = (entry: Pending): boolean => {\n const at = pending.indexOf(entry)\n if (at < 0)\n return false\n pending.splice(at, 1)\n clock.clearTimeout(entry.timer)\n if (entry.onAbort)\n entry.signal?.removeEventListener('abort', entry.onAbort)\n return true\n }\n const drop = (entry: Pending): void => {\n if (take(entry))\n entry.drop()\n }\n\n /** Delivers, in order, every buffered entry a client can take now. */\n const flush = (): void => {\n for (const entry of [...pending]) {\n const client = route(entry.sessionId, { dialogs: entry.dialogs })\n if (client && take(entry))\n entry.deliver(client)\n }\n }\n\n const buffer = (entry: Omit<Pending, 'timer'>): void => {\n if (entry.signal?.aborted)\n return entry.drop()\n while (pending.length >= PENDING_UI_LIMIT)\n drop(pending[0]!)\n const queued: Pending = { ...entry, timer: undefined }\n queued.timer = clock.setTimeout(() => drop(queued), PENDING_UI_TTL_MS)\n // A toast nobody will see must not keep a finished process (a headless run) alive.\n ;(queued.timer as { unref?: () => void } | undefined)?.unref?.()\n if (entry.signal) {\n queued.onAbort = () => drop(queued)\n entry.signal.addEventListener('abort', queued.onAbort, { once: true })\n }\n pending.push(queued)\n }\n\n const unsubscribe = port.onClientsChange?.(flush)\n\n const show = (client: UiClientInfo, request: DialogRequest, opts: DialogOpenOptions): Promise<unknown> => {\n if (opts.signal?.aborted)\n return Promise.reject(abortReason(opts.signal))\n const controller = new AbortController()\n return new Promise<unknown>((resolve, reject) => {\n let settled = false\n let timer: unknown\n const onAbort = (): void => {\n const reason = abortReason(opts.signal!)\n // eslint-disable-next-line ts/no-use-before-define -- finish and onAbort refer to each other\n finish(() => reject(reason))\n controller.abort(reason)\n }\n const finish = (fn: () => void): void => {\n if (settled)\n return\n settled = true\n if (timer !== undefined)\n clock.clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onAbort)\n fn()\n }\n opts.signal?.addEventListener('abort', onAbort, { once: true })\n if (opts.timeoutMs !== undefined && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0) {\n timer = clock.setTimeout(() => {\n const error = new DialogTimeoutError(request.kind, opts.timeoutMs!)\n finish(() => (opts.onTimeout === 'resolve' ? resolve(undefined) : reject(error)))\n controller.abort(error)\n }, opts.timeoutMs)\n }\n let shown: Promise<unknown>\n try {\n shown = port.show(client.id, request, {\n signal: controller.signal,\n extensionId: opts.extensionId,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.validate ? { validate: opts.validate } : {}),\n })\n }\n catch (err) {\n shown = Promise.reject(err)\n }\n shown.then(\n value => finish(() => resolve(value)),\n err => finish(() => reject(err)),\n )\n })\n }\n\n const open: DialogRouter['open'] = (request, opts) => {\n if (opts.signal?.aborted)\n return Promise.reject(abortReason(opts.signal))\n if (pending.length > 0)\n flush()\n const client = route(opts.sessionId)\n if (client)\n return show(client, request, opts)\n if (!opts.buffer)\n return Promise.reject(new NoUiError(request.kind))\n return new Promise<unknown>((resolve, reject) => {\n buffer({\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n dialogs: true,\n ...(opts.signal ? { signal: opts.signal } : {}),\n deliver: target => show(target, request, opts).then(resolve, reject),\n drop: () => resolve(undefined),\n })\n })\n }\n\n const deliver: DialogRouter['deliver'] = (fn, opts = {}) => {\n if (opts.signal?.aborted)\n return\n if (pending.length > 0)\n flush()\n const client = route(opts.sessionId, { dialogs: false })\n if (client)\n return fn(client)\n buffer({\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n dialogs: false,\n ...(opts.signal ? { signal: opts.signal } : {}),\n deliver: fn,\n drop: () => {},\n })\n }\n\n const dispose = (): void => {\n unsubscribe?.()\n for (const entry of [...pending])\n drop(entry)\n }\n\n return { route, open, deliver, dispose }\n}\n\n/**\n * A select answer: ids among the options (one unless `multi`), and an\n * action among the declared ones. `undefined` for a cancel or a malformed answer.\n *\n * @param raw - The client's answer.\n * @param request - The select request it answers.\n */\nexport function coerceSelect(raw: unknown, request: Extract<DialogRequest, { kind: 'select' }>): { ids: readonly string[], action?: string } | undefined {\n if (!raw || typeof raw !== 'object')\n return undefined\n const o = raw as { ids?: unknown, action?: unknown }\n const known = new Set(request.options.map(opt => opt.id))\n const ids = Array.isArray(o.ids) ? [...new Set(o.ids.filter((id): id is string => typeof id === 'string' && known.has(id)))] : []\n const action = typeof o.action === 'string' && request.actions?.some(a => a.id === o.action) ? o.action : undefined\n if (ids.length === 0 && !action)\n return undefined\n return { ids: request.multi ? ids : ids.slice(0, 1), ...(action ? { action } : {}) }\n}\n\n/**\n * A toast answer: an action id among the declared ones, else `undefined`.\n *\n * @param raw - The client's answer.\n * @param actions - The toast's actions.\n */\nexport function coerceToastAction(raw: unknown, actions: readonly { id: string }[] | undefined): string | undefined {\n return typeof raw === 'string' && actions?.some(a => a.id === raw) ? raw : undefined\n}\n\n/**\n * An ask-user answer. A malformed answer counts as no answers.\n *\n * @param raw - The client's answer.\n */\nexport function coerceQuestion(raw: unknown): QuestionResponse {\n const o = raw && typeof raw === 'object' ? raw as Partial<QuestionResponse> : undefined\n if (o?.kind === 'question' && o.answers && typeof o.answers === 'object')\n return o as QuestionResponse\n return { kind: 'question', answers: {} }\n}\n\n/**\n * A plan answer. A malformed answer is a rejection.\n *\n * @param raw - The client's answer.\n */\nexport function coercePlan(raw: unknown): PlanResponse {\n const o = raw && typeof raw === 'object' ? raw as Partial<PlanResponse> : undefined\n if (o?.kind === 'plan' && (o.decision === 'approve' || o.decision === 'reject' || o.decision === 'revise'))\n return o as PlanResponse\n return { kind: 'plan', decision: 'reject' }\n}\n","/**\n * `ctx.ui`, `ctx.composer` and `ctx.add` for one extension. Dialogs go\n * through the {@link DialogRouter}; panels, navigation, the composer and OS\n * notifications go to the routed client through a {@link UiClientPort};\n * contributions go to the {@link UiRegistry}.\n */\n\nimport type { AddFn, ComposerDomain, UiDomain } from '../api/ui'\nimport type { PanelFocus } from '../panels'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { DialogOpenOptions, DialogRequest, DialogRouter } from './dialogs'\nimport type { UiRegistry } from './registry'\nimport { parseBindingSpec } from '../../chat/keybindings'\nimport { DisposedError } from '../api/core'\nimport { NoUiError } from '../api/ui'\nimport { resolveMod } from '../commands/keymap'\nimport { coercePlan, coerceQuestion, coerceSelect, coerceToastAction } from './dialogs'\nimport { checkSettingsValues, cleanSettingsSchema, settingsWire } from './settings-form'\n\n/** Files `ctx.composer.attach` takes. */\nexport type ComposerFiles = readonly { path: string }[] | readonly { name: string, mimeType: string, data: Uint8Array }[]\n\n/** A composer edit for one client. */\nexport type ComposerOp\n = | { op: 'insert', text: string }\n | { op: 'setText', text: string }\n | { op: 'attach', files: ComposerFiles }\n\n/** Where `ctx.ui.navigate` goes, with screen ids made full (`<extension>/<id>`). */\nexport type NavigateTarget = { screen: string } | { session: string } | { newSession: true }\n\n/** The host side of the non-dialog `ctx.ui` calls and `ctx.composer`. Each call names the routed client. */\nexport interface UiClientPort {\n /** Opens, closes or toggles a panel (full id or built-in) in the client. Whether it did. */\n panel: (clientId: string, request: { action: 'open' | 'close' | 'toggle', panelId: string, sessionId?: string, focus?: PanelFocus }) => Promise<boolean>\n /** The panels open in the client (beside `sessionId` when given). */\n panelState: (clientId: string, opts: { sessionId?: string }) => Promise<readonly string[]>\n /** Shows a screen, a session or a new session in the client. Whether it did. */\n navigate: (clientId: string, to: NavigateTarget) => Promise<boolean>\n /** Edits the composer of the client (the one for `sessionId` when given). Whether it did. */\n composer: (clientId: string, op: ComposerOp, opts: { sessionId?: string }) => Promise<boolean>\n /** Shows an OS notification from the client, unless the app has focus. */\n notify: (clientId: string, notification: { title: string, body?: string, sound?: boolean, sessionId?: string, extensionId: string }) => void\n /**\n * Presses a chord (`'mod+k'`, `mod` not resolved: the client resolves it\n * for its platform) in the client, as if the user typed it, in the view\n * of `sessionId` when given. Whether a binding took it. Absent: the host's\n * clients cannot, and `ctx.keymap.dispatch` rejects with `NoUiError`.\n */\n keymapDispatch?: (clientId: string, request: { chord: string, sessionId?: string }) => Promise<boolean>\n}\n\n/** What the UI domains share across extensions. */\nexport interface UiDomainPorts {\n registry: UiRegistry\n dialogs: DialogRouter\n client: UiClientPort\n}\n\nfunction signalFor(deps: DomainDeps, signal: AbortSignal | undefined): AbortSignal {\n return signal ? AbortSignal.any([deps.owner.signal, signal]) : deps.owner.signal\n}\n\n/**\n * `ctx.add` for one extension.\n *\n * @param deps - The extension's deps.\n * @param registry - The shared UI registry.\n */\nexport function createUiAdd(deps: DomainDeps, registry: UiRegistry): AddFn {\n return registry.bind(deps)\n}\n\n/**\n * `ctx.ui` for one extension.\n *\n * @param deps - The extension's deps.\n * @param ports - Registry, dialog router and client port.\n */\nexport function createUiDomain(deps: DomainDeps, ports: UiDomainPorts): UiDomain {\n const { registry, dialogs, client } = ports\n\n const open = (request: DialogRequest, opts: Omit<DialogOpenOptions, 'extensionId'>): Promise<unknown> =>\n dialogs.open(request, { ...opts, extensionId: deps.extensionId, signal: signalFor(deps, opts.signal) })\n\n /** Runs a client call; a port failure is logged and counts as \"did nothing\". */\n const onClient = async <T>(label: string, sessionId: string | undefined, fallback: T, fn: (clientId: string) => Promise<T>): Promise<T> => {\n const target = dialogs.route(sessionId, { dialogs: false })\n if (!target)\n return fallback\n try {\n return await fn(target.id)\n }\n catch (err) {\n deps.logger.warn(`ui.${label}: the client failed`, { error: err instanceof Error ? err.message : String(err) })\n return fallback\n }\n }\n\n const panelId = (id: string): string => registry.qualify('panel', deps.extensionId, id)\n\n return {\n confirm: async ({ title, message, confirmLabel, danger, ...opts }) =>\n (await open({ kind: 'confirm', title, ...(message ? { message } : {}), ...(confirmLabel ? { confirmLabel } : {}), ...(danger ? { danger } : {}) }, opts)) === true,\n prompt: async ({ title, message, placeholder, initial, secret, ...opts }) => {\n const raw = await open({ kind: 'prompt', title, ...(message ? { message } : {}), ...(placeholder ? { placeholder } : {}), ...(initial !== undefined ? { initial } : {}), ...(secret ? { secret } : {}) }, opts)\n return typeof raw === 'string' ? raw : undefined\n },\n select: async ({ title, options, multi, placeholder, actions, ...opts }) => {\n const request: Extract<DialogRequest, { kind: 'select' }> = { kind: 'select', title, options, ...(multi ? { multi } : {}), ...(placeholder ? { placeholder } : {}), ...(actions ? { actions } : {}) }\n return coerceSelect(await open(request, opts), request)\n },\n form: async ({ title, schema: authored, values, ...opts }) => {\n const schema = cleanSettingsSchema(deps.extensionId, authored)\n const runValidate = (validate: (value: string) => string | undefined, value: string): string | undefined =>\n deps.guard.callSync('ui.form.validate', () => validate(value))\n const validate = (key: string, value: unknown): string | undefined => {\n const setting = schema.items[key]\n if (!setting)\n return 'unknown setting'\n return checkSettingsValues({ items: { [key]: setting } }, { [key]: value }, runValidate).errors[key]\n }\n const raw = await open({ kind: 'form', title, settings: settingsWire(deps.extensionId, schema, values) }, { ...opts, validate })\n if (raw === undefined || raw === null)\n return undefined\n const check = checkSettingsValues(schema, raw, runValidate)\n const bad = Object.keys(check.errors)\n if (bad.length > 0)\n throw new TypeError(`form: the client sent invalid values for ${bad.join(', ')}`)\n return check.values\n },\n askUser: async (payload, opts = {}) => coerceQuestion(await open({ kind: 'askUser', payload }, opts)),\n presentPlan: async (payload, opts = {}) => coercePlan(await open({ kind: 'presentPlan', payload }, opts)),\n toast: async ({ text, tone, actions, timeoutMs, sessionId }) => {\n const request: DialogRequest = { kind: 'toast', text, tone: tone ?? 'info', ...(actions ? { actions } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}) }\n try {\n const raw = await open(request, { ...(sessionId ? { sessionId } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}), onTimeout: 'resolve', buffer: true })\n return coerceToastAction(raw, actions)\n }\n catch (err) {\n // A toast is fire-and-forget: nobody to show it to is not an error.\n if (err instanceof NoUiError) {\n deps.logger.debug('ui.toast: no client to show it', { text })\n return undefined\n }\n throw err\n }\n },\n notify: ({ title, body, sound, sessionId }) => {\n dialogs.deliver((target) => {\n try {\n client.notify(target.id, { title, ...(body ? { body } : {}), ...(sound ? { sound } : {}), ...(sessionId ? { sessionId } : {}), extensionId: deps.extensionId })\n }\n catch (err) {\n deps.logger.warn('ui.notify: the client failed', { error: err instanceof Error ? err.message : String(err) })\n }\n }, { ...(sessionId ? { sessionId } : {}), signal: deps.owner.signal })\n },\n panel: {\n open: (id, opts = {}) => onClient('panel.open', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'open', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}), ...(opts.focus ? { focus: opts.focus } : {}) })),\n close: (id, opts = {}) => onClient('panel.close', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'close', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}) })),\n toggle: (id, opts = {}) => onClient('panel.toggle', opts.sessionId, false, clientId =>\n client.panel(clientId, { action: 'toggle', panelId: panelId(id), ...(opts.sessionId ? { sessionId: opts.sessionId } : {}) })),\n state: (opts = {}) => onClient<readonly string[]>('panel.state', opts.sessionId, [], clientId =>\n client.panelState(clientId, opts.sessionId ? { sessionId: opts.sessionId } : {})),\n },\n navigate: async (to, opts = {}) => {\n if (opts.signal?.aborted)\n return false\n const target: NavigateTarget = 'screen' in to ? { screen: registry.qualify('screen', deps.extensionId, to.screen) } : to\n return onClient('navigate', opts.sessionId ?? ('session' in to ? to.session : undefined), false, clientId => client.navigate(clientId, target))\n },\n }\n}\n\n/** Longest chord `ctx.keymap.dispatch` takes. */\nconst MAX_CHORD_LENGTH = 64\n\n/**\n * The client side of `ctx.keymap.dispatch` for one extension: routes like\n * the non-dialog `ctx.ui` calls (the client viewing `sessionId`, else the\n * last active one) and asks it to press the chord.\n *\n * @param deps - The extension's deps.\n * @param ports - Dialog router and client port.\n * @returns The dispatch. Rejects with `NoUiError` when no client can take it, with a `TypeError` for a chord that does not parse; a client that fails answers `false`.\n */\nexport function createKeymapDispatch(deps: DomainDeps, ports: Pick<UiDomainPorts, 'dialogs' | 'client'>): (chord: string, sessionId?: string) => Promise<boolean> {\n return async (chord, sessionId) => {\n if (deps.owner.disposed)\n throw new DisposedError('keymap.dispatch')\n if (typeof chord !== 'string' || !chord.trim() || chord.length > MAX_CHORD_LENGTH || !parseBindingSpec(resolveMod(chord, 'linux')))\n throw new TypeError(`keymap.dispatch: \"${String(chord)}\" is not a chord`)\n const press = ports.client.keymapDispatch\n const target = press ? ports.dialogs.route(sessionId, { dialogs: false }) : undefined\n if (!press || !target)\n throw new NoUiError('keymap.dispatch')\n try {\n return await press(target.id, { chord: chord.trim(), ...(sessionId ? { sessionId } : {}) }) === true\n }\n catch (err) {\n deps.logger.warn('keymap.dispatch: the client failed', { error: err instanceof Error ? err.message : String(err) })\n return false\n }\n }\n}\n\n/**\n * `ctx.composer` for one extension.\n *\n * @param deps - The extension's deps.\n * @param ports - Registry, dialog router and client port.\n */\nexport function createComposerDomain(deps: DomainDeps, ports: UiDomainPorts): ComposerDomain {\n const { registry, dialogs, client } = ports\n const edit = async (op: ComposerOp, sessionId: string | undefined): Promise<boolean> => {\n const target = dialogs.route(sessionId, { dialogs: false })\n if (!target)\n return false\n try {\n return await client.composer(target.id, op, sessionId ? { sessionId } : {})\n }\n catch (err) {\n deps.logger.warn(`composer.${op.op}: the client failed`, { error: err instanceof Error ? err.message : String(err) })\n return false\n }\n }\n return {\n insert: (text, opts = {}) => edit({ op: 'insert', text }, opts.sessionId),\n setText: (text, opts = {}) => edit({ op: 'setText', text }, opts.sessionId),\n attach: (files, opts = {}) => edit({ op: 'attach', files }, opts.sessionId),\n completions: { register: provider => registry.completions.register(deps, provider) },\n autocomplete: { register: provider => registry.autocomplete.register(deps, provider) },\n }\n}\n","/**\n * `ctx.commands` and `ctx.keymap` for one extension. Validates each spec,\n * wraps its callbacks so errors are attributed to the extension, ties the\n * registration to the extension's owner, and hands the result to the\n * host-wide {@link CommandRegistry} (the port).\n */\n\nimport type { CommandArgSuggestion, CommandStep } from '../../chat/commands'\nimport type { PaletteItem } from '../../chat/palette'\nimport type { CommandsDomain, CommandSpec, KeymapDomain, PaletteProviderSpec } from '../api/commands'\nimport type { Bindable, Disposable, Readable } from '../api/core'\nimport type { DomainDeps, Guard } from '../runtime/deps'\nimport type { ExtensionPaletteItem, ExtensionPaletteProviderEntry } from '../types'\nimport type { CommandEntry, CommandsDomainPort } from './registry'\nimport { DisposedError } from '../api/core'\nimport { NoUiError } from '../api/ui'\nimport { normalizeChords } from './keymap'\n\n/** Options for {@link createCommandsDomain}. */\nexport interface CommandsDomainOptions {\n /** Palette group for commands and providers that name none. Default: the extension id. */\n displayName?: string\n /** `process.platform` of the host; decides what `mod` means. Default `process.platform`. */\n platform?: string\n /**\n * Presses a chord in the client viewing `sessionId` (`createKeymapDispatch`).\n * Absent: `ctx.keymap.dispatch` rejects with `NoUiError`.\n */\n dispatch?: (chord: string, sessionId?: string) => Promise<boolean>\n}\n\n/** The two namespaces the domain fills on `ctx`. */\nexport interface CommandsDomains {\n /** `ctx.commands`. */\n commands: CommandsDomain\n /** `ctx.keymap`. */\n keymap: KeymapDomain\n}\n\nconst SLASH_TOKEN = /^[^\\s/]\\S*$/\nconst LOCAL_ID = /^[\\w.-]+$/\n\n/**\n * `true` when `value` is a {@link Readable}.\n *\n * @param value - A {@link Bindable} field.\n */\nexport function isReadable<T>(value: Bindable<T> | undefined): value is Readable<T> {\n return !!value && typeof value === 'object'\n && typeof (value as Readable<T>).get === 'function'\n && typeof (value as Readable<T>).subscribe === 'function'\n}\n\n/**\n * An extension palette provider as the host-facing entry, its callbacks guarded.\n *\n * @param deps - The extension's id and guard.\n * @param spec - The provider as registered.\n * @param group - Group for items that name none.\n */\nfunction paletteProviderEntry(deps: DomainDeps, spec: PaletteProviderSpec, group: string): ExtensionPaletteProviderEntry {\n const { extensionId, guard } = deps\n // Namespaced like every palette provider: item ids go out as\n // `<extension>/<id>` and come back bare, so two extensions never collide.\n const id = `${extensionId}/${spec.id}`\n const providerGroup = spec.group?.trim() || group\n const prefix = `${extensionId}/`\n const namespaced = (itemId: string) => (itemId.startsWith(prefix) ? itemId : `${prefix}${itemId}`)\n const stamp = (items: readonly ExtensionPaletteItem[]): PaletteItem[] =>\n items.map(item => ({ ...item, id: namespaced(item.id), group: item.group ?? providerGroup, source: id }))\n const subscribe = spec.subscribe\n const entry: ExtensionPaletteProviderEntry = {\n id,\n owner: extensionId,\n group: providerGroup,\n items: async (ctx) => {\n const query = (ctx as { query?: unknown }).query\n const items = await guard.call(`palette provider ${id} items`, () => spec.items({\n query: typeof query === 'string' ? query : '',\n busy: ctx.busy === true,\n ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}),\n }), { fallback: [] })\n return stamp(Array.isArray(items) ? items : [])\n },\n run: async (itemId, ctx) => {\n const bare = itemId.startsWith(prefix) ? itemId.slice(prefix.length) : itemId\n const result = await guard.call(`palette provider ${id} run`, () => spec.run(bare, ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}))\n if (!result)\n return undefined\n return result.kind === 'items' ? { ...result, items: stamp(result.items) } : result\n },\n ...(typeof subscribe === 'function'\n ? {\n subscribe: (emit: () => void) => {\n const stop = guard.callSync(`palette provider ${id} subscribe`, () => subscribe(emit))\n return () => {\n if (typeof stop === 'function')\n guard.callSync(`palette provider ${id} unsubscribe`, stop)\n }\n },\n }\n : {}),\n }\n return entry\n}\n\n/** Marks a run in flight (`Guard.lease`): an unload meanwhile tears down only once it ends. Throws `DisposedError` once unloaded. */\nfunction lease(guard: Guard, label: string): () => void {\n return guard.lease?.(label) ?? (() => {})\n}\n\n/** `fn` holding a lease while it runs. */\nfunction leased<A extends unknown[], R>(guard: Guard, label: string, fn: (...args: A) => R): (...args: A) => R {\n return (...args: A): R => {\n const release = lease(guard, label)\n let result: R\n try {\n result = fn(...args)\n }\n catch (error) {\n release()\n throw error\n }\n if (result && typeof (result as unknown as PromiseLike<unknown>).then === 'function')\n return (result as unknown as Promise<unknown>).finally(release) as R\n release()\n return result\n }\n}\n\n/**\n * The steps of one pipeline share one lease, from the first step to the last\n * (or the step that throws, or an abort), so an unload between two steps does\n * not tear the extension down under the next one. Keyed by the run's context,\n * which `executeCommand` hands to every step.\n */\nfunction pipeline(guard: Guard, label: string, steps: readonly CommandStep[]): CommandStep[] {\n const runs = new WeakMap<object, () => void>()\n const end = (ctx: object): void => {\n const release = runs.get(ctx)\n runs.delete(ctx)\n release?.()\n }\n return steps.map((step, i) => ({\n run: async (ctx: Parameters<CommandStep['run']>[0]) => {\n if (!runs.has(ctx)) {\n runs.set(ctx, lease(guard, label))\n ctx.signal?.addEventListener('abort', () => end(ctx), { once: true })\n }\n try {\n const result = await step.run(ctx)\n if (i === steps.length - 1)\n end(ctx)\n return result\n }\n catch (error) {\n end(ctx)\n throw error\n }\n },\n }))\n}\n\n/**\n * Makes `ctx.commands` and `ctx.keymap` for one extension.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host-wide registry (or anything with its domain-facing members).\n * @param opts - Palette group and host platform.\n */\nexport function createCommandsDomain(deps: DomainDeps, port: CommandsDomainPort, opts: CommandsDomainOptions = {}): CommandsDomains {\n const { extensionId, owner, guard, logger } = deps\n const platform = opts.platform ?? process.platform\n const group = opts.displayName?.trim() || extensionId\n const noop: Disposable = { dispose() {} }\n\n // Ties a registration to the owner: disposing either one withdraws it once.\n const own = (what: string, register: () => Disposable): Disposable => {\n if (owner.disposed)\n throw new DisposedError(what)\n const registration = register()\n let done = false\n const cleanup = owner.onCleanup(() => dispose())\n function dispose() {\n if (done)\n return\n done = true\n cleanup.dispose()\n registration.dispose()\n }\n return { dispose }\n }\n\n // Counts an error in the extension's budget and logs it, without the\n // guard's timeout: a command may run an agent for minutes. The error is\n // rethrown so the host flow (`executeCommand`) still sees it.\n const report = (label: string, error: unknown) => {\n guard.callSync(label, () => {\n throw error\n })\n }\n const attributed = <A extends unknown[], R>(label: string, fn: (...args: A) => R) => (...args: A): R => {\n let result: R\n try {\n result = fn(...args)\n }\n catch (error) {\n report(label, error)\n throw error\n }\n if (result && typeof (result as unknown as PromiseLike<unknown>).then === 'function') {\n return (result as unknown as Promise<unknown>).catch((error: unknown) => {\n report(label, error)\n throw error\n }) as R\n }\n return result\n }\n\n const read = <T>(label: string, value: Bindable<T>, fallback: T): T => {\n if (!isReadable(value))\n return value\n return guard.callSync(label, () => value.get(), { fallback }) ?? fallback\n }\n\n const register = (spec: CommandSpec): Disposable => {\n if (owner.disposed)\n throw new DisposedError('commands.register')\n if (!spec || typeof spec.id !== 'string' || !LOCAL_ID.test(spec.id)) {\n logger.warn('commands.register: id must be a [A-Za-z0-9_.-]+ token', { id: String(spec?.id) })\n return noop\n }\n const id = `${extensionId}.${spec.id}`\n if (spec.title === undefined || (typeof spec.title === 'string' && !spec.title.trim())) {\n logger.warn('commands.register: missing title', { command: id })\n return noop\n }\n const hasSteps = Array.isArray(spec.steps) && spec.steps.length > 0\n if (typeof spec.run !== 'function' && !hasSteps) {\n logger.warn('commands.register: needs run() or a non-empty steps[]', { command: id })\n return noop\n }\n if (hasSteps && !spec.slash) {\n logger.warn('commands.register: steps run only as a / command; add slash', { command: id })\n return noop\n }\n\n const normalized = normalizeChords(spec.bind, { platform, editable: spec.editable })\n for (const { chord, reason } of normalized.refused) {\n const why = reason === 'reserved'\n ? 'esc and ctrl+c are reserved'\n : reason === 'bare'\n ? 'a bare key on an editable binding would fire while typing'\n : 'the chord does not parse'\n logger.warn(`commands.register: binding refused, ${why}`, { command: id, chord })\n }\n\n let slash: CommandEntry['slash']\n if (spec.slash) {\n const { name, aliases = [], argumentHint } = spec.slash\n if (typeof name !== 'string' || !SLASH_TOKEN.test(name)) {\n logger.warn('commands.register: slash name must be one token without a leading /, slash dropped', { command: id, name: String(name) })\n }\n else {\n const valid = aliases.filter(a => typeof a === 'string' && SLASH_TOKEN.test(a) && a.toLowerCase() !== name.toLowerCase())\n if (valid.length !== aliases.length)\n logger.warn('commands.register: invalid slash aliases dropped', { command: id })\n slash = { name, aliases: [...new Set(valid)], ...(argumentHint ? { argumentHint } : {}) }\n }\n }\n\n const run = spec.run\n const complete = spec.slash?.complete\n const steps: CommandStep[] | undefined = hasSteps\n ? pipeline(guard, `command ${id}`, spec.steps!.map((step, i) => ({ run: attributed(`command ${id} step ${i + 1}`, step.run) })))\n : undefined\n\n const entry: CommandEntry = {\n id,\n extensionId,\n group,\n spec,\n chords: normalized.chords,\n signal: owner.signal,\n logger,\n ...(slash ? { slash } : {}),\n title: () => read(`command ${id} title`, spec.title, id),\n description: () => spec.description === undefined ? undefined : read(`command ${id} description`, spec.description, undefined as string | undefined),\n enabled: () => spec.enabled === undefined ? true : read(`command ${id} enabled`, spec.enabled, false) !== false,\n watch(onChange) {\n const stops: (() => void)[] = []\n for (const [field, value] of [['title', spec.title], ['description', spec.description], ['enabled', spec.enabled]] as const) {\n if (!isReadable<unknown>(value))\n continue\n const stop = guard.callSync(`command ${id} ${field} subscribe`, () => value.subscribe(() => onChange()))\n if (typeof stop === 'function')\n stops.push(stop)\n }\n return () => {\n for (const stop of stops)\n guard.callSync(`command ${id} unsubscribe`, stop)\n }\n },\n ...(typeof run === 'function' ? { run: leased(guard, `command ${id}`, attributed(`command ${id}`, run)) } : {}),\n ...(steps ? { steps } : {}),\n ...(typeof complete === 'function'\n ? {\n complete: async (prefix: string): Promise<readonly CommandArgSuggestion[]> =>\n (await guard.call(`command ${id} complete`, () => complete(prefix), { fallback: [] })) ?? [],\n }\n : {}),\n }\n return own('commands.register', () => port.add(entry))\n }\n\n const provider = (spec: PaletteProviderSpec): Disposable => {\n if (owner.disposed)\n throw new DisposedError('commands.provider')\n if (!spec || typeof spec.id !== 'string' || !spec.id.trim()) {\n logger.warn('commands.provider: missing id')\n return noop\n }\n if (typeof spec.items !== 'function' || typeof spec.run !== 'function') {\n logger.warn('commands.provider: items and run must be functions', { provider: spec.id })\n return noop\n }\n const entry = paletteProviderEntry(deps, spec, group)\n return own('commands.provider', () => port.addProvider(entry, logger))\n }\n\n const commands: CommandsDomain = {\n register,\n provider,\n run: (commandId, runOpts) => port.run(commandId, runOpts),\n list: () => port.list(),\n }\n\n const keymap: KeymapDomain = {\n mode: {\n push(name, modeOpts) {\n if (owner.disposed)\n throw new DisposedError('keymap.mode.push')\n if (typeof name !== 'string' || !name.trim()) {\n logger.warn('keymap.mode.push: missing name')\n return noop\n }\n return own('keymap.mode.push', () => port.keymap.pushMode(name, modeOpts))\n },\n current: () => port.keymap.currentMode(),\n },\n list: () => port.keymapEntries(),\n active: (activeOpts = {}) => [...port.keymap.activeModes(activeOpts.sessionId)],\n dispatch: async (chord, dispatchOpts = {}) => {\n if (owner.disposed)\n throw new DisposedError('keymap.dispatch')\n if (!opts.dispatch)\n throw new NoUiError('keymap.dispatch')\n return opts.dispatch(chord, dispatchOpts.sessionId)\n },\n bindings(commandId) {\n const exact = port.keymap.bindings(commandId)\n if (exact.length > 0 || commandId.includes('.'))\n return exact\n return port.keymap.bindings(`${extensionId}.${commandId}`)\n },\n }\n\n return { commands, keymap }\n}\n","/**\n * The host-facing command registry: every extension's commands, projected\n * into the shapes the hosts already consume.\n *\n * - `/` commands: chat {@link Command} (`src/chat/commands.ts`), the extension\n * layer the hosts pass to `mergeCommands` beside their built-ins.\n * - Palette: {@link ExtensionPaletteProviderEntry} (`src/extensions/types.ts`),\n * one static provider per extension plus the dynamic providers.\n * - Keys: the {@link Keymap} (scopes, modes, fall-through), plus the\n * {@link ExtensionKeybinding} / {@link ExtensionFooterHint} shapes the TUI\n * dispatcher and footer read today.\n *\n * Projections are cached and rebuilt after a change; {@link CommandRegistry.subscribe}\n * tells the hosts when. A bound `title`, `description` or `enabled` counts as a change.\n */\n\nimport type { Command, CommandArgSuggestion, CommandStep, CommandStepContext } from '../../chat/commands'\nimport type { PaletteContext, PaletteItem } from '../../chat/palette'\nimport type { Logger } from '../../logger'\nimport type { CommandInvocation, CommandSource, CommandSpec, KeymapEntry } from '../api/commands'\nimport type { Disposable } from '../api/core'\nimport type { ExtensionFooterHint, ExtensionKeybinding, ExtensionPaletteProviderEntry } from '../types'\nimport type { Keymap, KeyTriggerContext } from './keymap'\nimport { createKeymap } from './keymap'\n\n/**\n * One registered command, as {@link createCommandsDomain} hands it to the\n * registry. Callbacks are already wrapped: errors are attributed to the\n * extension.\n */\nexport interface CommandEntry {\n /** Published id: `<extension>.<id>`. */\n readonly id: string\n /** The registering extension. */\n readonly extensionId: string\n /** Palette group used when the spec names none. */\n readonly group: string\n /** The spec as registered (static fields only are read from it). */\n readonly spec: Readonly<CommandSpec>\n /** Validated, canonical default chords. */\n readonly chords: readonly string[]\n /** The slash name and aliases that passed validation. */\n readonly slash?: { readonly name: string, readonly aliases: readonly string[], readonly argumentHint?: string }\n /** Aborts when the registering owner is disposed. */\n readonly signal: AbortSignal\n /** The extension's logger. */\n readonly logger: Logger\n /** The current title. */\n title: () => string\n /** The current description. */\n description: () => string | undefined\n /** The current `enabled` value. */\n enabled: () => boolean\n /** Calls `onChange` when a bound field changes. Returns the unsubscribe. */\n watch: (onChange: () => void) => () => void\n /** The command's `run`, attributed. Throws and rejects like the original. */\n run?: (invocation: CommandInvocation) => void | false | Promise<void | false>\n /** The command's `steps`, attributed. */\n steps?: readonly CommandStep[]\n /** Argument completion; never throws. */\n complete?: (prefix: string) => Promise<readonly CommandArgSuggestion[]>\n}\n\n/** A command as {@link CommandsDomain.list} reports it. */\nexport interface CommandListing {\n /** Published id. */\n id: string\n /** Current title. */\n title: string\n /** Slash name, without the `/`. */\n slash?: string\n /** Effective chords. */\n bind?: readonly string[]\n}\n\n/** A projected `/` command: the chat {@link Command} plus where it came from. */\nexport type SlashCommand = Command & {\n /** Published id of the command. */\n readonly commandId: string\n /** Hint shown after the name. */\n readonly argumentHint?: string\n}\n\n/** A projected palette item. `featured` and `suggested` are not part of {@link PaletteItem} yet. */\nexport type CommandPaletteItem = PaletteItem & { featured?: true, suggested?: true }\n\n/** Host side of the registry. Every member is optional. */\nexport interface CommandHostPort {\n /** Built-in commands, for {@link CommandRegistry.list}. */\n builtins?: () => readonly CommandListing[]\n /**\n * The host's built-in key bindings (its keybinding registry), with their\n * effective chords after `keybindings.json`, for\n * {@link CommandRegistry.keymapEntries}. An entry here wins over a\n * built-in command of the same id.\n */\n keybindings?: () => readonly KeymapEntry[]\n /** Runs a built-in command. Returns `false` when the id is unknown. */\n runBuiltin?: (id: string, opts: { args: string, sessionId?: string }) => boolean | Promise<boolean>\n /**\n * The session-bound members (`emit`, `runAgent`, `interaction`…) for a run\n * that does not come from `/`. Omit what the host cannot offer.\n */\n invocation?: (source: CommandSource, sessionId?: string) => Partial<CommandStepContext>\n /** Submits `/name args` through the host's prompt pipeline (runs a steps-only command from a key or `run`). */\n submitSlash?: (text: string, sessionId?: string) => void | Promise<void>\n}\n\n/** Options for {@link createCommandRegistry}. */\nexport interface CommandRegistryOptions {\n /** Host effects. */\n port?: CommandHostPort\n /** The keymap to bind into. Default: a new one. */\n keymap?: Keymap\n /** Registry-level log (listener errors). */\n logger?: Logger\n}\n\n/** What {@link createCommandsDomain} needs from the registry. */\nexport interface CommandsDomainPort {\n /** Adds a command. A duplicate published id is refused with a warning. */\n add: (entry: CommandEntry) => Disposable\n /** Adds a dynamic palette provider. A duplicate id is refused with a warning. */\n addProvider: (entry: ExtensionPaletteProviderEntry, logger: Logger) => Disposable\n /** Runs a command by published id. */\n run: (id: string, opts?: { args?: string, sessionId?: string }) => Promise<boolean>\n /** Every command, built-ins included. */\n list: () => readonly CommandListing[]\n /** Every command with its effective bindings, scope and mode: built-in commands and keys, then extension commands. */\n keymapEntries: () => readonly KeymapEntry[]\n /** The shared keymap. */\n readonly keymap: Keymap\n}\n\n/** The host-wide command registry. */\nexport interface CommandRegistry extends CommandsDomainPort {\n /** The extension `/` commands, collisions resolved (first registration wins). */\n slashCommands: () => readonly SlashCommand[]\n /** Palette providers: one static provider per extension, then the dynamic ones. */\n paletteProviders: () => readonly ExtensionPaletteProviderEntry[]\n /** The commands as {@link ExtensionKeybinding}s (default chords; the host applies `keybindings.json`). */\n keybindings: () => readonly ExtensionKeybinding[]\n /** Footer hints for commands with `hint: true` and a chord. */\n footerHints: () => readonly ExtensionFooterHint[]\n /** A command by published id. */\n get: (id: string) => CommandEntry | undefined\n /** Calls `listener` after any projection changed. Returns the unsubscribe. */\n subscribe: (listener: () => void) => () => void\n /** Releases the keymap subscription. */\n dispose: () => void\n}\n\ninterface Projections {\n slash?: SlashCommand[]\n palette?: ExtensionPaletteProviderEntry[]\n keybindings?: ExtensionKeybinding[]\n hints?: ExtensionFooterHint[]\n}\n\nconst WHEN_DISABLED = {\n session: 'Needs an open session',\n busy: 'Wait for the run to finish',\n} as const\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function'\n}\n\nfunction linkSignals(owner: AbortSignal, host: AbortSignal | undefined): AbortSignal {\n return host && host !== owner ? AbortSignal.any([owner, host]) : owner\n}\n\n/** Runs commands for keys, the palette and `run`, building the invocation from the host port. */\nfunction createRunner(port: CommandHostPort) {\n const invocation = (entry: CommandEntry, source: CommandSource, args: string, sessionId?: string): CommandInvocation => {\n const host = port.invocation?.(source, sessionId) ?? {}\n return {\n ...host,\n source,\n args,\n ...(sessionId !== undefined ? { sessionId } : {}),\n signal: linkSignals(entry.signal, host.signal),\n }\n }\n\n // Runs a command from a key: synchronous so the host knows at once whether\n // the key was used. An async run claims the key; its `false` comes too late.\n const triggerFromKey = (entry: CommandEntry, ctx: KeyTriggerContext): boolean => {\n if (!entry.run) {\n if (!entry.slash || !port.submitSlash)\n return false\n void Promise.resolve(port.submitSlash(`/${entry.slash.name}`, ctx.focus.sessionId)).catch(() => undefined)\n return true\n }\n let result: void | false | Promise<void | false>\n try {\n result = entry.run(invocation(entry, 'key', '', ctx.focus.sessionId))\n }\n catch {\n return true\n }\n if (isThenable(result)) {\n void result.then(\n (value) => {\n if (value === false)\n entry.logger.debug('commands: an async run returned false; the key was already used', { command: entry.id })\n },\n () => undefined,\n )\n return true\n }\n return result !== false\n }\n\n const runEntry = async (entry: CommandEntry, source: CommandSource, args: string, sessionId?: string): Promise<boolean> => {\n if (!entry.enabled())\n return false\n if (entry.run) {\n try {\n await entry.run(invocation(entry, source, args, sessionId))\n }\n catch {\n // Already attributed to the extension by the domain.\n }\n return true\n }\n if (entry.slash && port.submitSlash) {\n await port.submitSlash(`/${entry.slash.name}${args ? ` ${args}` : ''}`, sessionId)\n return true\n }\n return false\n }\n return { triggerFromKey, runEntry }\n}\n\n/** The `/` projection: first registration wins, colliding names and aliases are dropped with a warning. */\nfunction projectSlash(entries: readonly CommandEntry[], warnOnce: (entry: CommandEntry, key: string, message: string, attrs: Record<string, unknown>) => void): SlashCommand[] {\n const out: SlashCommand[] = []\n // Same rule as `mergeCommands`: first registration wins, case-insensitive,\n // aliases reserve names. A later command whose alias is taken keeps its\n // name and loses only the alias.\n const owners = new Map<string, string>()\n for (const entry of entries) {\n if (!entry.slash || !entry.enabled())\n continue\n const name = entry.slash.name.toLowerCase()\n const taken = owners.get(name)\n if (taken !== undefined) {\n warnOnce(entry, `name:${name}`, 'commands: slash name already taken, the command is not reachable by /', { command: entry.id, name: entry.slash.name, owner: taken })\n continue\n }\n owners.set(name, entry.id)\n const aliases: string[] = []\n for (const alias of entry.slash.aliases) {\n const key = alias.toLowerCase()\n const aliasOwner = owners.get(key)\n if (aliasOwner !== undefined) {\n if (aliasOwner !== entry.id)\n warnOnce(entry, `alias:${key}`, 'commands: slash alias already taken, dropped', { command: entry.id, alias, owner: aliasOwner })\n continue\n }\n owners.set(key, entry.id)\n aliases.push(alias)\n }\n const run = entry.run\n const steps: readonly CommandStep[] = entry.steps ?? (run\n ? [{\n run: async (ctx: CommandStepContext) => {\n await run({ ...ctx, source: 'slash', ...(ctx.session ? { sessionId: ctx.session.id } : {}) })\n },\n }]\n : [])\n const complete = entry.complete\n out.push({\n commandId: entry.id,\n name: entry.slash.name,\n group: entry.extensionId,\n description: entry.description() ?? entry.title(),\n steps,\n ...(aliases.length > 0 ? { aliases } : {}),\n ...(entry.slash.argumentHint ? { argumentHint: entry.slash.argumentHint } : {}),\n ...(complete ? { completeArgs: (prefix: string) => complete(prefix) } : {}),\n })\n }\n return out\n}\n\n/** One command as a palette row; `when` becomes a `disabled` reason. */\nfunction paletteItem(entry: CommandEntry, ctx: PaletteContext, source: string, keymap: Keymap): CommandPaletteItem {\n const when = entry.spec.when ?? 'always'\n const disabled = when === 'session' && !ctx.sessionId\n ? WHEN_DISABLED.session\n : when === 'idle' && (!ctx.sessionId || ctx.busy)\n ? (ctx.sessionId ? WHEN_DISABLED.busy : WHEN_DISABLED.session)\n : undefined\n const description = entry.description()\n const keywords = entry.spec.keywords?.split(/\\s+/).filter(Boolean)\n const chord = keymap.bindings(entry.id)[0]\n const palette = entry.spec.palette\n return {\n id: entry.id,\n title: entry.title(),\n group: entry.spec.group?.trim() || entry.group,\n source,\n ...(description ? { description } : {}),\n ...(keywords && keywords.length > 0 ? { keywords } : {}),\n ...(entry.spec.icon ? { icon: entry.spec.icon } : {}),\n ...(chord ? { keybinding: chord } : {}),\n ...(disabled ? { disabled } : {}),\n ...(typeof palette === 'object' && palette.featured ? { featured: true as const } : {}),\n ...(typeof palette === 'object' && palette.suggested ? { suggested: true as const } : {}),\n }\n}\n\n/** `ctx.keymap.list`: built-in commands and keys (a key wins over a command of its id), then the extension commands, with their effective bindings. */\nfunction keymapEntriesOf(port: CommandHostPort, keymap: Keymap, entries: readonly CommandEntry[]): KeymapEntry[] {\n const builtins = new Map<string, KeymapEntry>()\n for (const b of port.builtins?.() ?? [])\n builtins.set(b.id, { id: b.id, title: b.title, bindings: [...(b.bind ?? [])], scope: 'global', editable: false })\n for (const k of port.keybindings?.() ?? [])\n builtins.set(k.id, { ...k, bindings: [...k.bindings] })\n const bound = new Map(keymap.list().map(b => [b.commandId, b]))\n const own = entries.map((e): KeymapEntry => {\n const b = bound.get(e.id)\n const mode = b?.mode ?? e.spec.mode\n return {\n id: e.id,\n title: e.title(),\n bindings: [...(b?.chords ?? e.chords)],\n scope: b?.scope ?? e.spec.scope ?? 'global',\n ...(mode !== undefined ? { mode } : {}),\n editable: b?.editable ?? e.spec.editable === true,\n extensionId: e.extensionId,\n }\n })\n return [...builtins.values(), ...own]\n}\n\n/**\n * Makes the host-wide command registry.\n *\n * @param opts - Host port, keymap and logger.\n */\nexport function createCommandRegistry(opts: CommandRegistryOptions = {}): CommandRegistry {\n const port = opts.port ?? {}\n const keymap = opts.keymap ?? createKeymap(opts.logger ? { logger: opts.logger } : {})\n const entries: CommandEntry[] = []\n const providers: { entry: ExtensionPaletteProviderEntry, owner: string }[] = []\n const extensionOrder: string[] = []\n const listeners = new Set<() => void>()\n const warned = new Set<string>()\n let cache: Projections = {}\n\n const changed = () => {\n cache = {}\n for (const listener of [...listeners]) {\n try {\n listener()\n }\n catch (error) {\n opts.logger?.warn('commands: listener threw', { error: String(error) })\n }\n }\n }\n const unsubscribeKeymap = keymap.subscribe(changed)\n\n const noteExtension = (id: string) => {\n if (!extensionOrder.includes(id))\n extensionOrder.push(id)\n }\n\n const { triggerFromKey, runEntry } = createRunner(port)\n\n const warnOnce = (entry: CommandEntry, key: string, message: string, attrs: Record<string, unknown>) => {\n const id = `${entry.id}\\0${key}`\n if (warned.has(id))\n return\n warned.add(id)\n entry.logger.warn(message, attrs)\n }\n\n const staticProvider = (extensionId: string): ExtensionPaletteProviderEntry | undefined => {\n const own = entries.filter(e => e.extensionId === extensionId && e.spec.palette !== false && e.enabled())\n if (own.length === 0)\n return undefined\n const id = `${extensionId}/commands`\n return {\n id,\n owner: extensionId,\n group: own[0]!.group,\n items: ctx => own.filter(e => e.enabled()).map(e => paletteItem(e, ctx, id, keymap)),\n run: async (itemId, ctx) => {\n const entry = own.find(e => e.id === itemId)\n if (!entry)\n return undefined\n // A steps-only command needs the prompt: put `/name ` in the composer.\n if (!entry.run && entry.slash)\n return { kind: 'insert', text: `/${entry.slash.name} ` }\n // Started, not awaited: the palette closes at once, so a dialog the command opens can show.\n void runEntry(entry, 'palette', '', ctx.sessionId)\n return undefined\n },\n }\n }\n\n const projectPalette = (): ExtensionPaletteProviderEntry[] => {\n const out: ExtensionPaletteProviderEntry[] = []\n for (const extensionId of extensionOrder) {\n const provider = staticProvider(extensionId)\n if (provider)\n out.push(provider)\n }\n for (const { entry } of providers)\n out.push(entry)\n return out\n }\n\n const projectKeybindings = (): ExtensionKeybinding[] => entries\n .filter(e => e.enabled() && (e.run || e.slash))\n .map(e => ({\n id: e.id,\n default: e.chords.join(' | '),\n label: e.title(),\n description: e.description() ?? '',\n onTrigger: () => {\n triggerFromKey(e, { chord: '', focus: { scope: 'global' } })\n },\n }))\n\n const projectHints = (): ExtensionFooterHint[] => {\n const out: ExtensionFooterHint[] = []\n for (const entry of entries) {\n if (!entry.spec.hint || !entry.enabled())\n continue\n const chord = keymap.bindings(entry.id)[0]\n if (chord)\n out.push({ key: chord, label: entry.title() })\n }\n return out\n }\n\n const registry: CommandRegistry = {\n keymap,\n add(entry) {\n if (entries.some(e => e.id === entry.id)) {\n entry.logger.warn('commands.register: a command with this id is already registered, ignored', { command: entry.id })\n return { dispose() {} }\n }\n noteExtension(entry.extensionId)\n entries.push(entry)\n const unwatch = entry.watch(changed)\n const binding = keymap.add({\n commandId: entry.id,\n defaults: entry.chords,\n ...(entry.spec.scope ? { scope: entry.spec.scope } : {}),\n ...(entry.spec.editable ? { editable: true } : {}),\n ...(entry.spec.mode ? { mode: entry.spec.mode } : {}),\n ...(entry.spec.when ? { when: entry.spec.when } : {}),\n enabled: entry.enabled,\n trigger: ctx => triggerFromKey(entry, ctx),\n })\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n unwatch()\n const at = entries.indexOf(entry)\n if (at >= 0)\n entries.splice(at, 1)\n binding.dispose()\n changed()\n },\n }\n },\n addProvider(entry, logger) {\n if (providers.some(p => p.entry.id === entry.id)) {\n logger.warn('commands.provider: a provider with this id is already registered, ignored', { provider: entry.id })\n return { dispose() {} }\n }\n noteExtension(entry.owner)\n const slot = { entry, owner: entry.owner }\n providers.push(slot)\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n const at = providers.indexOf(slot)\n if (at >= 0)\n providers.splice(at, 1)\n changed()\n },\n }\n },\n async run(id, runOpts = {}) {\n const entry = entries.find(e => e.id === id)\n if (entry)\n return runEntry(entry, 'api', runOpts.args ?? '', runOpts.sessionId)\n if (!port.runBuiltin)\n return false\n return port.runBuiltin(id, { args: runOpts.args ?? '', ...(runOpts.sessionId !== undefined ? { sessionId: runOpts.sessionId } : {}) })\n },\n list() {\n const own = entries.map((e): CommandListing => {\n const bind = keymap.bindings(e.id)\n return {\n id: e.id,\n title: e.title(),\n ...(e.slash ? { slash: e.slash.name } : {}),\n ...(bind.length > 0 ? { bind } : {}),\n }\n })\n return [...(port.builtins?.() ?? []), ...own]\n },\n keymapEntries: () => keymapEntriesOf(port, keymap, entries),\n slashCommands: () => (cache.slash ??= projectSlash(entries, warnOnce)),\n paletteProviders: () => (cache.palette ??= projectPalette()),\n keybindings: () => (cache.keybindings ??= projectKeybindings()),\n footerHints: () => (cache.hints ??= projectHints()),\n get: id => entries.find(e => e.id === id),\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n dispose() {\n unsubscribeKeymap()\n },\n }\n return registry\n}\n","/**\n * Exposes the router to remote callers: protocol clients over IPC\n * (`rpc.call` / `rpc.event`) and HTTP (`POST /rpc/<contract>/<method>`),\n * and an extension's own UI in a renderer. The host implements the\n * {@link RpcRemoteTransport} port and decides who a connection is; the\n * bridge checks the payload at the trust boundary, passes the host's scope\n * check to the router (a method's `scope` against the connection's token)\n * and forwards events.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcRouter } from './router'\nimport type { RpcCaller, RpcCallParams, RpcEventEnvelope, RpcResponseEnvelope } from './wire'\nimport { jsonBytes, RPC_MAX_PAYLOAD_BYTES, RpcErrorType } from './wire'\n\n/** A remote caller. Remote peers are never extensions. */\nexport type RpcRemoteCaller = Extract<RpcCaller, { kind: 'ui' | 'client' }>\n\n/** What the host provides so remote peers hear events. */\nexport interface RpcRemoteTransport {\n /** Sends one event to remote peers as the `rpc.event` signal. The host picks the recipients. */\n publish: (event: RpcEventEnvelope) => void\n}\n\n/** Options of {@link createRpcRemoteBridge}. */\nexport interface RpcRemoteBridgeOptions {\n /** JSON size cap for request input, response output and event data. Defaults to {@link RPC_MAX_PAYLOAD_BYTES}. */\n maxPayloadBytes?: number\n /** Told about each event not published (not JSON, or over the cap). */\n onDrop?: (event: RpcEventEnvelope, reason: string) => void\n}\n\n/** The remote side of the router. Dispose it to stop forwarding events. */\nexport interface RpcRemoteBridge extends Disposable {\n /**\n * Runs a remote call. `params` is untrusted (`rpc.call` params or the\n * HTTP route plus body). `authorize`: whether the connection's token\n * reaches a method that needs that scope; absent, not limited (a local\n * connection). Never rejects.\n */\n call: (params: unknown, caller: RpcRemoteCaller, signal?: AbortSignal, authorize?: (scope: AccessScope) => boolean) => Promise<RpcResponseEnvelope>\n}\n\nfunction invalid(contract: string, method: string, message: string): RpcResponseEnvelope {\n return { ok: false, error: { type: RpcErrorType.InvalidInput, message }, meta: { contract, method, scope: 'chat' } }\n}\n\n/**\n * Connects `router` to a host transport.\n *\n * @param router - The process router.\n * @param transport - The host's event publisher.\n * @param options - Payload cap and drop reporting.\n * @returns The bridge.\n */\nexport function createRpcRemoteBridge(router: RpcRouter, transport: RpcRemoteTransport, options: RpcRemoteBridgeOptions = {}): RpcRemoteBridge {\n const max = options.maxPayloadBytes ?? RPC_MAX_PAYLOAD_BYTES\n const events = router.onEvent((event) => {\n const bytes = jsonBytes(event.data)\n if (bytes === null)\n return options.onDrop?.(event, 'event data is not JSON')\n if (bytes > max)\n return options.onDrop?.(event, `event data is ${bytes} bytes, over the ${max} byte cap`)\n transport.publish(event)\n })\n\n return {\n async call(params, caller, signal, authorize) {\n if (typeof params !== 'object' || params === null)\n return invalid('', '', 'rpc.call params must be an object')\n const { contract, method, input, directory } = params as Partial<RpcCallParams>\n if (typeof contract !== 'string' || typeof method !== 'string' || !contract || !method)\n return invalid(String(contract ?? ''), String(method ?? ''), 'rpc.call needs a contract and a method')\n if (directory !== undefined && typeof directory !== 'string')\n return invalid(contract, method, 'rpc.call directory must be a string')\n const inBytes = jsonBytes(input)\n if (inBytes === null || inBytes > max)\n return invalid(contract, method, inBytes === null ? 'input is not JSON' : `input is ${inBytes} bytes, over the ${max} byte cap`)\n const response = await router.call({ contract, method, input, ...(directory === undefined ? {} : { directory }) }, { caller, ...(signal ? { signal } : {}), ...(authorize ? { authorize } : {}) })\n if (!response.ok) {\n const errBytes = jsonBytes(response.error.data)\n if (errBytes === null || errBytes > max)\n return { ok: false, error: { type: response.error.type, message: response.error.message }, meta: response.meta }\n return response\n }\n const outBytes = jsonBytes(response.output)\n if (outBytes === null || outBytes > max) {\n const message = outBytes === null ? 'output is not JSON' : `output is ${outBytes} bytes, over the ${max} byte cap`\n return { ok: false, error: { type: RpcErrorType.Internal, message }, meta: response.meta }\n }\n return response\n },\n dispose: () => events.dispose(),\n }\n}\n","/**\n * Id ownership shared by contracts, registries and RPC: an extension may\n * publish under its own id, or under `<id>.<name>`.\n */\n\n/**\n * Whether `extensionId` may publish `id`.\n *\n * @param extensionId - The publishing extension.\n * @param id - The contract, registry or RPC contract id.\n * @returns `true` when `id` is the extension id or starts with `<extensionId>.`.\n */\nexport function ownsId(extensionId: string, id: string): boolean {\n return id === extensionId || (id.length > extensionId.length + 1 && id.startsWith(`${extensionId}.`))\n}\n\n/**\n * Throws when `extensionId` may not publish `id` (see {@link ownsId}).\n *\n * @param what - The call, for the message (`contracts.provide`).\n * @param extensionId - The publishing extension.\n * @param id - The id it tried to publish.\n */\nexport function assertOwnsId(what: string, extensionId: string, id: string): void {\n if (!ownsId(extensionId, id))\n throw new Error(`${what}: \"${id}\" must be \"${extensionId}\" or start with \"${extensionId}.\"`)\n}\n","/**\n * Ties a registration to its owner: disposing the owner disposes it, and\n * disposing it early releases the owner's hook.\n */\n\nimport type { Disposable, Owner } from '../api/core'\n\n/**\n * Wraps `dispose` so it runs once, either when called or when `owner` is disposed.\n *\n * @param owner - The owner the registration belongs to.\n * @param dispose - Withdraws the registration.\n * @returns The registration's Disposable.\n */\nexport function bindToOwner(owner: Owner, dispose: () => void): Disposable {\n let done = false\n let hook: Disposable | undefined\n const run = (): void => {\n if (done)\n return\n done = true\n hook?.dispose()\n dispose()\n }\n hook = owner.onCleanup(run)\n return { dispose: run }\n}\n","/**\n * The process-wide RPC router: registrations by contract id, calls, and\n * event fan-out. One per host process. Every extension's rpc domain\n * registers on it and calls through it; the remote bridge exposes it to\n * protocol clients.\n *\n * A contract id holds a stack of registrations: the same extension loaded\n * for several directories (daemon), or a reloading instance overlapping the\n * old one. A call goes to the registration of the requested directory, else\n * the newest.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcCaller, RpcEventEnvelope, RpcRequestEnvelope, RpcResponseEnvelope, RpcResult, RpcWireError } from './wire'\nimport { errorMessage } from './schema'\nimport { RpcErrorType } from './wire'\n\n/** What a registration handler receives besides method and input. */\nexport interface RpcHandlerContext {\n /** Aborts when the caller gives up. */\n readonly signal: AbortSignal\n /** Who calls. */\n readonly caller: RpcCaller\n}\n\n/** One contract implementation, as the router holds it. */\nexport interface RpcRouterEntry {\n /** Contract id. */\n readonly contractId: string\n /** The implementing extension. */\n readonly extensionId: string\n /** The project the implementing extension runs in. */\n readonly directory: string\n /** Method names with the least token scope a protocol client needs. */\n readonly methods: Readonly<Record<string, { readonly scope: AccessScope }>>\n /** Event names of the contract. */\n readonly events: readonly string[]\n /** Runs a method the entry lists. Validates and never throws. */\n handle: (method: string, input: unknown, ctx: RpcHandlerContext) => Promise<RpcResult>\n}\n\n/** A registered contract, as hosts list it (for the protocol hello, Settings). */\nexport interface RpcContractDescriptor {\n /** Contract id. */\n contract: string\n /** The implementing extension. */\n extensionId: string\n /** The project it runs in. */\n directory: string\n /** Methods with the least token scope a protocol client needs. */\n methods: { name: string, scope: AccessScope }[]\n /** Event names. */\n events: string[]\n}\n\n/** Options of {@link RpcRouter.call}. */\nexport interface RpcRouterCallOptions {\n /** Who calls. */\n caller: RpcCaller\n /**\n * Whether the caller's token reaches a method that needs `scope`. Absent:\n * not limited (in-process callers, local connections, other extensions).\n * A remote host passes its connection's check (`scopeAllows`).\n */\n authorize?: (scope: AccessScope) => boolean\n /** Aborts the call: it then answers `rpc.aborted`. */\n signal?: AbortSignal\n}\n\n/** The process-wide RPC router. */\nexport interface RpcRouter {\n /** Adds an implementation. Disposing it removes it; the one below (if any) answers again. */\n register: (entry: RpcRouterEntry) => Disposable\n /** Runs a call. Never rejects: failures are `ok: false` envelopes. */\n call: (request: RpcRequestEnvelope, opts: RpcRouterCallOptions) => Promise<RpcResponseEnvelope>\n /** Delivers an event to local subscribers and to {@link RpcRouter.onEvent} listeners. */\n emit: (event: RpcEventEnvelope) => void\n /** Listens to one event of one contract, whether or not it is registered yet. */\n subscribe: (contract: string, event: string, listener: (event: RpcEventEnvelope) => void) => Disposable\n /** Listens to every event (the remote bridge forwards them). */\n onEvent: (listener: (event: RpcEventEnvelope) => void) => Disposable\n /** Calls `listener` after each register and unregister. */\n onChange: (listener: () => void) => Disposable\n /** Whether `contract` has a registration. */\n has: (contract: string) => boolean\n /** Every active registration (the one calls go to without a directory), in registration order. */\n list: () => RpcContractDescriptor[]\n}\n\n/**\n * Resolves with `promise`, or with `onAbort()` once `signal` aborts, whichever comes first.\n *\n * @param promise - The work.\n * @param signal - The signal to race.\n * @param onAbort - The value when aborted.\n */\nexport function raceAbort<T, A>(promise: Promise<T>, signal: AbortSignal, onAbort: () => A): Promise<T | A> {\n if (signal.aborted)\n return Promise.resolve(onAbort())\n return new Promise<T | A>((resolve, reject) => {\n const abort = (): void => resolve(onAbort())\n signal.addEventListener('abort', abort, { once: true })\n promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort))\n })\n}\n\nfunction failure(type: string, message: string, data?: unknown): { ok: false, error: RpcWireError } {\n return { ok: false, error: data === undefined ? { type, message } : { type, message, data } }\n}\n\nfunction safeEach<T>(listeners: Set<(value: T) => void>, value: T): void {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n }\n catch {\n // Domain listeners are guarded; a host listener throwing must not stop delivery.\n }\n }\n}\n\n/**\n * Creates an empty router.\n *\n * @returns The router, shared by every extension of the process.\n */\nexport function createRpcRouter(): RpcRouter {\n const entries = new Map<string, RpcRouterEntry[]>()\n const subscribers = new Map<string, Set<(event: RpcEventEnvelope) => void>>()\n const firehose = new Set<(event: RpcEventEnvelope) => void>()\n const changes = new Set<() => void>()\n\n function pick(contract: string, directory: string | undefined): RpcRouterEntry | undefined {\n const stack = entries.get(contract)\n if (!stack?.length)\n return undefined\n if (directory !== undefined) {\n for (let i = stack.length - 1; i >= 0; i--) {\n if (stack[i]!.directory === directory)\n return stack[i]\n }\n }\n return stack.at(-1)\n }\n\n function changed(): void {\n for (const listener of [...changes]) {\n try {\n listener()\n }\n catch {}\n }\n }\n\n function listen<T>(set: Set<T>, listener: T, cleanup?: () => void): Disposable {\n set.add(listener)\n return {\n dispose() {\n set.delete(listener)\n cleanup?.()\n },\n }\n }\n\n return {\n register(entry) {\n const stack = entries.get(entry.contractId) ?? []\n stack.push(entry)\n entries.set(entry.contractId, stack)\n changed()\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n stack.splice(stack.indexOf(entry), 1)\n if (!stack.length)\n entries.delete(entry.contractId)\n changed()\n },\n }\n },\n\n async call(request, { caller, signal, authorize }) {\n const { contract, method } = request\n const entry = pick(contract, request.directory)\n const spec = entry && Object.hasOwn(entry.methods, method) ? entry.methods[method] : undefined\n const meta = { contract, method, scope: spec?.scope ?? 'chat' as const, ...(entry ? { extensionId: entry.extensionId } : {}) }\n const reply = (result: RpcResult): RpcResponseEnvelope => ({ ...result, meta })\n if (!entry)\n return reply(failure(RpcErrorType.Unavailable, `no extension provides \"${contract}\"`))\n if (!spec)\n return reply(failure(RpcErrorType.Unavailable, `\"${contract}\" has no method \"${method}\"`))\n if (authorize && !authorize(spec.scope))\n return reply(failure(RpcErrorType.Forbidden, `\"${contract}.${method}\" needs a token with the ${spec.scope} scope`))\n const callSignal = signal ?? new AbortController().signal\n const aborted = (): RpcResult => failure(RpcErrorType.Aborted, `the call to \"${contract}.${method}\" was aborted`)\n if (callSignal.aborted)\n return reply(aborted())\n try {\n return reply(await raceAbort(entry.handle(method, request.input, { signal: callSignal, caller }), callSignal, aborted))\n }\n catch (error) {\n return reply(failure(RpcErrorType.Internal, errorMessage(error)))\n }\n },\n\n emit(event) {\n const set = subscribers.get(`${event.contract}\\0${event.event}`)\n if (set)\n safeEach(set, event)\n safeEach(firehose, event)\n },\n\n subscribe(contract, event, listener) {\n const key = `${contract}\\0${event}`\n let set = subscribers.get(key)\n if (!set) {\n set = new Set()\n subscribers.set(key, set)\n }\n const own = set\n return listen(own, listener, () => {\n if (!own.size && subscribers.get(key) === own)\n subscribers.delete(key)\n })\n },\n\n onEvent: listener => listen(firehose, listener),\n onChange: listener => listen(changes, listener),\n has: contract => (entries.get(contract)?.length ?? 0) > 0,\n list: () => [...entries.values()].map((stack) => {\n const entry = stack.at(-1)!\n return {\n contract: entry.contractId,\n extensionId: entry.extensionId,\n directory: entry.directory,\n methods: Object.entries(entry.methods).map(([name, m]) => ({ name, scope: m.scope })),\n events: [...entry.events],\n }\n }),\n }\n}\n","/**\n * `ctx.rpc`: implement contracts and call them. A per-extension view over\n * the process-wide {@link RpcRouter}. Inputs, outputs, declared error data\n * and event data are validated against the contract's schemas on the\n * implementing side, so every caller (in-process or remote) gets the same\n * checks.\n */\n\nimport type { AccessScope, Disposable } from '../api/core'\nimport type { RpcCallContext, RpcClient, RpcContract, RpcDomain, RpcError, RpcEvent, RpcEvents, RpcImplementation, RpcMethodSpec, RpcRegistration } from '../api/rpc'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RpcRouter, RpcRouterEntry } from './router'\nimport type { RpcCaller, RpcEventEnvelope, RpcResult } from './wire'\nimport { DisposedError } from '../api/core'\nimport { RpcCallError } from '../api/rpc'\nimport { assertOwnsId } from '../contracts/ids'\nimport { bindToOwner } from '../contracts/owned'\nimport { raceAbort } from './router'\nimport { checkSchema, errorMessage, isPlainRecord } from './schema'\nimport { RpcErrorType } from './wire'\n\n/** What the host tells the rpc domain about where the extension runs. */\nexport interface RpcDomainPort {\n /** The project the extension runs in. Stamped on its events; its calls prefer providers of the same directory. */\n readonly directory: string\n}\n\n/** Events a `subscribe` iterator keeps for a slow reader before it drops the oldest. */\nexport const RPC_SUBSCRIBE_BUFFER = 1024\n\nconst ACCESS_SCOPES: readonly unknown[] = ['chat', 'approve', 'admin'] satisfies readonly AccessScope[]\n\ntype AnyImpl = Record<string, (input: unknown, ctx: RpcCallContext<RpcMethodSpec>) => unknown>\n\nfunction isRpcError(value: unknown): value is RpcError {\n return typeof value === 'object' && value !== null && (value as { kind?: unknown }).kind === 'rpc-error'\n && typeof (value as { type?: unknown }).type === 'string'\n}\n\nfunction failure(type: string, message: string, data?: unknown): RpcResult {\n return { ok: false, error: data === undefined ? { type, message } : { type, message, data } }\n}\n\nfunction publicCaller(caller: RpcCaller): RpcCallContext<RpcMethodSpec>['caller'] {\n switch (caller.kind) {\n case 'extension': return { kind: 'extension', id: caller.id }\n case 'ui': return { kind: 'ui' }\n case 'client': return { kind: 'client', clientId: caller.clientId }\n }\n}\n\nfunction assertContract(what: string, contract: RpcContract): void {\n if (contract?.kind !== 'rpc' || typeof contract.id !== 'string')\n throw new TypeError(`${what}: not an RPC contract (use Rpc.define)`)\n if (Object.hasOwn(contract.methods, 'events'))\n throw new Error(`${what}: \"${contract.id}\" has a method named \"events\", which clients reserve for events`)\n for (const [name, spec] of Object.entries(contract.methods)) {\n if (Object.hasOwn(spec, 'internal'))\n throw new TypeError(`${what}: \"${contract.id}.${name}\" declares \"internal\", which no longer exists; set scope ('admin' for methods only the app should call)`)\n if (spec.scope !== undefined && !ACCESS_SCOPES.includes(spec.scope))\n throw new TypeError(`${what}: \"${contract.id}.${name}\" scope must be chat, approve or admin`)\n for (const type of Object.keys(spec.errors ?? {})) {\n if (type.startsWith('rpc.'))\n throw new Error(`${what}: \"${contract.id}.${name}\" declares error \"${type}\"; names starting with \"rpc.\" are reserved`)\n }\n }\n}\n\n/**\n * Creates the rpc domain of one extension (or one scope of it).\n *\n * @param deps - Extension id, owner, guard and logger.\n * @param router - The process-wide router, from `createRpcRouter`.\n * @param port - Where the extension runs.\n * @returns `ctx.rpc`.\n */\nexport function createRpcDomain(deps: DomainDeps, router: RpcRouter, port: RpcDomainPort): RpcDomain {\n const { extensionId, owner, guard, logger } = deps\n const self: RpcCaller = { kind: 'extension', id: extensionId }\n\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n\n function register<C extends RpcContract>(contract: C, impl: RpcImplementation<C>): RpcRegistration<C> {\n if (owner.disposed)\n throw new DisposedError('rpc.register')\n assertContract('rpc.register', contract)\n assertOwnsId('rpc.register', extensionId, contract.id)\n const methods = contract.methods as Readonly<Record<string, RpcMethodSpec>>\n const handlers = impl as unknown as AnyImpl\n for (const name of Object.keys(methods)) {\n if (typeof handlers[name] !== 'function')\n throw new TypeError(`rpc.register: \"${contract.id}\" has no implementation for \"${name}\"`)\n }\n\n const life = new AbortController()\n const label = (method: string): string => `rpc ${contract.id}.${method}`\n\n async function settleError(spec: RpcMethodSpec, method: string, error: RpcError): Promise<RpcResult> {\n const schema = spec.errors && Object.hasOwn(spec.errors, error.type) ? spec.errors[error.type] : undefined\n if (!schema)\n return failure(RpcErrorType.Internal, `\"${contract.id}.${method}\" returned undeclared error \"${error.type}\": ${error.message}`)\n const check = await checkSchema(schema, error.data)\n if (!check.ok)\n return failure(RpcErrorType.InvalidOutput, `\"${contract.id}.${method}\" error \"${error.type}\" data is invalid: ${check.message}`)\n return failure(error.type, error.message, check.value)\n }\n\n async function handle(method: string, input: unknown, hctx: { signal: AbortSignal, caller: RpcCaller }): Promise<RpcResult> {\n const spec = methods[method]!\n const inCheck = await checkSchema(spec.input, input)\n if (!inCheck.ok)\n return failure(RpcErrorType.InvalidInput, `\"${contract.id}.${method}\" input is invalid: ${inCheck.message}`)\n let thrown: unknown\n // The guard's signal aborts on its timeout; the caller's on abort; `life` when the provider is withdrawn.\n const run = guard.call(label(method), async (timeout) => {\n const ctx: RpcCallContext<RpcMethodSpec> = {\n signal: AbortSignal.any([hctx.signal, life.signal, timeout]),\n caller: publicCaller(hctx.caller),\n error: (type, message, data) => ({ kind: 'rpc-error', type, message, data }),\n }\n try {\n return { value: await handlers[method]!(inCheck.value, ctx) }\n }\n catch (error) {\n if (isRpcError(error))\n return { value: error as unknown }\n thrown = error\n throw error\n }\n })\n const withdrawn = Symbol('withdrawn')\n const settled = await raceAbort(run, life.signal, (): typeof withdrawn => withdrawn)\n if (settled === withdrawn)\n return failure(RpcErrorType.Unavailable, `\"${contract.id}\" was withdrawn during the call`)\n if (settled === undefined) {\n const why = thrown === undefined ? 'failed or timed out' : `threw: ${errorMessage(thrown)}`\n return failure(RpcErrorType.Internal, `\"${contract.id}.${method}\" ${why}`)\n }\n if (isRpcError(settled.value))\n return settleError(spec, method, settled.value)\n const outCheck = await checkSchema(spec.output, settled.value)\n if (!outCheck.ok)\n return failure(RpcErrorType.InvalidOutput, `\"${contract.id}.${method}\" output is invalid: ${outCheck.message}`)\n return { ok: true, output: outCheck.value }\n }\n\n const entry: RpcRouterEntry = {\n contractId: contract.id,\n extensionId,\n directory: port.directory,\n methods: Object.fromEntries(Object.entries(methods).map(([name, spec]) => [name, { scope: spec.scope ?? 'chat' }])),\n events: Object.keys(contract.events),\n handle,\n }\n const routed = router.register(entry)\n let disposed = false\n let queue: Promise<void> | undefined\n\n function deliver(event: string, data: unknown): void {\n if (disposed)\n return\n const envelope: RpcEventEnvelope = {\n type: `rpc.${contract.id}.${event}`,\n contract: contract.id,\n event,\n data: data as Record<string, unknown>,\n location: { directory: port.directory },\n extensionId,\n }\n router.emit(envelope)\n }\n\n function emit(event: string, data: unknown): void {\n if (disposed)\n return\n const spec = Object.hasOwn(contract.events, event) ? contract.events[event] : undefined\n if (!spec)\n throw new Error(`rpc emit: \"${contract.id}\" has no event \"${event}\"`)\n if (!isPlainRecord(data))\n throw new TypeError(`rpc emit: \"${contract.id}.${event}\" data must be an object`)\n const check = checkSchema(spec.schema, data)\n if (!queue && !(check instanceof Promise)) {\n if (!check.ok)\n throw new TypeError(`rpc emit: \"${contract.id}.${event}\" data is invalid: ${check.message}`)\n deliver(event, check.value)\n return\n }\n // An async validator (or one still pending ahead) keeps emit order by queueing.\n const next: Promise<void> = (queue ?? Promise.resolve()).then(async () => {\n const result = await check\n if (result.ok)\n deliver(event, result.value)\n else\n logger.warn(`rpc emit: \"${contract.id}.${event}\" data is invalid, dropped: ${result.message}`, { extensionId })\n })\n queue = next\n void next.then(() => {\n if (queue === next)\n queue = undefined\n })\n }\n\n const handle$ = owned(() => {\n disposed = true\n life.abort()\n routed.dispose()\n })\n return {\n events: { emit: emit as RpcRegistration<C>['events']['emit'] },\n dispose: () => handle$.dispose(),\n }\n }\n\n function client<C extends RpcContract>(contract: C): RpcClient<C> {\n assertContract('rpc.client', contract)\n const out: Record<string, unknown> = {}\n for (const method of Object.keys(contract.methods)) {\n out[method] = async (input: unknown, opts?: { signal?: AbortSignal }) => {\n const signal = opts?.signal ? AbortSignal.any([opts.signal, owner.signal]) : owner.signal\n const request = input === undefined\n ? { contract: contract.id, method, directory: port.directory }\n : { contract: contract.id, method, input, directory: port.directory }\n const response = await router.call(request, { caller: self, signal })\n if (response.ok)\n return response.output\n throw new RpcCallError(response.error.type, response.error.message, response.error.data)\n }\n }\n out.events = clientEvents(deps, router, contract)\n return out as RpcClient<C>\n }\n\n return { register, client }\n}\n\n/** The event side of a client: guarded listeners and buffered iterators, ended with the owner. */\nfunction clientEvents(deps: DomainDeps, router: RpcRouter, contract: RpcContract): RpcEvents<RpcContract['events']> {\n const { extensionId, owner, guard, logger } = deps\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n return {\n on(name, listener) {\n if (owner.disposed)\n throw new DisposedError('rpc events.on')\n const label = `rpc event ${contract.id}.${name}`\n const sub = router.subscribe(contract.id, name, event => guard.callSync(label, () => listener(toEvent(event))))\n return owned(() => sub.dispose())\n },\n subscribe(name) {\n return {\n [Symbol.asyncIterator](): AsyncIterator<RpcEvent<unknown>> {\n const buffer: RpcEvent<unknown>[] = []\n let wake: (() => void) | undefined\n let done = owner.disposed\n let dropped = 0\n let sub: Disposable | undefined\n const finish = (): void => {\n done = true\n sub?.dispose()\n sub = undefined\n wake?.()\n }\n if (!done) {\n const routed = router.subscribe(contract.id, name, (event) => {\n if (buffer.length >= RPC_SUBSCRIBE_BUFFER) {\n buffer.shift()\n if (dropped++ === 0)\n logger.warn(`rpc subscribe: \"${contract.id}.${name}\" reader is slow, dropping oldest events`, { extensionId })\n }\n buffer.push(toEvent(event))\n wake?.()\n })\n sub = owned(() => {\n routed.dispose()\n finish()\n })\n }\n return {\n async next() {\n while (true) {\n if (buffer.length)\n return { value: buffer.shift()!, done: false }\n if (done)\n return { value: undefined, done: true }\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n }\n },\n async return() {\n finish()\n buffer.length = 0\n return { value: undefined, done: true }\n },\n }\n },\n }\n },\n }\n}\n\nfunction toEvent(envelope: RpcEventEnvelope): RpcEvent<unknown> {\n return { type: envelope.type, data: envelope.data, location: envelope.location }\n}\n","/**\n * Guards: how the runtime calls extension code (extension API).\n *\n * Extensions run in-process and are trusted, so the guard does not sandbox.\n * It bounds and attributes: every callback runs with a timeout, a throw or a\n * timeout is logged against the extension and turns into a fallback, and an\n * error budget (N failures in a sliding window) trips once so the host can\n * disable the extension with the reason. A {@link StallMonitor} times the\n * synchronous part of each callback and names the extension that blocked the\n * event loop. Every call holds a lease on the extension's owner while it\n * runs (`lease`), so an unload waits for it before tearing down what it uses;\n * once the extension is unloaded a call returns its fallback without running.\n */\n\nimport type { Logger } from '../../logger'\nimport type { Guard } from './deps'\nimport { errorMessage } from '../../errors'\nimport { DisposedError } from '../api/core'\n\n/** Default bound of one async extension callback. Matches the setup bound (`SETUP_TIMEOUT_MS`, `runtime/lifecycle.ts`). */\nexport const DEFAULT_CALLBACK_TIMEOUT_MS = 10_000\n\n/** Default synchronous run time that counts as an event-loop stall. */\nexport const DEFAULT_STALL_THRESHOLD_MS = 500\n\n/** How many failures in how long trip the guard. */\nexport interface ErrorBudget {\n /** Failures that trip the guard. */\n maxFailures: number\n /** Sliding window the failures are counted in, in ms. */\n windowMs: number\n}\n\n/** Default {@link ErrorBudget}: 5 failures within a minute. */\nexport const DEFAULT_ERROR_BUDGET: Readonly<ErrorBudget> = { maxFailures: 5, windowMs: 60_000 }\n\n/** An extension callback that threw or timed out, attributed to its extension. */\nexport class ExtensionCallbackError extends Error {\n /** The extension the callback belongs to. */\n readonly extensionId: string\n /** What was called (`'tools.search.execute'`, `'setup'`). */\n readonly label: string\n /** `'error'`: it threw or rejected. `'timeout'`: it did not settle in time. */\n readonly kind: 'error' | 'timeout'\n\n /**\n * @param extensionId - The extension.\n * @param label - What was called.\n * @param kind - Threw or timed out.\n * @param message - Human-readable detail.\n * @param cause - The original error, when it threw.\n */\n constructor(extensionId: string, label: string, kind: 'error' | 'timeout', message: string, cause?: unknown) {\n super(`[${extensionId}] ${label}: ${message}`, cause === undefined ? undefined : { cause })\n this.name = 'ExtensionCallbackError'\n this.extensionId = extensionId\n this.label = label\n this.kind = kind\n }\n}\n\n/** One failure counted in the budget. */\nexport interface GuardFailure {\n /** The attributed error. */\n error: ExtensionCallbackError\n /** When it happened, from the guard's clock. */\n at: number\n}\n\n/** Why a guard tripped. The host disables the extension and shows `reason` in Settings. */\nexport interface GuardTrip {\n /** The extension to disable. */\n extensionId: string\n /** One line for Settings, e.g. `5 errors in 60s. Last: tools.x.execute: boom`. */\n reason: string\n /** The failures in the window that tripped it, oldest first. */\n failures: readonly GuardFailure[]\n}\n\n/** A synchronous callback that ran past the stall threshold. */\nexport interface StallReport {\n /** The extension whose callback was running. */\n extensionId: string\n /** What was called. */\n label: string\n /** Time spent in the callback itself, nested guarded callbacks excluded, in ms. */\n durationMs: number\n}\n\n/** Times guarded synchronous callbacks and reports the ones that block the event loop. */\nexport interface StallMonitor {\n /**\n * Runs `fn` as `extensionId`'s callback and returns its result (or\n * rethrows). When its own run time reaches the threshold, reports a stall\n * against it. Nested runs are attributed to the innermost extension.\n */\n run: <T>(extensionId: string, label: string, fn: () => T) => T\n /** The innermost guarded callback running now, if any. */\n readonly current: { extensionId: string, label: string } | undefined\n}\n\n/** Options for {@link createStallMonitor}. */\nexport interface StallMonitorOptions {\n /** Own run time that counts as a stall, in ms. Default {@link DEFAULT_STALL_THRESHOLD_MS}. */\n thresholdMs?: number\n /** Clock in ms. Default `performance.now`. A test seam. */\n now?: () => number\n /** Receives each stall. Errors it throws are dropped. */\n onStall: (report: StallReport) => void\n}\n\n/**\n * Makes a stall monitor. Share one across every extension of a host so a\n * call from one extension into another is split correctly.\n *\n * @param options - Threshold, clock and the stall sink.\n * @returns The monitor.\n */\nexport function createStallMonitor(options: StallMonitorOptions): StallMonitor {\n const thresholdMs = options.thresholdMs ?? DEFAULT_STALL_THRESHOLD_MS\n const now = options.now ?? (() => performance.now())\n const stack: { extensionId: string, label: string, nested: number }[] = []\n return {\n get current() {\n const top = stack.at(-1)\n return top ? { extensionId: top.extensionId, label: top.label } : undefined\n },\n run(extensionId, label, fn) {\n const frame = { extensionId, label, nested: 0 }\n stack.push(frame)\n const start = now()\n try {\n return fn()\n }\n finally {\n const total = now() - start\n stack.pop()\n const parent = stack.at(-1)\n if (parent)\n parent.nested += total\n const own = total - frame.nested\n if (own >= thresholdMs) {\n try {\n options.onStall({ extensionId, label, durationMs: own })\n }\n catch {}\n }\n }\n },\n }\n}\n\nconst TIMED_OUT = Symbol('timed out')\n\n/** Options for {@link createGuard}. */\nexport interface GuardOptions {\n /** The extension every failure is attributed to. */\n extensionId: string\n /** Where failures, stalls and the trip are logged. */\n logger: Logger\n /** Failures that trip the guard. Default {@link DEFAULT_ERROR_BUDGET}; `false` never trips. */\n budget?: Partial<ErrorBudget> | false\n /** Called once when the budget is spent. The host disables the extension with `trip.reason`. */\n onTrip?: (trip: GuardTrip) => void\n /** Called on every failure, before the budget check. */\n onFailure?: (failure: GuardFailure) => void\n /** Default bound of `call`, in ms. Default {@link DEFAULT_CALLBACK_TIMEOUT_MS}. `Infinity` means none. */\n timeoutMs?: number\n /** A shared stall monitor. Default: a private one that logs stalls as warnings and calls `onStall`. */\n stalls?: StallMonitor\n /** Receives stalls when the guard makes its own monitor. */\n onStall?: (report: StallReport) => void\n /** Clock for the budget window, in ms. Default `Date.now`. A test seam. */\n now?: () => number\n /**\n * Takes a lease on the extension's owner for one call (`RuntimeOwner.lease`):\n * throws `DisposedError` once it is disposed. Absent: calls are not tracked.\n */\n lease?: (label: string, opts: { timeoutMs?: number }) => () => void\n}\n\n/** A {@link Guard} with its budget state. */\nexport interface RuntimeGuard extends Guard {\n /** The extension the guard attributes to. */\n readonly extensionId: string\n /** Set once the budget is spent. A tripped guard no longer runs callbacks: `call` (except `teardown` calls) and `callSync` return their fallback. */\n readonly tripped: GuardTrip | undefined\n /** The failures inside the current window, oldest first. */\n readonly failures: readonly GuardFailure[]\n /** Counts an error the host caught itself (a rejected cleanup, a broken event handler) against the extension. */\n report: (label: string, error: unknown) => void\n}\n\n/**\n * Makes the guard for one extension.\n *\n * @param options - Extension id, logger, budget, timeouts and sinks.\n * @returns The guard.\n */\nexport function createGuard(options: GuardOptions): RuntimeGuard {\n const { extensionId, logger } = options\n const now = options.now ?? Date.now\n const defaultTimeout = options.timeoutMs ?? DEFAULT_CALLBACK_TIMEOUT_MS\n const budget = options.budget === false ? undefined : { ...DEFAULT_ERROR_BUDGET, ...options.budget }\n const stalls = options.stalls ?? createStallMonitor({\n onStall: (report) => {\n logger.warn(`${report.label} blocked the event loop for ${Math.round(report.durationMs)}ms`, { extension: report.extensionId, label: report.label, durationMs: report.durationMs })\n options.onStall?.(report)\n },\n })\n let failures: GuardFailure[] = []\n let tripped: GuardTrip | undefined\n\n const prune = (): void => {\n if (budget)\n failures = failures.filter(f => now() - f.at < budget.windowMs)\n }\n\n const fail = (error: ExtensionCallbackError): void => {\n logger.error(error.message, { extension: extensionId, label: error.label, kind: error.kind, ...(error.cause !== undefined ? { error: errorMessage(error.cause) } : {}) })\n const failure: GuardFailure = { error, at: now() }\n failures.push(failure)\n prune()\n try {\n options.onFailure?.(failure)\n }\n catch {}\n if (!budget || tripped || failures.length < budget.maxFailures)\n return\n const last = error.message.replace(`[${extensionId}] `, '')\n tripped = {\n extensionId,\n reason: `${failures.length} errors in ${Math.round(budget.windowMs / 1000)}s. Last: ${last}`,\n failures: [...failures],\n }\n logger.error(`error budget spent, disabling: ${tripped.reason}`, { extension: extensionId })\n try {\n options.onTrip?.(tripped)\n }\n catch {}\n }\n\n const threw = (label: string, cause: unknown): void => {\n fail(new ExtensionCallbackError(extensionId, label, 'error', errorMessage(cause), cause))\n }\n\n const lease = (label: string, opts: { timeoutMs?: number } = {}): (() => void) =>\n options.lease ? options.lease(`[${extensionId}] ${label}`, opts) : () => {}\n\n /** A lease for a guarded call, or `undefined` when the extension is unloaded (the call does not run). */\n const tryLease = (label: string, timeoutMs?: number): (() => void) | undefined => {\n try {\n return lease(label, timeoutMs !== undefined && Number.isFinite(timeoutMs) ? { timeoutMs } : {})\n }\n catch (error) {\n if (error instanceof DisposedError)\n return undefined\n throw error\n }\n }\n\n return {\n extensionId,\n get tripped() { return tripped },\n get failures() {\n prune()\n return [...failures]\n },\n\n report: threw,\n lease,\n\n async call<T>(label: string, fn: (signal: AbortSignal) => T | Promise<T>, opts: { timeoutMs?: number, fallback?: T, teardown?: boolean } = {}): Promise<T | undefined> {\n if (tripped && !opts.teardown)\n return opts.fallback\n // A teardown call runs while the owner tears down: it holds no lease.\n const release = opts.teardown ? () => {} : tryLease(label, opts.timeoutMs ?? defaultTimeout)\n if (!release)\n return opts.fallback\n try {\n return await runCall(label, fn, opts)\n }\n finally {\n release()\n }\n },\n\n callSync<T>(label: string, fn: () => T, opts: { fallback?: T } = {}): T | undefined {\n if (tripped)\n return opts.fallback\n const release = tryLease(label)\n if (!release)\n return opts.fallback\n let value: T\n try {\n value = stalls.run(extensionId, label, fn)\n }\n catch (error) {\n release()\n threw(label, error)\n return opts.fallback\n }\n if (isThenable(value)) {\n Promise.resolve(value).catch(error => threw(label, error)).finally(release)\n return value\n }\n release()\n return value\n },\n }\n\n async function runCall<T>(label: string, fn: (signal: AbortSignal) => T | Promise<T>, opts: { timeoutMs?: number, fallback?: T }): Promise<T | undefined> {\n const controller = new AbortController()\n let result: T | Promise<T>\n try {\n result = stalls.run(extensionId, label, () => fn(controller.signal))\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n if (!isThenable(result))\n return result\n const pending = Promise.resolve(result)\n const timeoutMs = opts.timeoutMs ?? defaultTimeout\n if (!Number.isFinite(timeoutMs)) {\n try {\n return await pending\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(resolve, timeoutMs, TIMED_OUT)\n })\n try {\n const value = await Promise.race([pending, timedOut])\n if (value !== TIMED_OUT)\n return value\n const message = `timed out after ${timeoutMs}ms`\n controller.abort(new Error(`${label} ${message}`))\n // A late rejection was already accounted for by the timeout.\n pending.catch(() => {})\n fail(new ExtensionCallbackError(extensionId, label, 'timeout', message))\n return opts.fallback\n }\n catch (error) {\n threw(label, error)\n return opts.fallback\n }\n finally {\n clearTimeout(timer)\n }\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof (value as PromiseLike<unknown>).then === 'function'\n}\n","/**\n * The agents catalog: `ctx.agents`. Two sections, agent profiles and\n * spawnable sub-agents, plus the default profile id, all edited by one\n * {@link AgentEditor} per transform.\n */\n\nimport type { AgentProfile } from '../../chat/agents'\nimport type { ExtensionSubagentDef } from '../../tools/spawn'\nimport type { AgentEditor, AgentsDomain, Disposable, ItemOrigin } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** Supplies the base profiles, sub-agents and default. The host connects config and built-ins. */\nexport interface AgentsCatalogPort extends RefreshablePort {\n /** Built-in and config profiles. */\n profiles: () => readonly Sourced<AgentProfile>[]\n /** The host's base sub-agents (the spawn tool's registry). */\n subagents?: () => readonly Sourced<ExtensionSubagentDef>[]\n /** The configured default profile id. */\n defaultId?: () => string | undefined\n}\n\n/** Catalog-wide agent state. */\nexport interface AgentsState {\n /** The default profile id. */\n defaultId?: string\n /** The extension whose transform set the default. */\n defaultSetBy?: string\n}\n\n/** Section item types of the agents catalog. */\nexport interface AgentsSections {\n /** Agent profiles, by `id`. */\n profiles: AgentProfile\n /** Spawnable sub-agents, by `name`. */\n subagents: ExtensionSubagentDef\n}\n\n/** A replayed agents value. `state.defaultId` is cleared when its profile is gone. */\nexport type AgentsValue = CatalogValue<AgentsSections, AgentsState>\n\n/** The shared agents catalog a host builds once. */\nexport interface AgentsCatalog {\n /** The replayed value. */\n read: () => AgentsValue\n /** Adds a profile. */\n registerProfile: (profile: AgentProfile, origin: ItemOrigin) => Disposable\n /** Adds a sub-agent. */\n registerSubagent: (def: ExtensionSubagentDef, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createAgentsEngine>\n}\n\nfunction createAgentsEngine(port: AgentsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<AgentsSections, AgentsState, void>({\n ...options,\n name: 'agents',\n sections: {\n profiles: { key: profile => profile.id, base: () => port.profiles() },\n subagents: { key: def => def.name, base: () => port.subagents?.() ?? [] },\n },\n state: {\n base: () => {\n const defaultId = port.defaultId?.()\n return defaultId === undefined ? {} : { defaultId }\n },\n clone: state => ({ ...state }),\n },\n })\n}\n\n/** Builds the {@link AgentEditor} over one transform's draft. */\nfunction agentEditor(draft: CatalogDraft<AgentsSections, AgentsState, void>): AgentEditor {\n const profiles = draft.sections.profiles\n const subagents = draft.sections.subagents\n return {\n list: profiles.list,\n get: profiles.get,\n origin: profiles.origin,\n add: profiles.add,\n update: profiles.update,\n remove: profiles.remove,\n default: {\n get: () => {\n draft.assertOpen()\n return draft.state.defaultId\n },\n set: (id) => {\n draft.assertOpen()\n if (!profiles.get(id))\n throw new Error(`agents.default.set: no profile \"${id}\"`)\n draft.state = { defaultId: id, defaultSetBy: draft.extensionId }\n },\n },\n subagents: {\n list: subagents.list,\n get: subagents.get,\n origin: subagents.origin,\n add: subagents.add,\n update: subagents.update,\n remove: subagents.remove,\n override: (name, override) => {\n if (typeof override !== 'function')\n throw new TypeError('agents.subagents.override: override must be a function')\n const current = subagents.cloneOf(name)\n let def: Omit<ExtensionSubagentDef, 'name'> | undefined\n if (current) {\n const { name: _name, ...rest } = current\n def = rest\n }\n const next = override(def)\n if (next === undefined)\n subagents.remove(name)\n else\n subagents.replace({ ...next, name })\n },\n },\n }\n}\n\n/** Creates the shared agents catalog. */\nexport function createAgentsCatalog(port: AgentsCatalogPort, options: CatalogOptions = {}): AgentsCatalog {\n const engine = createAgentsEngine(port, options)\n return {\n engine,\n read: () => {\n const value = engine.read()\n const { defaultId } = value.state\n if (defaultId === undefined || value.sections.profiles.get(defaultId))\n return value\n return Object.freeze({ ...value, state: Object.freeze({}) })\n },\n registerProfile: (profile, origin) => engine.register('profiles', profile, origin),\n registerSubagent: (def, origin) => engine.register('subagents', def, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.agents` over the shared catalog. */\nexport function createAgentsDomain(deps: DomainDeps, catalog: AgentsCatalog): AgentsDomain {\n return {\n register(profile) {\n if (!profile || typeof profile.id !== 'string' || profile.id.length === 0)\n throw new TypeError('agents.register: profile needs a non-empty id')\n return owned(deps, 'agents.register', () => catalog.registerProfile(profile, extensionOrigin(deps)))\n },\n subagents: {\n register(def) {\n if (!def || typeof def.name !== 'string' || def.name.length === 0)\n throw new TypeError('agents.subagents.register: def needs a non-empty name')\n return owned(deps, 'agents.subagents.register', () => catalog.registerSubagent(def, extensionOrigin(deps)))\n },\n },\n transform: fn => addTransform(deps, catalog.engine, 'agents.transform', agentEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.profiles.items,\n }\n}\n","/**\n * The MCP server catalog: `ctx.mcp`. Server configs replay like every\n * catalog; connection status and calls go to the host, which connects the\n * replayed configs.\n */\n\nimport type { McpServerConfig } from '../../mcp'\nimport type { CatalogEditor, Disposable, ItemOrigin, McpDomain, McpServerStatus } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** A server status as a host reports it. The catalog fills `url`, `command` and `toolPrefix` the host leaves out. */\nexport type McpPortStatus = Omit<McpServerStatus, 'toolPrefix'> & { toolPrefix?: string }\n\n/**\n * The prefix the agent gives a server's tools: `mcp_<name>_` (the\n * canonical naming of `connectMcpServers`, see `src/agent-mcp-naming.ts`).\n *\n * @param server - The server name as configured.\n * @returns The prefix of its canonical tool names.\n */\nexport function mcpToolPrefix(server: string): string {\n return `mcp_${server}_`\n}\n\n/**\n * A host's status with the catalog's config data: `url` and `command` from\n * the replayed server config when the host gave none, and `toolPrefix`.\n *\n * @param status - What the host reported.\n * @param config - The server's replayed config, when the catalog has it.\n * @returns The status `ctx.mcp.list` reports.\n */\nexport function completeMcpStatus(status: McpPortStatus, config: McpServerConfig | undefined): McpServerStatus {\n const url = status.url ?? config?.url\n const command = status.command ?? config?.command\n return {\n ...status,\n ...(url ? { url } : {}),\n ...(command ? { command } : {}),\n toolPrefix: status.toolPrefix ?? mcpToolPrefix(status.name),\n }\n}\n\n/** Supplies config servers and talks to live connections. Each host implements it. */\nexport interface McpCatalogPort extends RefreshablePort {\n /** Servers from config files and built-ins. */\n servers: () => readonly Sourced<McpServerConfig>[]\n /** Status of every connection the host holds. */\n status: () => readonly McpPortStatus[]\n /** Calls a tool of a connected server. */\n call: (server: string, tool: string, args: Record<string, unknown> | undefined, opts: { timeoutMs?: number, signal?: AbortSignal }) => Promise<{ content: unknown, isError: boolean }>\n}\n\n/** Section item types of the MCP catalog. */\nexport interface McpSections {\n /** Server configs, by `name`. */\n servers: McpServerConfig\n}\n\n/** A replayed MCP value. */\nexport type McpValue = CatalogValue<McpSections, undefined>\n\n/** The shared MCP catalog a host builds once. */\nexport interface McpCatalog {\n /** The replayed server configs. */\n read: () => McpValue\n /** Adds a server config. */\n register: (server: McpServerConfig, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change (the host reconnects). */\n subscribe: (listener: () => void) => () => void\n /** The port, for status and calls. */\n readonly port: McpCatalogPort\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createMcpEngine>\n}\n\nfunction createMcpEngine(port: McpCatalogPort, options: CatalogOptions) {\n return createCatalogSet<McpSections, undefined, void>({\n ...options,\n name: 'mcp',\n sections: { servers: { key: server => server.name, base: () => port.servers() } },\n })\n}\n\n/** Creates the shared MCP catalog. */\nexport function createMcpCatalog(port: McpCatalogPort, options: CatalogOptions = {}): McpCatalog {\n const engine = createMcpEngine(port, options)\n return {\n engine,\n port,\n read: () => engine.read(),\n register: (server, origin) => engine.register('servers', server, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.mcp` over the shared catalog. */\nexport function createMcpDomain(deps: DomainDeps, catalog: McpCatalog): McpDomain {\n return {\n register(server) {\n if (!server || typeof server.name !== 'string' || server.name.length === 0)\n throw new TypeError('mcp.register: server needs a non-empty name')\n return owned(deps, 'mcp.register', () => catalog.register(server, extensionOrigin(deps)))\n },\n transform: fn => addTransform(deps, catalog.engine, 'mcp.transform', (draft): CatalogEditor<McpServerConfig> => {\n const { list, get, origin, add, update, remove } = draft.sections.servers\n return { list, get, origin, add, update, remove }\n }, fn),\n reload: catalog.reload,\n list: () => {\n const servers = catalog.read().sections.servers\n return catalog.port.status().map(status => completeMcpStatus(status, servers.get(status.name)))\n },\n call: (server, tool, args, opts = {}) => catalog.port.call(server, tool, args, opts),\n }\n}\n","/**\n * The skills catalog: `ctx.skills`. Skill configs, plus the set of skills\n * auto-activated at the start of every run (`autoinvoke`). Per-run choices\n * belong to `hooks.intercept('skills.activate')`, not here.\n */\n\nimport type { SkillConfig } from '../../skills'\nimport type { CatalogEditor, Disposable, ItemOrigin, SkillsDomain } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** Supplies discovered skills. The host connects skill discovery and plugins. */\nexport interface SkillsCatalogPort extends RefreshablePort {\n /** Discovered and built-in skills. */\n skills: () => readonly Sourced<SkillConfig>[]\n /** Names auto-activated before any transform (config). */\n autoinvoke?: () => readonly string[]\n}\n\n/** One auto-invoke decision. */\nexport interface AutoinvokeEntry {\n /** On or off. */\n readonly on: boolean\n /** The extension whose transform decided it; absent for the base. */\n readonly by?: string\n}\n\n/** Catalog-wide skill state: auto-invoke decisions by skill name. */\nexport interface SkillsState {\n /** Decisions by skill name. */\n autoinvoke: Record<string, AutoinvokeEntry>\n}\n\n/** Section item types of the skills catalog. */\nexport interface SkillsSections {\n /** Skills, by `name`. */\n skills: SkillConfig\n}\n\n/** A replayed skills value. */\nexport type SkillsValue = CatalogValue<SkillsSections, SkillsState>\n\n/** The editor a skills transform gets. */\nexport type SkillEditor = CatalogEditor<SkillConfig> & { autoinvoke: (name: string, on: boolean) => void }\n\n/** The shared skills catalog a host builds once. */\nexport interface SkillsCatalog {\n /** The replayed value. */\n read: () => SkillsValue\n /** Names of present skills to activate at the start of every run. */\n autoinvoked: () => readonly string[]\n /** Adds a skill. */\n register: (skill: SkillConfig, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createSkillsEngine>\n}\n\nfunction createSkillsEngine(port: SkillsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<SkillsSections, SkillsState, void>({\n ...options,\n name: 'skills',\n sections: { skills: { key: skill => skill.name, base: () => port.skills() } },\n state: {\n base: () => ({ autoinvoke: Object.fromEntries((port.autoinvoke?.() ?? []).map(name => [name, { on: true }])) }),\n clone: state => ({ autoinvoke: { ...state.autoinvoke } }),\n },\n })\n}\n\nfunction skillEditor(draft: CatalogDraft<SkillsSections, SkillsState, void>): SkillEditor {\n const { list, get, origin, add, update, remove } = draft.sections.skills\n return {\n list,\n get,\n origin,\n add,\n update,\n remove,\n autoinvoke: (name, on) => {\n draft.assertOpen()\n draft.state.autoinvoke[name] = { on, by: draft.extensionId }\n },\n }\n}\n\n/** Creates the shared skills catalog. */\nexport function createSkillsCatalog(port: SkillsCatalogPort, options: CatalogOptions = {}): SkillsCatalog {\n const engine = createSkillsEngine(port, options)\n return {\n engine,\n read: () => engine.read(),\n autoinvoked: () => {\n const value = engine.read()\n return Object.entries(value.state.autoinvoke)\n .filter(([name, entry]) => entry.on && value.sections.skills.get(name))\n .map(([name]) => name)\n },\n register: (skill, origin) => engine.register('skills', skill, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.skills` over the shared catalog. */\nexport function createSkillsDomain(deps: DomainDeps, catalog: SkillsCatalog): SkillsDomain {\n return {\n register(skill) {\n if (!skill || typeof skill.name !== 'string' || skill.name.length === 0)\n throw new TypeError('skills.register: skill needs a non-empty name')\n return owned(deps, 'skills.register', () => catalog.register(skill, extensionOrigin(deps)))\n },\n transform: fn => addTransform(deps, catalog.engine, 'skills.transform', skillEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.skills.items,\n }\n}\n","/**\n * The tools catalog: `ctx.tools`. The base is the tool set of the agent\n * being built (built-ins and MCP tools), which differs per session, so a\n * read takes the phase, the session and optionally that base. Extension\n * tools are added after it, then transforms replay with a {@link ToolEditor}.\n */\n\nimport type { ToolResultMetadata } from '../../types'\nimport type { Disposable, ItemOrigin, NamedTool, ToolEditor, ToolMetadataNamespace, ToolsDomain } from '../api'\nimport type { Json } from '../api/storage'\nimport type { DomainDeps, Guard } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogOptions, CatalogValue, SectionValue, Sourced } from './engine'\nimport { clonePlain } from './clone'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet, once } from './engine'\n\n/** What a tools read is for. */\nexport interface ToolCatalogContext {\n /** `'pre-run'` when listing before a run (pickers, Settings), `'run'` when building the run. */\n readonly phase: 'pre-run' | 'run'\n /** The session the tools are for. */\n readonly sessionId?: string\n /** The agent's own tools for this read. Default: the port's base. Reads with a base are not memoized. */\n readonly base?: readonly Sourced<NamedTool>[]\n}\n\n/** Supplies the base tools. The host connects the agent's tool set. */\nexport interface ToolsCatalogPort extends RefreshablePort {\n /** Built-in and MCP tools for a context with no explicit base. */\n base: (context: { phase: 'pre-run' | 'run', sessionId?: string }) => readonly Sourced<NamedTool>[]\n}\n\n/** An extension's tool-result metadata namespace. */\nexport interface ToolMetadataEntry {\n /** The namespace (the key under `ToolResultMetadata`). */\n readonly namespace: string\n /** The extension that owns it. */\n readonly extensionId: string\n /** The spec as registered. Call it through {@link ToolsCatalog.metadata}, which guards it. */\n readonly spec: ToolMetadataNamespace\n}\n\n/** The shared tools catalog a host builds once. */\nexport interface ToolsCatalog {\n /** Replays for a context. Default context: `{ phase: 'pre-run' }`. */\n read: (context?: ToolCatalogContext) => SectionValue<NamedTool> & { readonly failures: CatalogValue<{ tools: NamedTool }, undefined>['failures'] }\n /** Adds an extension's tool. */\n register: (tool: NamedTool, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /** Tool-result metadata namespaces. */\n metadata: {\n /** Every registered namespace. */\n list: () => readonly ToolMetadataEntry[]\n /** Context-panel rows for a namespace, through its extension's guard. */\n contextRows: (namespace: string, entries: readonly { value: Json }[]) => readonly { label: string, value: string }[] | undefined\n /** Compact summary of one value, through its extension's guard. */\n summarize: (namespace: string, metadata: ToolResultMetadata) => Json | undefined\n }\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createToolsEngine>\n /**\n * Registers a metadata namespace for the domain factory.\n *\n * @internal\n */\n registerMetadata: (entry: ToolMetadataEntry, guard: Guard) => Disposable\n}\n\n/**\n * Copies a tool for `update`. Own property descriptors are kept, so getters\n * (live state on the spawn tool) stay live; the spec is deep-copied.\n */\nfunction cloneTool(tool: NamedTool): NamedTool {\n const def = Object.create(Object.getPrototypeOf(tool.def), Object.getOwnPropertyDescriptors(tool.def)) as NamedTool['def']\n def.spec = clonePlain(tool.def.spec)\n return { name: tool.name, def }\n}\n\nfunction createToolsEngine(port: ToolsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<{ tools: NamedTool }, undefined, ToolCatalogContext>({\n ...options,\n name: 'tools',\n sections: {\n tools: {\n key: tool => tool.name,\n base: context => context.base ?? port.base({ phase: context.phase, ...(context.sessionId !== undefined ? { sessionId: context.sessionId } : {}) }),\n clone: cloneTool,\n },\n },\n contextKey: context => context.base ? undefined : `${context.phase}\\u0000${context.sessionId ?? ''}`,\n })\n}\n\n/** Creates the shared tools catalog. */\nexport function createToolsCatalog(port: ToolsCatalogPort, options: CatalogOptions = {}): ToolsCatalog {\n const engine = createToolsEngine(port, options)\n const namespaces = new Map<string, { entry: ToolMetadataEntry, guard: Guard }>()\n return {\n engine,\n read: (context = { phase: 'pre-run' }) => {\n const value = engine.read(context)\n return Object.freeze({ ...value.sections.tools, failures: value.failures })\n },\n register: (tool, origin) => engine.register('tools', tool, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n registerMetadata(entry, guard) {\n const owner = namespaces.get(entry.namespace)\n if (owner && owner.entry.extensionId !== entry.extensionId)\n throw new Error(`tools.metadata: namespace \"${entry.namespace}\" belongs to \"${owner.entry.extensionId}\"`)\n const record = { entry, guard }\n namespaces.set(entry.namespace, record)\n return once(() => {\n if (namespaces.get(entry.namespace) === record)\n namespaces.delete(entry.namespace)\n })\n },\n metadata: {\n list: () => [...namespaces.values()].map(record => record.entry),\n contextRows(namespace, entries) {\n const record = namespaces.get(namespace)\n const fn = record?.entry.spec.contextRows\n if (!record || !fn)\n return undefined\n return record.guard.callSync(`tools.metadata.${namespace}.contextRows`, () => fn({ namespace, entries }))\n },\n summarize(namespace, metadata) {\n const record = namespaces.get(namespace)\n const fn = record?.entry.spec.summarize\n if (!record || !fn)\n return undefined\n return record.guard.callSync(`tools.metadata.${namespace}.summarize`, () => fn(metadata))\n },\n },\n }\n}\n\n/**\n * `def` whose `execute` holds a lease on the extension (`Guard.lease`) while\n * it runs: an agent that took the tool before an unload finishes the call\n * on live domains. A call that starts after the unload throws\n * `DisposedError`. Same prototype and properties, like {@link cloneTool}.\n */\nfunction leasedTool(deps: DomainDeps, name: string, def: NamedTool['def']): NamedTool['def'] {\n const lease = deps.guard.lease\n if (!lease)\n return def\n const execute = def.execute\n const wrapped = Object.create(Object.getPrototypeOf(def), Object.getOwnPropertyDescriptors(def)) as NamedTool['def']\n wrapped.execute = function (this: unknown, ...args: Parameters<typeof execute>) {\n const release = lease(`tool ${name}`)\n let result: ReturnType<typeof execute>\n try {\n result = execute.apply(this, args)\n }\n catch (error) {\n release()\n throw error\n }\n if (result && typeof (result as PromiseLike<unknown>).then === 'function')\n return (result as Promise<Awaited<typeof result>>).finally(release) as typeof result\n release()\n return result\n }\n return wrapped\n}\n\n/** Creates one extension's `ctx.tools` over the shared catalog. */\nexport function createToolsDomain(deps: DomainDeps, catalog: ToolsCatalog): ToolsDomain {\n return {\n register(name, def) {\n if (typeof name !== 'string' || name.length === 0)\n throw new TypeError('tools.register: name must be a non-empty string')\n if (!def || typeof def.execute !== 'function')\n throw new TypeError(`tools.register: \"${name}\" needs a ToolDef with execute`)\n return owned(deps, 'tools.register', () => catalog.register({ name, def: leasedTool(deps, name, def) }, extensionOrigin(deps)))\n },\n metadata(namespace, spec) {\n if (typeof namespace !== 'string' || namespace.length === 0)\n throw new TypeError('tools.metadata: namespace must be a non-empty string')\n return owned(deps, 'tools.metadata', () => catalog.registerMetadata({ namespace, extensionId: deps.extensionId, spec }, deps.guard))\n },\n transform: fn => addTransform(deps, catalog.engine, 'tools.transform', (draft): ToolEditor => {\n const tools = draft.sections.tools\n return {\n phase: draft.context.phase,\n ...(draft.context.sessionId !== undefined ? { sessionId: draft.context.sessionId } : {}),\n list: tools.list,\n get: tools.get,\n origin: tools.origin,\n add: tools.add,\n update: tools.update,\n remove: tools.remove,\n }\n }, fn),\n reload: catalog.reload,\n list: () => catalog.read().items,\n }\n}\n","/**\n * `ctx.contracts`: provide and use contracts, add to and list registries.\n * A per-extension view over the process-wide {@link ContractRegistry}.\n * Everything registered or subscribed through it ends with the owner.\n */\n\nimport type { ContractsDomain, ContractToken, RegistryToken } from '../api/contracts'\nimport type { Disposable, LiveAccessor, Readable } from '../api/core'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { ContractRegistry } from './registry'\nimport { DisposedError } from '../api/core'\nimport { assertOwnsId } from './ids'\nimport { bindToOwner } from './owned'\n\n/**\n * Creates the contracts domain of one extension (or one scope of it).\n *\n * @param deps - Extension id, owner, guard and logger.\n * @param registry - The process-wide store, from `createContractRegistry`.\n * @returns `ctx.contracts`.\n */\nexport function createContractsDomain(deps: DomainDeps, registry: ContractRegistry): ContractsDomain {\n const { extensionId, owner, guard } = deps\n const accessors = new Map<string, LiveAccessor<unknown>>()\n const lists = new Map<string, Readable<readonly unknown[]>>()\n\n function live(what: string): void {\n if (owner.disposed)\n throw new DisposedError(what)\n }\n\n const owned = (dispose: () => void): Disposable => bindToOwner(owner, dispose)\n\n function guardedSubscribe<T>(what: string, watch: (listener: (value: T) => void) => () => void, listener: (value: T) => void): () => void {\n live(what)\n const sub = owned(watch(value => guard.callSync(what, () => listener(value))))\n return () => sub.dispose()\n }\n\n return {\n provide<T>(token: ContractToken<T>, impl: T): Disposable {\n live('contracts.provide')\n assertOwnsId('contracts.provide', extensionId, token.id)\n const provision = registry.provide(token.id, extensionId, impl)\n return owned(() => provision.dispose())\n },\n use<T>(token: ContractToken<T>): LiveAccessor<T> {\n let accessor = accessors.get(token.id)\n if (!accessor) {\n const id = token.id\n accessor = {\n get: () => registry.live(id),\n value: () => {\n const current = registry.live(id)\n return current.status === 'active' ? current.value : undefined\n },\n subscribe: listener => guardedSubscribe(`contracts.use(${id})`, l => registry.watch(id, l), listener),\n }\n accessors.set(id, accessor)\n }\n return accessor as LiveAccessor<T>\n },\n add<T>(token: RegistryToken<T>, item: T): Disposable {\n live('contracts.add')\n const entry = registry.add(token.id, extensionId, item)\n return owned(() => entry.dispose())\n },\n list<T>(token: RegistryToken<T>): Readable<readonly T[]> {\n assertOwnsId('contracts.list', extensionId, token.id)\n let list = lists.get(token.id)\n if (!list) {\n const id = token.id\n list = {\n get: () => registry.items(id),\n subscribe: listener => guardedSubscribe(`contracts.list(${id})`, l => registry.watchItems(id, l), listener),\n }\n lists.set(id, list)\n }\n return list as Readable<readonly T[]>\n },\n }\n}\n","/**\n * The process-wide store behind `ctx.contracts`: who provides each\n * contract, and what each registry holds. One per host process; every\n * extension's contracts domain reads and writes it.\n *\n * A contract id holds a stack of provisions. The newest is active; when it\n * goes, the one below it (an older instance of the same extension still\n * unloading) becomes active again. Every change of the active provision\n * bumps the id's generation, so a consumer can tell a reload from no change.\n */\n\nimport type { Disposable, Live } from '../api/core'\n\n/** Options of {@link createContractRegistry}. */\nexport interface ContractRegistryOptions {\n /**\n * Position of an extension in load order (lower loads first). Registry\n * items are listed by it. Extensions it doesn't know (`undefined`) come\n * after the known ones, in the order they first added an item.\n */\n loadOrder?: (extensionId: string) => number | undefined\n}\n\n/** The process-wide contract and registry store. */\nexport interface ContractRegistry {\n /** Makes `impl` the active provision of contract `id`. Ownership is checked by the caller. */\n provide: (id: string, extensionId: string, impl: unknown) => Disposable\n /** The current state of contract `id`. The same object until it changes. */\n live: (id: string) => Live<unknown>\n /** Calls `listener` after each change of contract `id`. Returns the unsubscribe. */\n watch: (id: string, listener: (live: Live<unknown>) => void) => () => void\n /** Adds `item` to registry `id` on behalf of `extensionId`. */\n add: (id: string, extensionId: string, item: unknown) => Disposable\n /** Items of registry `id` in load order. The same array until it changes. */\n items: (id: string) => readonly unknown[]\n /** Calls `listener` after each change of registry `id`. Returns the unsubscribe. */\n watchItems: (id: string, listener: (items: readonly unknown[]) => void) => () => void\n}\n\ninterface Provision { extensionId: string, impl: unknown }\ninterface ContractState {\n stack: Provision[]\n generation: number\n live: Live<unknown>\n listeners: Set<(live: Live<unknown>) => void>\n}\ninterface Item { extensionId: string, item: unknown, seq: number }\ninterface RegistryState {\n entries: Item[]\n view: readonly unknown[]\n listeners: Set<(items: readonly unknown[]) => void>\n}\n\nconst PENDING: Live<unknown> = Object.freeze({ status: 'pending' })\nconst EMPTY: readonly unknown[] = Object.freeze([])\n\nfunction notify<T>(listeners: Set<(value: T) => void>, value: T): void {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n }\n catch {\n // Listeners are guarded by the domain; one failing never stops the rest.\n }\n }\n}\n\n/**\n * Creates an empty contract and registry store.\n *\n * @param options - Load order for registry listing.\n * @returns The store, shared by every extension's contracts domain.\n */\nexport function createContractRegistry(options: ContractRegistryOptions = {}): ContractRegistry {\n const contracts = new Map<string, ContractState>()\n const registries = new Map<string, RegistryState>()\n const firstSeen = new Map<string, number>()\n let seq = 0\n\n function contract(id: string): ContractState {\n let state = contracts.get(id)\n if (!state) {\n state = { stack: [], generation: 0, live: PENDING, listeners: new Set() }\n contracts.set(id, state)\n }\n return state\n }\n\n function registry(id: string): RegistryState {\n let state = registries.get(id)\n if (!state) {\n state = { entries: [], view: EMPTY, listeners: new Set() }\n registries.set(id, state)\n }\n return state\n }\n\n function rank(extensionId: string): [number, number] {\n const order = options.loadOrder?.(extensionId)\n return order === undefined ? [1, firstSeen.get(extensionId) ?? 0] : [0, order]\n }\n\n function rebuild(state: RegistryState): void {\n const sorted = [...state.entries].sort((a, b) => {\n const [ka, oa] = rank(a.extensionId)\n const [kb, ob] = rank(b.extensionId)\n return ka - kb || oa - ob || a.seq - b.seq\n })\n state.view = Object.freeze(sorted.map(entry => entry.item))\n notify(state.listeners, state.view)\n }\n\n return {\n provide(id, extensionId, impl) {\n const state = contract(id)\n const provision: Provision = { extensionId, impl }\n state.stack.push(provision)\n state.generation++\n state.live = Object.freeze({ status: 'active', value: impl, generation: state.generation })\n notify(state.listeners, state.live)\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n const index = state.stack.indexOf(provision)\n const wasActive = index === state.stack.length - 1\n state.stack.splice(index, 1)\n if (!wasActive)\n return\n const next = state.stack.at(-1)\n if (next) {\n state.generation++\n state.live = Object.freeze({ status: 'active', value: next.impl, generation: state.generation })\n }\n else {\n state.live = Object.freeze({ status: 'inactive', reason: `${extensionId} withdrew \"${id}\"` })\n }\n notify(state.listeners, state.live)\n },\n }\n },\n live: id => contracts.get(id)?.live ?? PENDING,\n watch(id, listener) {\n const { listeners } = contract(id)\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n add(id, extensionId, item) {\n if (!firstSeen.has(extensionId))\n firstSeen.set(extensionId, firstSeen.size)\n const state = registry(id)\n const entry: Item = { extensionId, item, seq: seq++ }\n state.entries.push(entry)\n rebuild(state)\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n state.entries.splice(state.entries.indexOf(entry), 1)\n rebuild(state)\n },\n }\n },\n items: id => registries.get(id)?.view ?? EMPTY,\n watchItems(id, listener) {\n const { listeners } = registry(id)\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n }\n}\n","/**\n * `ctx.artifacts` (extension API): artifact kinds, plus list / find /\n * record over the host runtime bridge's artifacts facade. A kind is checked\n * as `registerArtifactKind` checks it; its callbacks run through the guard.\n */\n\nimport type { SessionArtifact } from '../../../session/artifacts'\nimport type { ArtifactsDomain } from '../../api/sessions'\nimport type { ExtensionArtifactKindRegistration } from '../../types'\nimport type { DomainDeps } from '../deps'\nimport type { ArtifactsPort } from './ports'\nimport { ARTIFACT_KIND_PATTERN } from '../../../session/artifacts'\nimport { createArtifactDetectHook } from '../../artifact-detect'\nimport { createArtifactsSurface } from '../../host-runtime'\nimport { assertAlive, assertUsable, track } from '../owner'\n\nconst CALLBACKS = ['detect', 'validateMeta', 'render', 'resolve', 'badge'] as const\n\n/** Throws a TypeError naming what is wrong with `registration`. */\nfunction checkKind(registration: ExtensionArtifactKindRegistration): void {\n if (!registration || typeof registration.kind !== 'string' || !ARTIFACT_KIND_PATTERN.test(registration.kind))\n throw new TypeError('artifacts.kinds.register: kind must match [\\\\w.:-]+')\n if (typeof registration.label !== 'string' || !registration.label)\n throw new TypeError(`artifacts.kinds.register: kind \"${registration.kind}\" needs a label`)\n for (const fn of CALLBACKS) {\n if (registration[fn] !== undefined && typeof registration[fn] !== 'function')\n throw new TypeError(`artifacts.kinds.register: ${fn} of kind \"${registration.kind}\" must be a function`)\n }\n}\n\n/** A copy of `registration` whose callbacks run through the guard: a throw or a timeout is attributed and turns into \"nothing\". */\nfunction guarded(deps: DomainDeps, registration: ExtensionArtifactKindRegistration): ExtensionArtifactKindRegistration {\n const { guard } = deps\n const { kind, detect, validateMeta, render, resolve, badge } = registration\n const label = (fn: string): string => `artifacts.kind(${kind}).${fn}`\n return {\n ...registration,\n ...(detect ? { detect: async outcome => guard.call(label('detect'), () => detect(outcome)) } : {}),\n ...(validateMeta ? { validateMeta: meta => guard.callSync(label('validateMeta'), () => validateMeta(meta), { fallback: false }) ?? false } : {}),\n ...(render ? { render: (artifact: SessionArtifact) => guard.callSync(label('render'), () => render(artifact)) } : {}),\n ...(resolve ? { resolve: async (artifact, opts) => guard.call(label('resolve'), () => resolve(artifact, opts)) } : {}),\n ...(badge ? { badge: artifacts => guard.callSync(label('badge'), () => badge(artifacts)) } : {}),\n }\n}\n\n/**\n * Creates one extension's `ctx.artifacts`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's artifact scope and kind registry.\n * @returns The domain. Calls throw (or reject) with `DisposedError` once the owner is disposed.\n */\nexport function createArtifactsDomain(deps: DomainDeps, port: ArtifactsPort): ArtifactsDomain {\n const { extensionId, owner, logger } = deps\n const surface = createArtifactsSurface(() => port.current()?.artifacts?.() ?? null)\n return {\n kinds: {\n register(registration) {\n assertAlive(owner, 'artifacts.kinds.register')\n checkKind(registration)\n if (!port.registerKind)\n throw new Error(`artifacts.kinds.register: this host does not support artifact kinds (extension \"${extensionId}\").`)\n const safe = guarded(deps, registration)\n const detect = createArtifactDetectHook(safe, { warn: (message, fields) => logger.warn(message, fields) })\n return track(owner, port.registerKind({ extensionId, registration: safe, ...(detect ? { detect } : {}) }))\n },\n },\n list: async (query) => {\n assertUsable(owner, 'artifacts.list')\n return surface.list(query)\n },\n // The store answers newest first: the most recently updated match.\n find: async (kind, uri) => {\n assertUsable(owner, 'artifacts.find')\n return (await surface.find(kind, uri))[0]\n },\n record: async (input) => {\n assertUsable(owner, 'artifacts.record')\n return surface.record(input)\n },\n }\n}\n","/**\n * `ctx.generate` (extension API): model calls outside any session. The\n * host resolves the provider (the user's credentials and default model) and\n * counts usage; `object` reuses the schema-pinned side-channel call behind\n * the chat commands' `ctx.generateData`, `decide` the decisions model, and\n * `image` the host's image port (the generate_image tool's models).\n */\n\nimport type { AgentDecide, DecisionOutcome, DecisionQuestions, DecisionRequest } from '../../../decisions/types'\nimport type { Provider } from '../../../providers'\nimport type { TurnUsage } from '../../../types'\nimport type { GenerateDomain, GenerateImageOptions } from '../../api/sessions'\nimport type { DomainDeps } from '../deps'\nimport type { GenerateImageReference, GenerateImageRequest, GenerateModelRef, GeneratePort, ResolvedGenerateModel } from './ports'\nimport { createHooks } from 'hookable'\nimport { generateStructuredData } from '../../../chat/generate-data'\nimport { createDecider } from '../../../decisions'\nimport { currentRunDecide } from '../../../decisions/run-scope'\nimport { IMAGE_ASPECT_RATIOS, MAX_IMAGES_PER_REQUEST } from '../../../providers/images'\nimport { validateStoreValue } from '../../storage/validate'\nimport { assertUsable, isTornDown } from '../owner'\n\n/**\n * Wraps `provider` so each `stream` call that returns reports its usage.\n * Other members forward to the original, bound to it (class providers keep\n * their private state).\n */\nfunction counting(provider: Provider, onUsage: (usage: TurnUsage) => void): Provider {\n const stream: Provider['stream'] = async (options, callbacks) => {\n const result = await provider.stream(options, callbacks)\n onUsage(result.usage)\n return result\n }\n return new Proxy(provider, {\n get(target, prop) {\n if (prop === 'stream')\n return stream\n const value = Reflect.get(target, prop, target) as unknown\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value\n },\n })\n}\n\n/** Most reference images one `generate.image` call takes, as the generate_image tool. */\nexport const MAX_IMAGE_REFERENCES = 8\n\n/** Largest prompt `generate.image` takes, in characters. */\nconst MAX_IMAGE_PROMPT = 32_000\n\n/**\n * Checks `ctx.generate.image` options (an extension's input) and builds the\n * host request. Throws a `TypeError` naming the first problem.\n *\n * @param extensionId - The calling extension.\n * @param opts - The options as passed.\n * @param signal - The combined owner and caller signal.\n */\nexport function imageRequest(extensionId: string, opts: GenerateImageOptions, signal: AbortSignal): GenerateImageRequest {\n if (!opts || typeof opts.prompt !== 'string' || !opts.prompt.trim() || opts.prompt.length > MAX_IMAGE_PROMPT)\n throw new TypeError(`generate.image: prompt must be a non-empty string of at most ${MAX_IMAGE_PROMPT} characters`)\n const n = opts.n ?? 1\n if (!Number.isInteger(n) || n < 1 || n > MAX_IMAGES_PER_REQUEST)\n throw new TypeError(`generate.image: n must be an integer from 1 to ${MAX_IMAGES_PER_REQUEST}`)\n if (opts.aspectRatio !== undefined && !(IMAGE_ASPECT_RATIOS as readonly string[]).includes(opts.aspectRatio))\n throw new TypeError(`generate.image: aspectRatio must be one of ${IMAGE_ASPECT_RATIOS.join(', ')}`)\n const model = opts.model\n if (model !== undefined && (typeof model?.providerId !== 'string' || typeof model.modelId !== 'string' || !model.providerId || !model.modelId))\n throw new TypeError('generate.image: model must be { providerId, modelId }')\n const references = opts.references ?? []\n if (!Array.isArray(references) || references.length > MAX_IMAGE_REFERENCES)\n throw new TypeError(`generate.image: references must be a list of at most ${MAX_IMAGE_REFERENCES}`)\n const refs = references.map((ref, i): GenerateImageReference => {\n if (ref && typeof (ref as { path?: unknown }).path === 'string' && (ref as { path: string }).path)\n return { path: (ref as { path: string }).path }\n const bytes = ref as { mimeType?: unknown, data?: unknown }\n if (bytes && typeof bytes.mimeType === 'string' && bytes.mimeType.startsWith('image/') && bytes.data instanceof Uint8Array)\n return { mimeType: bytes.mimeType, data: bytes.data }\n throw new TypeError(`generate.image: references[${i}] must be { path } or { mimeType: 'image/…', data: Uint8Array }`)\n })\n const save = opts.save === true\n ? {}\n : opts.save && typeof opts.save === 'object'\n ? (typeof opts.save.sessionId === 'string' && opts.save.sessionId ? { sessionId: opts.save.sessionId } : {})\n : undefined\n return {\n extensionId,\n prompt: opts.prompt.trim(),\n ...(model ? { model: { providerId: model.providerId, modelId: model.modelId } } : {}),\n n,\n ...(opts.aspectRatio !== undefined ? { aspectRatio: opts.aspectRatio } : {}),\n references: refs,\n ...(save ? { save } : {}),\n signal,\n }\n}\n\n/** The owner's signal, combined with the caller's when given. */\nfunction combined(owner: AbortSignal, signal: AbortSignal | undefined): AbortSignal {\n return signal ? AbortSignal.any([signal, owner]) : owner\n}\n\n/**\n * Creates one extension's `ctx.generate`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's provider resolution, usage counter and decisions model.\n * @returns The domain. Calls reject with `DisposedError` once the owner is disposed, and abort with it.\n */\nexport function createGenerateDomain(deps: DomainDeps, port: GeneratePort): GenerateDomain {\n const { extensionId, owner } = deps\n // Answers `unavailable` (or throws DecisionUnavailableError with `{ throw: true }`) when the host has no decisions model.\n let unavailable: AgentDecide | undefined\n // Inside a hook observer of a run: that run's decider, so the decision is\n // stamped, cancelled and (in a replay run) journaled like the agent's own.\n const decider = (): AgentDecide => currentRunDecide() ?? port.decide ?? (unavailable ??= createDecider({ providers: [], config: undefined, hooks: createHooks() }).forRun(undefined))\n\n const resolve = async (method: 'text' | 'object', model: GenerateModelRef | undefined): Promise<ResolvedGenerateModel & { counted: Provider }> => {\n assertUsable(owner, `generate.${method}`)\n const resolved = await port.resolve(model)\n assertUsable(owner, `generate.${method}`)\n const counted = counting(resolved.provider, (usage) => {\n try {\n port.recordUsage?.({ extensionId, method, providerId: resolved.providerId, modelId: resolved.modelId, usage })\n }\n catch (error) {\n deps.logger.warn('generate: recording usage failed', { error: error instanceof Error ? error.message : String(error) })\n }\n })\n return { ...resolved, counted }\n }\n\n const decide = ((request: DecisionRequest<DecisionQuestions>, options?: { throw: true }): Promise<DecisionOutcome<DecisionQuestions>> => {\n assertUsable(owner, 'generate.decide')\n const scoped = { ...request, signal: combined(owner.signal, request.signal) }\n return options ? decider()(scoped, options) : decider()(scoped)\n }) as AgentDecide\n Object.defineProperty(decide, 'available', { get: () => !isTornDown(owner) && decider().available })\n\n return {\n async text(opts) {\n const { counted, modelId } = await resolve('text', opts.model)\n const result = await counted.stream(\n {\n model: modelId,\n system: opts.system ?? '',\n tools: [],\n messages: [counted.userMessage(opts.prompt)],\n signal: combined(owner.signal, opts.signal),\n },\n { onText: () => {} },\n )\n return result.text\n },\n async object(opts) {\n const { counted, modelId } = await resolve('object', opts.model)\n const payload = await generateStructuredData<unknown>({\n provider: counted,\n model: modelId,\n prompt: opts.prompt,\n schema: opts.schema,\n ...(opts.system !== undefined ? { system: opts.system } : {}),\n signal: combined(owner.signal, opts.signal),\n })\n // The model's answer is untrusted: check it against the schema (and take its parsed value).\n const checked = await validateStoreValue(opts.schema, payload)\n if (!checked.ok)\n throw new Error(`generate.object: the model's answer does not match the schema: ${checked.error}`)\n return checked.value as never\n },\n decide,\n async image(opts) {\n assertUsable(owner, 'generate.image')\n const request = imageRequest(extensionId, opts, combined(owner.signal, opts?.signal))\n if (!port.image)\n throw new Error('generate.image: this host cannot generate images')\n const result = await port.image(request)\n assertUsable(owner, 'generate.image')\n try {\n port.recordUsage?.({ extensionId, method: 'image', providerId: result.providerId, modelId: result.modelId, usage: { input: 0, output: 0, ...(result.costUsd !== undefined ? { cost: result.costUsd } : {}) } })\n }\n catch (error) {\n deps.logger.warn('generate: recording usage failed', { error: error instanceof Error ? error.message : String(error) })\n }\n return { images: result.images }\n },\n }\n}\n","/**\n * `ctx.instructions` (extension API): text extensions add to the system\n * prompt. An entry without a session applies to every session (like a\n * registry system prompt fragment); a session entry applies to that session only. A\n * `key` replaces the extension's earlier entry with the same key and\n * session, in place. Entries belong to the owner they were added through.\n */\n\nimport type { Disposable, InstructionsDomain } from '../../api'\nimport type { DomainDeps } from '../deps'\nimport type { InstructionsRegistry } from '../outputs'\nimport { track } from '../owner'\n\n/** Options of {@link createInstructionsRegistry}. */\nexport interface InstructionsRegistryOptions {\n /** Load-order rank of an extension (lower first). Read on every `list`. Default: registration order only. */\n order?: (extensionId: string) => number\n}\n\ninterface Entry {\n readonly extensionId: string\n readonly sessionId?: string\n readonly slot?: string\n text: string\n seq: number\n /** Drops the owner link once the entry is gone. */\n unlink?: () => void\n}\n\n/**\n * Creates the shared instructions registry the agent reads, with the factory\n * of each extension's `ctx.instructions`.\n *\n * @param options - Load order.\n * @returns The registry, plus `domain(deps)` to make one extension's domain.\n */\nexport function createInstructionsRegistry(options: InstructionsRegistryOptions = {}): InstructionsRegistry & { domain: (deps: DomainDeps) => InstructionsDomain } {\n const entries = new Set<Entry>()\n const bySlot = new Map<string, Entry>()\n const listeners = new Set<() => void>()\n let nextSeq = 0\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n }\n catch {}\n }\n }\n\n const remove = (entry: Entry): void => {\n if (!entries.delete(entry))\n return\n if (entry.slot !== undefined && bySlot.get(entry.slot) === entry)\n bySlot.delete(entry.slot)\n entry.unlink?.()\n notify()\n }\n\n const sorted = (list: Entry[]): Entry[] => {\n const rank = options.order\n return list.sort((a, b) => (rank ? rank(a.extensionId) - rank(b.extensionId) : 0) || a.seq - b.seq)\n }\n\n return {\n list: (sessionId) => {\n const all = [...entries]\n const global = sorted(all.filter(entry => entry.sessionId === undefined))\n const scoped = sessionId === undefined ? [] : sorted(all.filter(entry => entry.sessionId === sessionId))\n return [...global, ...scoped].map(entry => entry.text)\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n domain: (deps: DomainDeps): InstructionsDomain => ({\n add(text, opts = {}): Disposable {\n if (typeof text !== 'string')\n throw new TypeError('instructions.add: text must be a string')\n if (opts.sessionId !== undefined && (typeof opts.sessionId !== 'string' || opts.sessionId.length === 0))\n throw new TypeError('instructions.add: sessionId must be a non-empty string')\n if (opts.key !== undefined && (typeof opts.key !== 'string' || opts.key.length === 0))\n throw new TypeError('instructions.add: key must be a non-empty string')\n const slot = opts.key === undefined ? undefined : JSON.stringify([deps.extensionId, opts.sessionId ?? null, opts.key])\n const previous = slot === undefined ? undefined : bySlot.get(slot)\n const entry: Entry = {\n extensionId: deps.extensionId,\n ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),\n ...(slot !== undefined ? { slot } : {}),\n text,\n // A replacement keeps the place of the entry it replaces.\n seq: previous?.seq ?? nextSeq++,\n }\n // Throws DisposedError (and adds nothing) once the owner is disposed.\n const handle = track(deps.owner, { dispose: () => remove(entry) })\n entry.unlink = handle.dispose\n if (previous) {\n entries.delete(previous)\n previous.unlink?.()\n }\n entries.add(entry)\n if (slot !== undefined)\n bySlot.set(slot, entry)\n notify()\n return handle\n },\n }),\n }\n}\n","/**\n * `ctx.plugins` (extension API): loads an Agent Plugin folder with the\n * plugin loader (`loadAgentPlugin`) and registers its skills and MCP servers through the catalogs.\n * The returned plugin is a Disposable that withdraws them; it is also\n * withdrawn with the owner it was loaded through.\n */\n\nimport type { LoadedPlugin } from '../../../plugins'\nimport type { SkillSource } from '../../../skills'\nimport type { PluginsDomain } from '../../api/catalogs'\nimport type { Disposable, ExtensionSource } from '../../api/core'\nimport type { DomainDeps } from '../deps'\nimport type { PluginsPort } from './ports'\nimport { basename, isAbsolute, resolve } from 'node:path'\nimport { loadAgentPlugin } from '../../../plugins'\nimport { DisposedError } from '../../api/core'\nimport { withProvenance } from '../../shared'\nimport { resolveStoragePath } from '../../storage/paths'\nimport { assertAlive, track } from '../owner'\n\n/** The skill source a plugin's skills inherit: the extension's scope (config-installed extensions are user-level). */\nfunction skillSource(source: ExtensionSource): SkillSource {\n return source === 'config' ? 'user' : source\n}\n\n/**\n * Creates one extension's `ctx.plugins`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The extension's location and the catalog registration functions.\n * @returns The domain. `load` rejects with `DisposedError` when the owner is disposed before or during the load.\n */\nexport function createPluginsDomain(deps: DomainDeps, port: PluginsPort): PluginsDomain {\n const { extensionId, owner, logger } = deps\n return {\n async load(spec) {\n assertAlive(owner, 'plugins.load')\n const options = typeof spec === 'string' ? { dir: spec } : spec\n const requested = options?.dir\n if (typeof requested !== 'string' || requested.length === 0)\n throw new TypeError('plugins.load: dir must be a non-empty string')\n const extension = port.extension(extensionId)\n if (!extension)\n throw new Error(`plugins.load: the host does not know extension \"${extensionId}\".`)\n\n // Relative specs resolve against the extension's folder (vendored plugins); inline extensions use the cwd.\n const target = isAbsolute(requested) ? requested : resolve(extension.dir ?? extension.paths.cwd, requested)\n const source = skillSource(extension.source)\n const loaded = await loadAgentPlugin(target, {\n source,\n // `${PLUGIN_DATA}` lives in the loading extension's storage root.\n dataRoot: extension.storagePath?.('data', 'plugin-data')\n ?? resolveStoragePath({ paths: extension.paths, extensionId, ...(extension.dir !== undefined ? { dir: extension.dir } : {}), logger }, 'data', 'plugin-data'),\n ...(options.skills !== undefined ? { skills: options.skills } : {}),\n ...(options.mcp !== undefined ? { mcp: options.mcp } : {}),\n ...(options.namePrefix !== undefined ? { namePrefix: options.namePrefix } : {}),\n })\n\n // Diagnostics are logged, never thrown: a bad package must not fail the extension that loaded it.\n for (const diagnostic of loaded.diagnostics) {\n const detail = { plugin: loaded.manifest?.name ?? target, code: diagnostic.code, ...(diagnostic.path ? { path: diagnostic.path } : {}) }\n if (diagnostic.severity === 'error')\n logger.error(`plugins.load: ${diagnostic.message}`, detail)\n else\n logger.warn(`plugins.load: ${diagnostic.message}`, detail)\n }\n if (owner.disposed)\n throw new DisposedError('plugins.load')\n\n const origin = { kind: 'extension', id: extensionId } as const\n const parts: Disposable[] = []\n const withdraw = (): void => {\n for (const part of parts.splice(0).reverse()) {\n try {\n part.dispose()\n }\n catch (error) {\n logger.warn('plugins.load: withdrawing a registration failed', { error: error instanceof Error ? error.message : String(error) })\n }\n }\n }\n try {\n if (loaded.ok) {\n for (const skill of loaded.skills)\n parts.push(port.registerSkill(withProvenance(skill, source, extensionId), origin))\n for (const server of loaded.mcpServers)\n parts.push(port.registerMcpServer(server, origin))\n }\n // A rejected plugin is recorded too: \"the plugin is broken\" beats it silently missing.\n if (port.recordPlugin)\n parts.push(port.recordPlugin({ name: loaded.manifest?.name ?? basename(target), extensionName: extensionId, dir: target, plugin: loaded }))\n }\n catch (error) {\n withdraw()\n throw error\n }\n const handle = track(owner, { dispose: withdraw })\n logger.debug('plugins.load: registered', { plugin: loaded.manifest?.name, skills: loaded.skills.length, mcpServers: loaded.mcpServers.length })\n return Object.assign(loaded, { dispose: handle.dispose }) as LoadedPlugin & Disposable\n },\n }\n}\n","/**\n * `ctx.workspace` (extension API): the host runtime bridge's workspace facade, owner-checked.\n * Shell and file operations run in the session's execution context, resolved\n * live on every call; detached calls reject.\n */\n\nimport type { WorkspaceDomain } from '../../api/sessions'\nimport type { DomainDeps } from '../deps'\nimport type { WorkspacePort } from './ports'\nimport { createWorkspaceSurface } from '../../host-runtime'\nimport { assertUsable } from '../owner'\n\n/**\n * Creates one extension's `ctx.workspace`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's live runtime implementation.\n * @returns The domain. Every call rejects with `DisposedError` once the owner is disposed; `exec` aborts with it.\n */\nexport function createWorkspaceDomain(deps: DomainDeps, port: WorkspacePort): WorkspaceDomain {\n const { owner } = deps\n const surface = createWorkspaceSurface(\n async () => await port.current()?.workspace?.() ?? null,\n () => port.current()?.workspaceAvailable?.(),\n )\n return {\n available: async () => {\n assertUsable(owner, 'workspace.available')\n return surface.available()\n },\n exec: async (command, options = {}) => {\n assertUsable(owner, 'workspace.exec')\n const signal = options.signal ? AbortSignal.any([options.signal, owner.signal]) : owner.signal\n return surface.exec(command, { ...options, signal })\n },\n readFile: async (path) => {\n assertUsable(owner, 'workspace.readFile')\n return surface.readFile(path)\n },\n writeFile: async (path, content) => {\n assertUsable(owner, 'workspace.writeFile')\n return surface.writeFile(path, content)\n },\n listFiles: async (path, options) => {\n assertUsable(owner, 'workspace.listFiles')\n return surface.listFiles(path, options)\n },\n fileSize: async (path) => {\n assertUsable(owner, 'workspace.fileSize')\n return surface.fileSize(path)\n },\n }\n}\n","/**\n * Builds the {@link ExtensionContext} of one extension from the domain\n * factories (extension API).\n *\n * Every domain gets {@link DomainDeps} bound to one owner: the extension's\n * root owner, or a child made by `ctx.scope()`. A scope rebuilds the domain\n * views on its child owner, so disposing the scope withdraws exactly what\n * was registered through it. Storage and settings keep one cache per\n * extension; a scope wraps them so its subscriptions end with the scope.\n */\n\nimport type { AgentDecide } from '../../decisions/types'\nimport type { Logger } from '../../logger'\nimport type { InstructionsDomain } from '../api/catalogs'\nimport type { ExtensionContext, ExtensionInfo } from '../api/context'\nimport type { AppInfo, Disposable, ExtensionPaths, ExtensionSource } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { SessionFacetsDomain, SessionsDomain } from '../api/sessions'\nimport type { SettingsDomain, SettingsSchema } from '../api/settings'\nimport type { KeyValue, StorageDomain, Store } from '../api/storage'\nimport type { DesktopDomain } from '../api/ui'\nimport type { AgentsCatalog, McpCatalog, ModelsCatalog, ProvidersCatalog, SkillsCatalog, ToolsCatalog } from '../catalog'\nimport type { CommandRegistry } from '../commands'\nimport type { ContractRegistry } from '../contracts'\nimport type { HooksPort, InterceptorRegistry } from '../hooks'\nimport type { IntegrationFlowPort, IntegrationRegistry } from '../integrations'\nimport type { RpcRouter } from '../rpc'\nimport type { SettingsDomainInstance } from '../settings'\nimport type { StorageRuntime } from '../storage'\nimport type { DialogRouter, UiClientPort, UiRegistry } from '../ui'\nimport type { DomainDeps, Guard } from './deps'\nimport type { HostRuntimePorts } from './domains'\nimport type { FacetsRuntime } from './facets'\nimport type { InstructionsRegistry } from './outputs'\nimport type { RuntimeOwner } from './owner'\nimport { createHooks } from 'hookable'\nimport { createDecider } from '../../decisions'\nimport { createAgentsDomain, createMcpDomain, createModelsDomain, createProvidersDomain, createSkillsDomain, createToolsDomain } from '../catalog'\nimport { createCommandsDomain } from '../commands'\nimport { createContractsDomain } from '../contracts'\nimport { createHooksDomain } from '../hooks'\nimport { createIntegrationsDomain } from '../integrations'\nimport { createRpcDomain } from '../rpc'\nimport { createComposerDomain, createKeymapDispatch, createUiAdd, createUiDomain } from '../ui'\nimport { createArtifactsDomain, createGenerateDomain, createPluginsDomain, createSessionsDomain, createWorkspaceDomain } from './domains'\nimport { track } from './owner'\n\n/**\n * The desktop app's main-process handle behind `ctx.desktop`. Only the\n * desktop host gives one; elsewhere `ctx.desktop` is undefined.\n */\nexport interface DesktopPort {\n /** The `electron` module. */\n electron: () => unknown\n /** Window list and window events. `on` returns the unsubscribe. */\n windows: {\n list: () => readonly { id: number, focused: boolean }[]\n on: (event: 'open' | 'close' | 'focus', listener: (window: { id: number }) => void) => () => void\n }\n}\n\n/** The instructions registry together with its per-extension domain factory (`createInstructionsRegistry`). */\nexport type InstructionsRuntime = InstructionsRegistry & { domain: (deps: DomainDeps) => InstructionsDomain }\n\n/** The shared registries and host ports every extension's context draws on. One set per runtime. */\nexport interface ContextServices {\n /** Host and version data behind `ctx.app`. */\n readonly app: AppInfo\n /** Interceptors extensions add with `ctx.hooks`. */\n readonly interceptors: InterceptorRegistry\n /** The catalogs behind `ctx.tools`, `ctx.agents`, `ctx.models`, `ctx.providers`, `ctx.mcp` and `ctx.skills`. */\n readonly catalogs: {\n readonly tools: ToolsCatalog\n readonly agents: AgentsCatalog\n readonly models: ModelsCatalog\n readonly providers: ProvidersCatalog\n readonly mcp: McpCatalog\n readonly skills: SkillsCatalog\n }\n /** System prompt text behind `ctx.instructions`. */\n readonly instructions: InstructionsRuntime\n /** The facet registry behind `ctx.sessions.facets`. */\n readonly facets: FacetsRuntime\n /** The registry behind `ctx.add`. */\n readonly ui: UiRegistry\n /** Routes `ctx.ui` dialogs to a client. */\n readonly dialogs: DialogRouter\n /** Panels, navigation and composer calls on a client. */\n readonly uiClient: UiClientPort\n /** The registry behind `ctx.commands` and `ctx.keymap`. */\n readonly commands: CommandRegistry\n /** The router behind `ctx.rpc`. */\n readonly rpc: RpcRouter\n /** The registry behind `ctx.contracts`. */\n readonly contracts: ContractRegistry\n /** The registry behind `ctx.integrations`. */\n readonly integrations: IntegrationRegistry\n /** How integration sign-in flows show their UI. */\n readonly integrationFlows: IntegrationFlowPort\n /** Session, generate, workspace, artifacts and plugins ports. A missing port makes that domain reject. */\n readonly host: HostRuntimePorts\n /** The desktop app's handle behind `ctx.desktop`. Absent on other hosts. */\n readonly desktop?: DesktopPort\n /** Platform for keymap `mod` resolution. Default `process.platform`. */\n readonly platform?: string\n /** `ctx.extensions`. */\n readonly extensions: { list: () => readonly ExtensionInfo[], get: (id: string) => ExtensionInfo | undefined }\n}\n\n/** What is specific to one extension. */\nexport interface ExtensionContextInput<S extends SettingsSchema = SettingsSchema> {\n /** The extension's validated definition. */\n readonly definition: ExtensionDefinition<S>\n /** Where the extension was found. */\n readonly source: ExtensionSource\n /** The extension's folder. */\n readonly dir?: string\n /** Paths handed to the extension as `ctx.paths`. */\n readonly paths: ExtensionPaths\n /** The extension's logger. */\n readonly logger: Logger\n /** Bounds the extension's callbacks with timeouts and an error budget. */\n readonly guard: Guard\n /** The extension's hooks port (its own agent-hook bus and host events). */\n readonly hooks: HooksPort\n /** The extension's storage runtime, built on its root owner. */\n readonly storage: StorageRuntime\n /** The extension's settings domain, built on its root owner. */\n readonly settings: SettingsDomainInstance<S>\n /** The extension's project directory for RPC routing. Default `paths.projectRoot ?? paths.cwd`. */\n readonly directory?: string\n}\n\n/**\n * The members of host domains that return synchronously. On a host without\n * the port they throw at once instead of returning a rejected promise.\n */\nconst SYNC_MEMBERS: ReadonlySet<string> = new Set(['artifacts.kinds.register'])\n\n/** Values of a missing domain that are not calls (`generate.decide.available`). */\nconst UNAVAILABLE_VALUES: Readonly<Record<string, unknown>> = { 'generate.decide.available': false }\n\n/**\n * A domain whose host port is missing. Every member is a function: a\n * synchronous one (see {@link SYNC_MEMBERS}) throws, an async one rejects,\n * each with an error naming the member and the host. Nested members\n * (`kinds.register`) work the same way. `generate.decide` keeps\n * {@link AgentDecide}'s shape: `available` is `false`, and a call answers\n * `unavailable` (or throws `DecisionUnavailableError` with `{ throw: true }`).\n */\nfunction unavailableDomain<T>(name: string, host: string): T {\n const error = (path: string): Error => new Error(`ctx.${path} is not available in the ${host} host`)\n const make = (path: string): unknown => new Proxy(() => {}, {\n get: (_target, prop) => {\n if (prop === 'then' || typeof prop === 'symbol')\n return undefined\n const child = `${path}.${prop}`\n return Object.hasOwn(UNAVAILABLE_VALUES, child) ? UNAVAILABLE_VALUES[child] : make(child)\n },\n apply: (_target, _this, args: unknown[]) => {\n if (SYNC_MEMBERS.has(path))\n throw error(path)\n if (path === 'generate.decide')\n return unavailableDecider()(...(args as Parameters<AgentDecide>))\n return Promise.reject(error(path))\n },\n })\n return make(name) as T\n}\n\nlet noDecider: AgentDecide | undefined\n/** The decisions model of a host without one: `available` false, every call answers `unavailable`. */\nfunction unavailableDecider(): AgentDecide {\n return noDecider ??= createDecider({ providers: [], config: undefined, hooks: createHooks() }).forRun(undefined)\n}\n\nfunction hostDomain<P, T>(name: string, host: string, port: P | undefined, factory: (port: P) => T): T {\n return port === undefined ? unavailableDomain<T>(name, host) : factory(port)\n}\n\n/**\n * `ctx.sessions` with `facets`, which work on every host: on a host without\n * sessions the rest of the domain rejects, `facets` still registers.\n */\nfunction sessionsDomain(base: Omit<SessionsDomain, 'facets'>, facets: SessionFacetsDomain): SessionsDomain {\n if (typeof base === 'function')\n return new Proxy(base as SessionsDomain, { get: (target, prop, receiver) => (prop === 'facets' ? facets : Reflect.get(target, prop, receiver)) })\n return { ...base, facets }\n}\n\n/** `ctx.storage` bound to a scope: subscriptions made through it end with the scope. */\nfunction scopedStorage(root: StorageDomain, owner: RuntimeOwner): StorageDomain {\n const kv = (scope: Parameters<StorageDomain['kv']>[0], sessionId?: string): KeyValue => {\n const inner = root.kv(scope, sessionId)\n return { ...inner, subscribe: listener => track(owner, inner.subscribe(listener)) }\n }\n const scopeReadable = <T>(readable: { get: () => T, subscribe: (l: (v: T) => void) => () => void }) => ({\n get: readable.get,\n subscribe: (listener: (value: T) => void) => {\n const off = readable.subscribe(listener)\n return track(owner, { dispose: off }).dispose\n },\n })\n const store: StorageDomain['store'] = (name, schema, initial, opts) => {\n const inner = root.store(name, schema, initial, opts) as Store<unknown>\n return {\n ...scopeReadable(inner),\n set: inner.set,\n select: <U>(pick: (value: unknown) => U) => scopeReadable(inner.select(pick)),\n } as never\n }\n return { kv, store, memory: root.memory, path: root.path }\n}\n\n/** `ctx.settings` bound to a scope: `onChange` listeners end with the scope. */\nfunction scopedSettings<S extends SettingsSchema>(root: SettingsDomain<S>, owner: RuntimeOwner): SettingsDomain<S> {\n return Object.freeze({\n get: root.get,\n locked: root.locked,\n onChange: ((key, listener) => track(owner, root.onChange(key, listener))) as SettingsDomain<S>['onChange'],\n })\n}\n\n/**\n * Builds the context `setup` receives, bound to `owner`. `ctx.scope()`\n * makes a child owner and a context rebuilt on it.\n *\n * @param input - The extension's definition, paths, logger, guard and per-extension runtimes.\n * @param services - The runtime's shared registries and host ports.\n * @param owner - The owner registrations attach to (the root owner for `setup`).\n * @returns The context.\n */\nexport function createExtensionContext<S extends SettingsSchema>(\n input: ExtensionContextInput<S>,\n services: ContextServices,\n owner: RuntimeOwner,\n): ExtensionContext<S> {\n const { definition, logger, guard } = input\n const deps: DomainDeps = { extensionId: definition.id, owner, guard, logger }\n const isRoot = owner.parent === undefined\n const { catalogs, host } = services\n const uiPorts = { registry: services.ui, dialogs: services.dialogs, client: services.uiClient }\n const commands = createCommandsDomain(deps, services.commands, {\n ...(definition.displayName !== undefined ? { displayName: definition.displayName } : {}),\n ...(services.platform !== undefined ? { platform: services.platform } : {}),\n dispatch: createKeymapDispatch(deps, uiPorts),\n })\n const settings = isRoot ? input.settings.api : scopedSettings(input.settings.api, owner)\n const storage = isRoot ? input.storage.storage : scopedStorage(input.storage.storage, owner)\n\n const ctx: ExtensionContext<S> = {\n id: definition.id,\n ...(definition.version !== undefined ? { version: definition.version } : {}),\n ...(input.dir !== undefined ? { dir: input.dir } : {}),\n source: input.source,\n app: services.app,\n paths: input.paths,\n logger,\n signal: owner.signal,\n scope: () => {\n const child = owner.scope(`${owner.label}/scope`)\n const childCtx = createExtensionContext(input, services, child)\n return Object.assign(childCtx, { dispose: () => child.dispose() })\n },\n // Like the cleanup `setup` returns: runs once the calls in flight ended.\n onCleanup: cleanup => owner.onTeardown(cleanup),\n add: createUiAdd(deps, services.ui),\n tools: createToolsDomain(deps, catalogs.tools),\n hooks: createHooksDomain(deps, input.hooks, { interceptors: services.interceptors }),\n commands: commands.commands,\n keymap: commands.keymap,\n agents: createAgentsDomain(deps, catalogs.agents),\n models: createModelsDomain(deps, catalogs.models),\n providers: createProvidersDomain(deps, catalogs.providers),\n mcp: createMcpDomain(deps, catalogs.mcp),\n skills: createSkillsDomain(deps, catalogs.skills),\n plugins: hostDomain('plugins', services.app.host, host.plugins, port => createPluginsDomain(deps, port)),\n instructions: services.instructions.domain(deps),\n artifacts: hostDomain('artifacts', services.app.host, host.artifacts, port => createArtifactsDomain(deps, port)),\n sessions: sessionsDomain(host.sessions === undefined ? unavailableDomain('sessions', services.app.host) : createSessionsDomain(deps, host.sessions), services.facets.domain(deps)),\n generate: hostDomain('generate', services.app.host, host.generate, port => createGenerateDomain(deps, port)),\n workspace: hostDomain('workspace', services.app.host, host.workspace, port => createWorkspaceDomain(deps, port)),\n storage,\n settings,\n integrations: createIntegrationsDomain(deps, services.integrationFlows, services.integrations),\n rpc: createRpcDomain(deps, services.rpc, { directory: input.directory ?? input.paths.projectRoot ?? input.paths.cwd }),\n contracts: createContractsDomain(deps, services.contracts),\n ui: createUiDomain(deps, uiPorts),\n composer: createComposerDomain(deps, uiPorts),\n ...(services.desktop ? { desktop: desktopDomain(services.desktop, owner) } : {}),\n extensions: services.extensions,\n }\n return ctx\n}\n\n/** `ctx.desktop` over the host's port: window listeners end with the owner. */\nfunction desktopDomain(port: DesktopPort, owner: RuntimeOwner): DesktopDomain {\n return {\n electron: <T>() => port.electron() as T,\n windows: {\n list: () => port.windows.list(),\n on: (event, listener): Disposable => track(owner, { dispose: port.windows.on(event, listener) }),\n },\n }\n}\n","/**\n * Running an extension's `setup` and unloading it (extension API).\n *\n * Setup runs through the extension's guard with a 10 s bound\n * ({@link SETUP_TIMEOUT_MS}), so its errors are attributed and its\n * synchronous part is timed for stalls. A returned cleanup joins the\n * extension's owner. When setup throws or times out, everything it\n * registered so far is rolled back by disposing the owner: later\n * registrations from the still-running setup throw `DisposedError`.\n * The cleanup `setup` returns runs in the owner's teardown phase: after the\n * extension's in-flight calls ended (`owner.ts`).\n */\n\nimport type { ExtensionContext } from '../api/context'\nimport type { Cleanup } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { SettingsSchema } from '../api/settings'\nimport type { Guard } from './deps'\nimport type { RuntimeOwner } from './owner'\nimport { errorMessage } from '../../errors'\n\n/** How long `setup` may take, in ms. */\nexport const SETUP_TIMEOUT_MS = 10_000\n\n/** How long unload waits for async cleanups, in ms. */\nexport const UNLOAD_TIMEOUT_MS = 5_000\n\n/** Builds the `ctx` handed to `setup`, bound to `owner`. */\nexport type ContextFactory<S extends SettingsSchema = SettingsSchema> = (owner: RuntimeOwner) => ExtensionContext<S>\n\n/** Why a setup failed. */\nexport type SetupFailureReason\n /** `setup` threw or rejected. */\n = | 'threw'\n /** `setup` did not settle in time. */\n | 'timeout'\n /** The host's context factory threw: a host bug, not counted against the extension. */\n | 'context'\n /** The owner was disposed before or during setup (the extension was unloaded meanwhile). */\n | 'disposed'\n /** The guard refused to run it (its error budget is spent). */\n | 'refused'\n\n/** What {@link runSetup} reports. */\nexport type SetupOutcome\n = | { ok: true, warnings: readonly string[] }\n | { ok: false, reason: SetupFailureReason, error: string, cause?: unknown }\n\n/** Options for {@link runSetup}. */\nexport interface RunSetupOptions {\n /** Setup bound in ms. Default {@link SETUP_TIMEOUT_MS}. */\n timeoutMs?: number\n /** How long the rollback waits for async cleanups. Default {@link UNLOAD_TIMEOUT_MS}. */\n rollbackTimeoutMs?: number\n}\n\n/** What {@link unload} reports. */\nexport interface UnloadOutcome {\n /** `false` when an async cleanup was still running at the bound. It keeps running; nothing waits for it. */\n ok: boolean\n /** Set when `ok` is false. */\n error?: string\n /** Calls were still running: the registrations are withdrawn, the teardown waits for them (`owner.settled`). */\n draining?: boolean\n}\n\nconst NOT_SETTLED = Symbol('not settled')\n\n/**\n * Runs `definition.setup` with a context bound to `owner`.\n *\n * @param definition - The validated extension.\n * @param ctxFactory - Builds `ctx` for `owner`.\n * @param owner - The extension's root owner. Disposed on failure.\n * @param guard - The extension's guard.\n * @param options - Bounds.\n * @returns `ok`, or why it failed.\n */\nexport async function runSetup<S extends SettingsSchema>(\n definition: ExtensionDefinition<S>,\n ctxFactory: ContextFactory<S>,\n owner: RuntimeOwner,\n guard: Guard,\n options: RunSetupOptions = {},\n): Promise<SetupOutcome> {\n const timeoutMs = options.timeoutMs ?? SETUP_TIMEOUT_MS\n const fail = async (reason: SetupFailureReason, error: string, cause?: unknown): Promise<SetupOutcome> => {\n await unload(owner, { timeoutMs: options.rollbackTimeoutMs })\n return { ok: false, reason, error, ...(cause !== undefined ? { cause } : {}) }\n }\n\n if (owner.disposed)\n return { ok: false, reason: 'disposed', error: 'the extension was unloaded before setup ran' }\n\n let ctx: ExtensionContext<S>\n try {\n ctx = ctxFactory(owner)\n }\n catch (cause) {\n return fail('context', `could not build the extension context: ${errorMessage(cause)}`, cause)\n }\n\n let started = false\n let thrown: { cause: unknown } | undefined\n // `teardown`: the guard tripping is one of the ways the extension gets disposed, and its cleanup must still run then.\n const runCleanup = async (cleanup: Cleanup): Promise<void> => { await guard.call('cleanup', cleanup, { teardown: true }) }\n const result = await guard.call<unknown>('setup', async () => {\n started = true\n let returned: unknown\n try {\n returned = await definition.setup(ctx)\n }\n catch (cause) {\n thrown = { cause }\n throw cause\n }\n // Settled after a timeout or an unload: nothing will register this cleanup, so run it now.\n if (owner.disposed && typeof returned === 'function')\n void runCleanup(returned as Cleanup)\n return returned\n }, { timeoutMs, fallback: NOT_SETTLED })\n\n if (!started)\n return fail('refused', 'setup was not run: the extension\\'s error budget is spent')\n if (thrown)\n return fail('threw', errorMessage(thrown.cause), thrown.cause)\n if (result === NOT_SETTLED)\n return fail('timeout', `setup timed out after ${timeoutMs}ms`)\n\n if (owner.disposed) {\n if (typeof result === 'function')\n void runCleanup(result as Cleanup)\n return { ok: false, reason: 'disposed', error: 'the extension was unloaded during setup' }\n }\n const warnings: string[] = []\n if (typeof result === 'function') {\n const cleanup = result as Cleanup\n owner.onTeardown(() => runCleanup(cleanup))\n }\n else if (result !== undefined) {\n warnings.push(`setup returned ${typeof result}; only a cleanup function or nothing is used`)\n }\n return { ok: true, warnings }\n}\n\n/**\n * Unloads an extension: disposes its owner (every registration withdrawn,\n * then `ctx.signal` aborted and the teardown cleanups run) and waits for the\n * async cleanups up to a bound. With calls in flight the teardown waits for\n * them (`owner.ts`): unload then waits only for the withdrawal and reports\n * `draining`. Calling it again is harmless.\n *\n * @param owner - The extension's root owner.\n * @param options - `timeoutMs`, default {@link UNLOAD_TIMEOUT_MS}.\n * @param options.timeoutMs - How long to wait for async cleanups.\n * @returns Whether every cleanup finished in time.\n */\nexport async function unload(owner: RuntimeOwner, options: { timeoutMs?: number } = {}): Promise<UnloadOutcome> {\n owner.dispose()\n if (owner.draining) {\n const outcome = await settleWithin(owner.withdrawn, options.timeoutMs)\n return { ...outcome, draining: true }\n }\n return settleWithin(owner.settled, options.timeoutMs)\n}\n\n/**\n * Waits for `done` up to `timeoutMs` (default {@link UNLOAD_TIMEOUT_MS}).\n *\n * @param done - Async cleanups settling.\n * @param timeoutMs - The bound.\n */\nexport async function settleWithin(done: Promise<void>, timeoutMs = UNLOAD_TIMEOUT_MS): Promise<UnloadOutcome> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<typeof NOT_SETTLED>((resolve) => {\n timer = setTimeout(resolve, timeoutMs, NOT_SETTLED)\n })\n try {\n const result = await Promise.race([done, timedOut])\n return result === NOT_SETTLED ? { ok: false, error: `cleanup still running after ${timeoutMs}ms` } : { ok: true }\n }\n finally {\n clearTimeout(timer)\n }\n}\n","/**\n * Load order from the `dependencies` field (extension API).\n *\n * Dependencies only order the loads and give install hints: a missing or\n * mismatched dependency is reported, never fatal (`ctx.use` reports it as\n * inactive at run time). The order is topological; among extensions that are\n * ready at the same time, input order wins, so the result is deterministic\n * for a deterministic discovery order. A cycle is broken at its member that\n * comes first in the input, with a warning.\n */\n\nimport { satisfiesVersionRange } from '../host-version'\n\n/** What the resolver needs of an extension. */\nexport interface LoadOrderEntry {\n /** The extension id. */\n id: string\n /** Its version, checked against the ranges that name it. */\n version?: string\n /** `{ id: semver range }`. */\n dependencies?: Readonly<Record<string, string>>\n}\n\n/** A problem the resolver reports. None of them stops a load. */\nexport type LoadOrderIssue\n = | { kind: 'missing', id: string, dependency: string, range: string }\n | { kind: 'version', id: string, dependency: string, range: string, version: string }\n | { kind: 'cycle', ids: readonly string[], brokenAt: string }\n | { kind: 'duplicate', id: string }\n\n/** What {@link resolveLoadOrder} returns. */\nexport interface LoadOrder<E extends LoadOrderEntry> {\n /** The entries in load order. A duplicate id keeps its first entry only. */\n order: readonly E[]\n /** Missing and mismatched dependencies, broken cycles, dropped duplicates. */\n issues: readonly LoadOrderIssue[]\n}\n\n/**\n * Orders `entries` so each loads after the extensions it depends on.\n *\n * @param entries - The extensions, in discovery order (the tiebreak).\n * @returns The order and the issues found.\n */\nexport function resolveLoadOrder<E extends LoadOrderEntry>(entries: readonly E[]): LoadOrder<E> {\n const issues: LoadOrderIssue[] = []\n const byId = new Map<string, { entry: E, index: number }>()\n for (const entry of entries) {\n if (byId.has(entry.id))\n issues.push({ kind: 'duplicate', id: entry.id })\n else\n byId.set(entry.id, { entry, index: byId.size })\n }\n\n // Edges to present dependencies only; the rest are reported.\n const deps = new Map<string, string[]>()\n for (const { entry } of byId.values()) {\n const present: string[] = []\n for (const [dependency, range] of Object.entries(entry.dependencies ?? {})) {\n const target = byId.get(dependency)\n if (!target) {\n issues.push({ kind: 'missing', id: entry.id, dependency, range })\n continue\n }\n if (dependency === entry.id)\n continue\n present.push(dependency)\n const version = target.entry.version\n if (version !== undefined && satisfiesVersionRange(version, range) === false)\n issues.push({ kind: 'version', id: entry.id, dependency, range, version })\n }\n deps.set(entry.id, present)\n }\n\n const loaded = new Set<string>()\n const order: E[] = []\n const pending = [...byId.values()].sort((a, b) => a.index - b.index).map(v => v.entry)\n while (pending.length > 0) {\n let next = pending.findIndex(e => deps.get(e.id)!.every(d => loaded.has(d)))\n if (next === -1) {\n // Every pending entry waits on another, so a walk from any of them ends in a cycle.\n // Break it at its member that comes first in input order.\n const cycle = findCycle(pending[0]!.id, deps, loaded)\n next = pending.findIndex(e => cycle.includes(e.id))\n issues.push({ kind: 'cycle', ids: cycle, brokenAt: pending[next]!.id })\n }\n const [entry] = pending.splice(next, 1)\n loaded.add(entry!.id)\n order.push(entry!)\n }\n return { order, issues }\n}\n\n/** The cycle reached by walking unloaded dependencies from `start`, in walk order. */\nfunction findCycle(start: string, deps: ReadonlyMap<string, readonly string[]>, loaded: ReadonlySet<string>): string[] {\n const path: string[] = []\n const seen = new Map<string, number>()\n let current: string | undefined = start\n while (current !== undefined && !seen.has(current)) {\n seen.set(current, path.length)\n path.push(current)\n current = deps.get(current)!.find(d => !loaded.has(d))\n }\n return current === undefined ? path : path.slice(seen.get(current))\n}\n","/**\n * The extension runtime of one host (extension API).\n *\n * `createExtensionRuntime` builds the shared registries once (interceptors,\n * catalogs, instructions, UI, commands, RPC, contracts, integrations) and\n * loads definitions into them: validated, in dependency order, one owner\n * and one guard per extension, storage preloaded before `setup`, everything\n * rolled back when `setup` fails. A guard whose error budget is spent\n * disables its extension (status `'failed'` with the reason) and disposes\n * its owner. Disabled extensions never run; their settings stay readable\n * from the static schema. An extension unloaded, reloaded or disposed with\n * calls in flight (a command run, a tool execute, a guarded callback) has\n * its registrations withdrawn at once and its domains torn down once those\n * calls end, at most {@link ExtensionRuntimeOptions.drainTimeoutMs} for a\n * call without a bound of its own (`owner.ts`).\n *\n * Hosts plug in through {@link RuntimePorts}; every port is optional and\n * falls back to an in-memory or \"not available\" one.\n */\n\nimport type { Logger } from '../../logger'\nimport type { OAuthRefreshHookContext } from '../../types'\nimport type { ExtensionInfo } from '../api/context'\nimport type { ExtensionHostKind, ExtensionPaths, ExtensionSource } from '../api/core'\nimport type { ExtensionDefinition } from '../api/define'\nimport type { HookEvents } from '../api/hooks'\nimport type { ActionSetting } from '../api/settings'\nimport type { Json } from '../api/storage'\nimport type { AgentsCatalogPort, McpCatalogPort, ModelsCatalogPort, ProvidersCatalogPort, SkillsCatalogPort, ToolsCatalogPort } from '../catalog'\nimport type { CommandHostPort, KeymapPort } from '../commands'\nimport type { HooksPort, HostEventName } from '../hooks'\nimport type { AuthStorePort, IntegrationFlowPort } from '../integrations'\nimport type { RpcRemoteBridge, RpcRemoteTransport } from '../rpc'\nimport type { SettingsDomainInstance, SettingsPort, WireSettings } from '../settings'\nimport type { MemoryRegistry, StorageArea, StorageLocation, StoragePort, StorageRuntime } from '../storage'\nimport type { ExtensionManifest, LoadedPluginRecord } from '../types'\nimport type { DialogPort, UiClientPort } from '../ui'\nimport type { OwnSettingActions } from '../ui/callbacks'\nimport type { ContextServices, DesktopPort } from './context'\nimport type { DomainDeps } from './deps'\nimport type { ArtifactKindEntry, HostRuntimePorts, PluginsPort } from './domains'\nimport type { ErrorBudget, GuardTrip, RuntimeGuard, StallMonitor, StallReport } from './guard'\nimport type { LoadOrderIssue } from './load-order'\nimport type { ExtensionRuntimeOutputs, HostEventSink } from './outputs'\nimport type { RuntimeOwner } from './owner'\nimport { basename } from 'node:path'\nimport { onProviderAccountsChange } from '../../chat/credentials'\nimport { consoleSink, createLogger } from '../../logger'\nimport { ZIDANE_VERSION } from '../../version'\nimport { createAgentsCatalog, createMcpCatalog, createModelsCatalog, createProvidersCatalog, createSkillsCatalog, createToolsCatalog, watchProviderAccounts } from '../catalog'\nimport { createCommandRegistry, createKeymap } from '../commands'\nimport { createContractRegistry } from '../contracts'\nimport { createInterceptorRegistry } from '../hooks'\nimport { createIntegrationRegistry, createMemoryAuthStore } from '../integrations'\nimport { createRpcRemoteBridge, createRpcRouter } from '../rpc'\nimport { actionScope, createSettingsDomain } from '../settings'\nimport { createMemoryRegistry, createStorageDomain } from '../storage'\nimport { createDialogRouter, createUiRegistry } from '../ui'\nimport { createExtensionContext } from './context'\nimport { createInstructionsRegistry } from './domains'\nimport { createFacetRegistry } from './facets'\nimport { createGuard, createStallMonitor } from './guard'\nimport { runSetup, settleWithin, unload as unloadOwner } from './lifecycle'\nimport { resolveLoadOrder } from './load-order'\nimport { createMemorySettingsPort, createMemoryStoragePort, EMPTY_MCP_PORT, NO_CLIENT_DIALOG_PORT, NO_INTEGRATION_FLOWS, NO_UI_CLIENT_PORT } from './memory-ports'\nimport { createOwner } from './owner'\nimport { runtimeSettingsWire } from './settings-wire'\nimport { validateDefinition } from './validate-definition'\n\n/** The agent-hook side of the hooks port. */\nexport interface RuntimeHooksPorts {\n /**\n * The agent hook bus (`Agent['hooks']`, or a fan-out over every agent).\n * Without it, observers land on a per-extension bus the registry\n * view hands to the hosts as ordinary hook handlers.\n */\n agentHooks?: HooksPort['agentHooks']\n /** See {@link HooksPort.sessionIdOf}. */\n sessionIdOf?: HooksPort['sessionIdOf']\n /**\n * The host calls `outputs.hostEvents.emit` itself. When `false` (default),\n * the registry view also exposes per-extension `runSettled` /\n * `sessionEvents` handlers so the host delivers host events through them.\n */\n emitsHostEvents?: boolean\n}\n\n/** Base data of the shared catalogs. Each falls back to an empty base. */\nexport interface RuntimeCatalogPorts {\n /** Base tools. */\n tools?: ToolsCatalogPort\n /** Base agent profiles. */\n agents?: AgentsCatalogPort\n /** Base models. */\n models?: ModelsCatalogPort\n /** Base providers. */\n providers?: ProvidersCatalogPort\n /** Base MCP servers. */\n mcp?: McpCatalogPort\n /** Base skills. */\n skills?: SkillsCatalogPort\n}\n\n/** Everything a host plugs into the runtime. Every member is optional. */\nexport interface RuntimePorts {\n /** Where `ctx.storage` keeps data. Default: in memory. */\n storage?: StoragePort\n /** Where settings values live. Default: in memory. */\n settings?: SettingsPort\n /** Where integration connections persist. Default: in memory. */\n authStore?: AuthStorePort\n /** How integration sign-in flows show their UI. Default: refuses. */\n integrationFlows?: IntegrationFlowPort\n /** Agent hooks and host events. */\n hooks?: RuntimeHooksPorts\n /** Catalog bases. */\n catalogs?: RuntimeCatalogPorts\n /** Built-in commands, slash submission and session-bound invocation members. */\n commands?: CommandHostPort\n /** User keybinding overrides. */\n keymap?: KeymapPort\n /** Clients and dialogs. Default: no client (dialogs reject with `NoUiError`). */\n dialogs?: DialogPort\n /** Panels, navigation, composer and notifications on a client. */\n uiClient?: UiClientPort\n /** Where RPC events go to remote clients. With it, the runtime exposes `rpcBridge`. */\n rpcTransport?: RpcRemoteTransport\n /** The desktop app's main-process handle; `ctx.desktop` is undefined without it. */\n desktop?: DesktopPort\n /**\n * Session, generate, workspace, artifacts and plugins ports. A missing one\n * makes that domain reject, except `plugins`, which defaults to the\n * runtime's own catalogs.\n */\n host?: HostRuntimePorts\n /** The session the current call runs for (default of `'session'` storage). */\n currentSessionId?: () => string | undefined\n}\n\n/** One extension to load. */\nexport interface RuntimeEntry {\n /** The module's default export; validated before use. */\n definition: unknown\n /** Where the extension was found. */\n source: ExtensionSource\n /** The extension's folder. Its name must equal the id. */\n dir?: string\n /** `false`: discovered but turned off. Not run; settings stay readable. Default `true`. */\n enabled?: boolean\n /** Its manifest (`extension.json`, `package.json#zidane`): the display name and icon when the definition has none. */\n manifest?: ExtensionManifest\n /**\n * Why the module could not be imported (a syntax error, no definition). The\n * entry is listed as `failed` with this error and never validated, so a\n * later {@link ExtensionRuntime.reload} of its folder can bring it up.\n */\n error?: string\n}\n\n/** Options of {@link createExtensionRuntime}. */\nexport interface ExtensionRuntimeOptions {\n /** The host process. */\n host: ExtensionHostKind\n /** Paths handed to every extension. */\n paths: ExtensionPaths\n /** Host ports. */\n ports?: RuntimePorts\n /** Base logger; each extension logs through `logger.with({ extension })`. Default: warnings to stderr. */\n logger?: Logger\n /** Process-wide `ctx.storage.memory`. Default: one registry per process. */\n memory?: MemoryRegistry\n /** Error budget of each guard. `false` never trips. */\n budget?: Partial<ErrorBudget> | false\n /** Default bound of guarded callbacks, in ms. */\n callbackTimeoutMs?: number\n /** Bound of `setup`, in ms. */\n setupTimeoutMs?: number\n /**\n * How long an unloaded extension's teardown waits for a call in flight that\n * has no bound of its own (a command run, a tool execute), in ms. Default\n * `DEFAULT_DRAIN_MS` (`owner.ts`): 30 minutes.\n */\n drainTimeoutMs?: number\n /**\n * Imports an entry's module again for {@link ExtensionRuntime.reload}.\n * Default: entries with a folder (`project`, `user`, `config`) are\n * imported fresh from it (`loadExtensionFolder`, module graph evicted\n * first); `inline` and `builtin` entries keep their definition.\n */\n reimport?: (entry: RuntimeEntry) => Promise<RuntimeEntry>\n /** Receives event-loop stalls (after they are logged). */\n onStall?: (report: StallReport) => void\n /** Called after an extension's status changed (loaded, failed, disabled by its guard, unloaded). */\n onChange?: (info: ExtensionInfo | { id: string, status: 'unloaded' }) => void\n /** zidane version for `ctx.app`. Default: this package's. */\n version?: string\n /** Platform for `ctx.app` and keymap `mod`. Default `process.platform`. */\n platform?: string\n /**\n * Receives the promise of every async guarded callback (observers, RPC\n * handlers, panel loads). A test seam: the testing kit waits on them so a\n * fired event has been handled before it returns.\n */\n trackCalls?: (pending: Promise<unknown>) => void\n}\n\n/** The loaded state of one extension, for hosts and the registry view. */\nexport interface RuntimeExtension {\n /** The extension id. */\n readonly id: string\n /** The entry it was loaded from. */\n readonly entry: RuntimeEntry\n /** The validated definition; absent when validation failed. */\n readonly definition?: ExtensionDefinition\n /** Status and metadata, as `ctx.extensions` shows it. */\n readonly info: ExtensionInfo\n /** Present while active. */\n readonly guard?: RuntimeGuard\n /** Present while active. */\n readonly settings?: SettingsDomainInstance\n /** Validation warnings and load-order issues about this extension. */\n readonly warnings: readonly string[]\n}\n\n/** Handlers an extension put on its own agent-hook bus and host events (when the host gave no agent hooks). */\nexport interface ExtensionHookHandlers {\n /** Agent-hook handlers, by hook name. */\n readonly agent: ReadonlyMap<string, ReadonlySet<(...args: unknown[]) => unknown>>\n /** Host-event handlers, by event name. */\n readonly host: ReadonlyMap<HostEventName, ReadonlySet<(event: never) => void>>\n}\n\n/** What {@link createExtensionRuntime} returns. */\nexport interface ExtensionRuntime {\n /** Loads entries (in dependency order, after those already loaded). Never rejects. */\n load: (entries: readonly RuntimeEntry[]) => Promise<readonly ExtensionInfo[]>\n /** Unloads an extension and forgets it. `forget: true` also clears its `ctx.storage.memory`. */\n unload: (id: string, opts?: { forget?: boolean }) => Promise<void>\n /**\n * Reloads one extension in place: its owner is disposed (registrations\n * withdrawn, cleanups run), its module imported again from its folder\n * (`options.reimport`), and `setup` runs again at the same load-order\n * position. Other extensions are untouched; `ctx.storage.memory`\n * survives. `opts.entry` replaces the entry instead of re-importing.\n * Resolves with the new status, or `undefined` for an unknown id.\n */\n reload: (id: string, opts?: { entry?: RuntimeEntry }) => Promise<ExtensionInfo | undefined>\n /** The id of the extension loaded from `dir`, if any. */\n idOfDir: (dir: string) => string | undefined\n /** The shared registries. */\n readonly outputs: ExtensionRuntimeOutputs\n /** Every known extension, in load order. */\n extensions: () => ExtensionInfo[]\n /** One extension's state. */\n get: (id: string) => RuntimeExtension | undefined\n /** Settings of every known extension (active and disabled) in the Settings wire format. */\n settingsWire: () => WireSettings\n /** Loads `'session'` storage of every active extension for a run. Failures are logged. */\n preloadSession: (sessionId: string) => Promise<void>\n /**\n * Checks a client's write to an extension's storage against what the\n * extension holds (a store's version and schema): why it is refused, or\n * `undefined` (also for an extension that is not active).\n */\n checkStorageWrite: (loc: StorageLocation, area: StorageArea, key: string, value: Json | undefined) => Promise<string | undefined>\n /** An extension's own agent-hook and host-event handlers. */\n hookHandlers: (id: string) => ExtensionHookHandlers\n /** Artifact kinds an extension registered (`ctx.artifacts.kinds.register`), callbacks guarded. */\n artifactKinds: (id: string) => readonly ArtifactKindEntry[]\n /** Agent Plugins an extension loaded (`ctx.plugins.load`). */\n plugins: (id: string) => readonly LoadedPluginRecord[]\n /**\n * Calls `listener` after an extension's status changed (loaded, failed,\n * disabled by its guard, unloaded) or it registered or released an\n * artifact kind, an Agent Plugin or the first observer of an agent hook.\n * The registry view re-reads on it. Returns the unsubscribe.\n */\n subscribe: (listener: () => void) => () => void\n /** Whether the host gave its own agent hooks / emits host events (the registry view skips those parts). */\n readonly hostWired: { agentHooks: boolean, hostEvents: boolean }\n /** The protocol side of RPC, when the host gave a transport. */\n readonly rpcBridge?: RpcRemoteBridge\n /** Load-order issues of the last `load`. */\n readonly issues: readonly LoadOrderIssue[]\n /** Unloads everything and releases the registries. */\n dispose: () => Promise<void>\n}\n\n/** One per process: `ctx.storage.memory` survives reloads and registry rebuilds. */\nconst processMemory = createMemoryRegistry()\n\ninterface MutableRecord {\n id: string\n entry: RuntimeEntry\n definition?: ExtensionDefinition\n info: ExtensionInfo\n guard?: RuntimeGuard\n owner?: RuntimeOwner\n settings?: SettingsDomainInstance\n storage?: StorageRuntime\n warnings: string[]\n /** The running {@link deactivateRecord} of the last active owner, so a later unload waits for a teardown the guard started. */\n deactivating?: Promise<void>\n /** Set when that owner was unloaded with calls in flight: its teardown, once they ended. Runtime dispose waits for it. */\n teardown?: Promise<void>\n agent: Map<string, Set<(...args: unknown[]) => unknown>>\n host: Map<HostEventName, Set<(event: never) => void>>\n}\n\n/** Live entries kept per extension; a Disposable takes its entry out. */\n/** An extension's own settings actions, as the UI registry runs them for `setting.action` with its id as page id. */\nfunction ownSettingActions(settings: SettingsDomainInstance | undefined): OwnSettingActions | undefined {\n if (!settings)\n return undefined\n const action = (key: string): ActionSetting | undefined => {\n const item = Object.hasOwn(settings.schema.items, key) ? settings.schema.items[key] : undefined\n return item?.type === 'action' ? item : undefined\n }\n return {\n run: async (key, signal) => action(key) ? { message: (await settings.runAction(key, { signal })).message } : undefined,\n status: key => settings.actionStatus(key),\n scope: (key) => {\n const item = action(key)\n return item ? actionScope(item) : undefined\n },\n }\n}\n\nfunction keep<T>(list: T[], item: T): { dispose: () => void } {\n list.push(item)\n return {\n dispose: () => {\n const at = list.indexOf(item)\n if (at >= 0)\n list.splice(at, 1)\n },\n }\n}\n\nfunction issueText(issue: LoadOrderIssue): string {\n switch (issue.kind) {\n case 'missing': return `dependency \"${issue.dependency}\" (${issue.range}) is not installed`\n case 'version': return `dependency \"${issue.dependency}\" is ${issue.version}, needs ${issue.range}`\n case 'cycle': return `dependency cycle ${issue.ids.join(' → ')}; loaded \"${issue.brokenAt}\" first`\n case 'duplicate': return `another extension with id \"${issue.id}\" was loaded first`\n }\n}\n\nfunction idOf(entry: RuntimeEntry): string {\n const def = entry.definition as { id?: unknown, name?: unknown } | undefined\n if (def && typeof def.id === 'string' && def.id)\n return def.id\n if (entry.dir)\n return basename(entry.dir)\n // A definition that fails validation for lack of an `id` may still say what it is called.\n return def && typeof def.name === 'string' && def.name ? def.name : '(unknown)'\n}\n\n/** The registries and host ports one runtime shares across its extensions. */\ninterface Shared {\n outputs: ExtensionRuntimeOutputs\n services: ContextServices\n hostListeners: Set<HostListener>\n /** `oauth:refresh` observers, also told of integration refreshes (which run outside any agent). */\n refreshObservers: Set<(event: OAuthRefreshHookContext) => void>\n artifactKinds: ArtifactKindEntry[]\n pluginRecords: LoadedPluginRecord[]\n /** Tells {@link ExtensionRuntime.subscribe} listeners. */\n changed: () => void\n /** Tells `options.onChange`, then the {@link ExtensionRuntime.subscribe} listeners. */\n statusChanged: (info: ExtensionInfo | { id: string, status: 'unloaded' }) => void\n /** {@link ExtensionRuntime.subscribe}. */\n subscribe: (listener: () => void) => () => void\n /** The listeners of {@link ExtensionRuntime.subscribe}. */\n changeListeners: Set<() => void>\n rpcBridge?: RpcRemoteBridge\n /** Releases what the shared registries hold (RPC bridge, commands, buffered toasts). */\n release: () => void\n /** Counts one withdrawal ({@link ExtensionRuntimeOutputs.withdrawals}). */\n withdrawn: () => void\n}\n\ninterface HostListener { name: HostEventName, fn: (event: never) => void, ext: string }\n\n/** Builds the shared registries over the host's ports (or their in-memory fallbacks). */\nfunction createShared(options: ExtensionRuntimeOptions, ports: RuntimePorts, baseLogger: Logger, records: ReadonlyMap<string, MutableRecord>, order: readonly string[], rank: (id: string) => number): Shared {\n const loadOrder = { order: rank }\n const hostListeners = new Set<HostListener>()\n const refreshObservers = new Set<(event: OAuthRefreshHookContext) => void>()\n const hostEvents: HostEventSink = {\n emit: (name, event) => {\n for (const l of [...hostListeners]) {\n if (l.name === name)\n l.fn(event as never)\n }\n },\n }\n\n const commands = createCommandRegistry({\n ...(ports.commands ? { port: ports.commands } : {}),\n keymap: createKeymap({ ...(ports.keymap ? { port: ports.keymap } : {}), ...(options.platform ? { platform: options.platform } : {}), logger: baseLogger }),\n logger: baseLogger,\n })\n const ui = createUiRegistry({ logger: baseLogger, settingsAccess: id => records.get(id)?.settings?.actionAccess, ownActions: id => ownSettingActions(records.get(id)?.settings), commands: { has: id => commands.get(id) !== undefined, subscribe: listener => commands.subscribe(listener) } })\n const rpc = createRpcRouter()\n const instructions = createInstructionsRegistry({ order: rank })\n // The host computes them: handed to its session control once an extension uses them.\n const facets: ReturnType<typeof createFacetRegistry> = createFacetRegistry({ order: rank, attachHost: registry => ports.host?.sessions?.sessionControl()?.attachFacets?.(registry) })\n const artifactKinds: ArtifactKindEntry[] = []\n const pluginRecords: LoadedPluginRecord[] = []\n const changeListeners = new Set<() => void>()\n const changed = (): void => {\n for (const listener of [...changeListeners]) {\n try {\n listener()\n }\n catch {}\n }\n }\n const statusChanged = (info: ExtensionInfo | { id: string, status: 'unloaded' }): void => {\n try {\n options.onChange?.(info)\n }\n catch {}\n changed()\n }\n const subscribe = (listener: () => void): (() => void) => {\n changeListeners.add(listener)\n return () => {\n changeListeners.delete(listener)\n }\n }\n let withdrawals = 0\n const outputs: ExtensionRuntimeOutputs = {\n withdrawals: () => withdrawals,\n interceptors: createInterceptorRegistry({ loadOrder: rank }),\n catalogs: {\n tools: createToolsCatalog(ports.catalogs?.tools ?? { base: () => [] }, loadOrder),\n agents: createAgentsCatalog(ports.catalogs?.agents ?? { profiles: () => [] }, loadOrder),\n models: createModelsCatalog(ports.catalogs?.models ?? { models: () => [] }, loadOrder),\n providers: createProvidersCatalog(ports.catalogs?.providers ?? { providers: () => [] }, loadOrder),\n mcp: createMcpCatalog(ports.catalogs?.mcp ?? EMPTY_MCP_PORT, loadOrder),\n skills: createSkillsCatalog(ports.catalogs?.skills ?? { skills: () => [] }, loadOrder),\n },\n instructions,\n ui,\n commands,\n rpc,\n contracts: createContractRegistry({ loadOrder: id => (order.includes(id) ? rank(id) : undefined) }),\n integrations: createIntegrationRegistry({\n store: ports.authStore ?? createMemoryAuthStore(),\n logger: baseLogger,\n onRefresh: (event) => {\n for (const fn of [...refreshObservers])\n fn(structuredClone(event))\n },\n }),\n hostEvents,\n facets,\n }\n const rpcBridge = ports.rpcTransport ? createRpcRemoteBridge(rpc, ports.rpcTransport) : undefined\n // Provider transforms read accounts (per-account model lists): re-run them when an integration connection or a stored provider account changes.\n const unwatchAccounts = watchProviderAccounts(outputs.catalogs.providers, outputs.integrations, [onProviderAccountsChange])\n\n const hostPorts: HostRuntimePorts = { ...ports.host }\n const hostArtifacts = ports.host?.artifacts\n if (hostArtifacts) {\n hostPorts.artifacts = {\n ...hostArtifacts,\n registerKind: (entry) => {\n const kept = keep(artifactKinds, entry)\n const forwarded = hostArtifacts.registerKind?.(entry)\n changed()\n return {\n dispose: () => {\n kept.dispose()\n forwarded?.dispose()\n changed()\n },\n }\n },\n }\n }\n const hostPlugins = ports.host?.plugins\n const defaultPlugins: PluginsPort = {\n extension: (id) => {\n const r = records.get(id)\n return r ? { ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}), source: r.entry.source, paths: options.paths, ...(r.storage ? { storagePath: r.storage.storage.path } : {}) } : undefined\n },\n registerSkill: (skill, origin) => outputs.catalogs.skills.register(skill, origin),\n registerMcpServer: (server, origin) => outputs.catalogs.mcp.register(server, origin),\n }\n const basePlugins = hostPlugins ?? defaultPlugins\n hostPorts.plugins = {\n ...basePlugins,\n recordPlugin: (record) => {\n const kept = keep(pluginRecords, record)\n const forwarded = basePlugins.recordPlugin?.(record)\n changed()\n return {\n dispose: () => {\n kept.dispose()\n forwarded?.dispose()\n changed()\n },\n }\n },\n }\n\n const services: ContextServices = {\n app: { name: 'zidane', version: options.version ?? ZIDANE_VERSION, host: options.host, platform: options.platform ?? process.platform },\n interceptors: outputs.interceptors,\n catalogs: outputs.catalogs,\n instructions,\n facets,\n ui,\n dialogs: createDialogRouter(ports.dialogs ?? NO_CLIENT_DIALOG_PORT),\n uiClient: ports.uiClient ?? NO_UI_CLIENT_PORT,\n commands,\n rpc,\n contracts: outputs.contracts,\n integrations: outputs.integrations,\n integrationFlows: ports.integrationFlows ?? NO_INTEGRATION_FLOWS,\n host: hostPorts,\n ...(ports.desktop ? { desktop: ports.desktop } : {}),\n ...(options.platform ? { platform: options.platform } : {}),\n extensions: {\n list: () => order.map(id => records.get(id)).filter((r): r is MutableRecord => !!r).map(r => r.info),\n get: (id) => {\n const r = records.get(id)\n return r?.info\n },\n },\n }\n\n const release = (): void => {\n unwatchAccounts()\n rpcBridge?.dispose()\n commands.dispose()\n services.dialogs.dispose()\n }\n\n const withdrawn = (): void => {\n withdrawals++\n }\n\n return { outputs, services, hostListeners, refreshObservers, artifactKinds, pluginRecords, changed, statusChanged, subscribe, changeListeners, ...(rpcBridge ? { rpcBridge } : {}), release, withdrawn }\n}\n\n/** The per-extension hooks port: the host's bus when given, else the extension's own. */\nfunction createHooksPort(r: MutableRecord, ports: RuntimePorts, hostListeners: Set<HostListener>, refreshObservers: Set<(event: OAuthRefreshHookContext) => void>, changed: () => void): HooksPort {\n const bus: HooksPort['agentHooks'] = ports.hooks?.agentHooks ?? {\n hook: ((name: string, fn: (...args: unknown[]) => unknown) => {\n let set = r.agent.get(name)\n const first = !set\n if (!set) {\n set = new Set()\n r.agent.set(name, set)\n }\n set.add(fn)\n // The registry view hands out one dispatcher per hook name: a new name needs a new read.\n if (first)\n changed()\n return () => { set.delete(fn) }\n }) as HooksPort['agentHooks']['hook'],\n }\n // `oauth:refresh` observers also hear integration refreshes, which no agent bus carries.\n const agentHooks: HooksPort['agentHooks'] = {\n hook: ((name: string, fn: (...args: unknown[]) => unknown) => {\n const off = (bus.hook as (name: string, fn: (...args: unknown[]) => unknown) => () => void)(name, fn)\n if (name !== 'oauth:refresh')\n return off\n const observer = fn as (event: OAuthRefreshHookContext) => void\n refreshObservers.add(observer)\n return () => {\n refreshObservers.delete(observer)\n off()\n }\n }) as HooksPort['agentHooks']['hook'],\n }\n return {\n agentHooks,\n hostEvents: {\n on: <K extends HostEventName>(name: K, fn: (event: HookEvents[K]) => void) => {\n const listener = { name, fn: fn as (event: never) => void, ext: r.id }\n hostListeners.add(listener)\n let set = r.host.get(name)\n if (!set) {\n set = new Set()\n r.host.set(name, set)\n }\n set.add(listener.fn)\n return () => {\n hostListeners.delete(listener)\n set.delete(listener.fn)\n }\n },\n },\n ...(ports.hooks?.sessionIdOf ? { sessionIdOf: ports.hooks.sessionIdOf } : {}),\n }\n}\n\n/** Validates new entries and orders the loadable ones after the known ones. Pure apart from the records it makes. */\nfunction prepareLoad(entries: readonly RuntimeEntry[], known: readonly MutableRecord[], status: (r: MutableRecord, status: ExtensionInfo['status'], error?: string) => void, logger: Logger): { fresh: MutableRecord[], sequence: MutableRecord[], issues: readonly LoadOrderIssue[] } {\n const taken = new Set(known.map(r => r.id))\n const fresh: MutableRecord[] = []\n for (const entry of entries) {\n const id = idOf(entry)\n const r: MutableRecord = { id, entry, info: { id, displayName: id, source: entry.source, status: 'failed' }, warnings: [], agent: new Map(), host: new Map() }\n fresh.push(r)\n if (entry.error !== undefined) {\n status(r, 'failed', entry.error)\n continue\n }\n const folderName = entry.dir && entry.source !== 'inline' && entry.source !== 'builtin' ? basename(entry.dir) : undefined\n const result = validateDefinition(entry.definition, folderName !== undefined ? { folderName } : {})\n r.warnings.push(...result.warnings.map(w => (w.path ? `${w.path}: ${w.message}` : w.message)))\n if (!result.ok) {\n status(r, 'failed', result.errors.map(e => (e.path ? `${e.path}: ${e.message}` : e.message)).join('; '))\n continue\n }\n r.definition = result.definition\n if (taken.has(id)) {\n status(r, 'failed', `Duplicate extension id \"${id}\" ignored; the earlier one wins.`)\n continue\n }\n taken.add(id)\n }\n const loadable = fresh.filter(r => r.definition && r.info.error === undefined)\n const resolved = resolveLoadOrder([...known.filter(r => r.definition), ...loadable].map(r => ({\n id: r.id,\n ...(r.definition!.version !== undefined ? { version: r.definition!.version } : {}),\n ...(r.definition!.dependencies ? { dependencies: r.definition!.dependencies } : {}),\n r,\n })))\n for (const issue of resolved.issues) {\n const about = issue.kind === 'cycle' ? issue.brokenAt : issue.id\n const r = loadable.find(x => x.id === about)\n if (r && issue.kind !== 'duplicate') {\n r.warnings.push(issueText(issue))\n logger.warn(issueText(issue), { extension: about })\n }\n }\n const loadIds = new Set(loadable.map(r => r.id))\n return { fresh, sequence: resolved.order.filter(e => loadIds.has(e.id)).map(e => e.r), issues: resolved.issues }\n}\n\n/** A record as hosts see it. */\nfunction view(r: MutableRecord): RuntimeExtension {\n return {\n id: r.id,\n entry: r.entry,\n ...(r.definition ? { definition: r.definition } : {}),\n info: r.info,\n ...(r.guard ? { guard: r.guard } : {}),\n ...(r.settings ? { settings: r.settings } : {}),\n warnings: r.warnings,\n }\n}\n\n/** Loads one session's storage for every active record; failures are logged. */\nasync function preloadSessions(records: readonly MutableRecord[], sessionId: string, logger: Logger): Promise<void> {\n await Promise.all(records.map(async (r) => {\n try {\n await r.storage?.preload('session', sessionId)\n }\n catch (error) {\n logger.warn('session storage could not be loaded', { extension: r.id, sessionId, error: String(error) })\n }\n }))\n}\n\n/**\n * Ends a record's active state: its owner is disposed (registrations\n * withdrawn, cleanups run) and its async cleanups get the unload bound; one\n * still running then is logged and left alone. Called again while that runs\n * (an unload after the guard tripped), it waits for the same teardown.\n * `withdrawn` is told before an active owner's registrations go.\n */\nfunction deactivateRecord(r: MutableRecord, logger: Logger, withdrawn: () => void): Promise<void> {\n const owner = r.owner\n r.owner = undefined\n r.guard = undefined\n r.settings = undefined\n r.storage = undefined\n if (!owner) {\n r.agent.clear()\n r.host.clear()\n return r.deactivating ?? Promise.resolve()\n }\n withdrawn()\n owner.dispose()\n // Calls in flight: the teardown comes once they end. A reload goes on now; a runtime dispose waits for it.\n if (owner.draining)\n r.teardown = awaitTeardown(owner, r.id, logger)\n r.deactivating = (async () => {\n const outcome = await unloadOwner(owner)\n if (!outcome.ok)\n logger.warn(`unload: ${outcome.error}`, { extension: r.id })\n r.agent.clear()\n r.host.clear()\n })()\n return r.deactivating\n}\n\n/**\n * Waits for a draining owner's teardown: it runs once its calls in flight\n * ended (bounded by the drain bound), then its async cleanups get the unload bound.\n */\nfunction awaitTeardown(owner: RuntimeOwner, id: string, logger: Logger): Promise<void> {\n return new Promise((resolve) => {\n // The unload bound starts with the teardown (the owner aborts its signal then), not later.\n const started = (): void => {\n void settleWithin(owner.settled).then((outcome) => {\n if (!outcome.ok)\n logger.warn(`unload: ${outcome.error}`, { extension: id })\n resolve()\n })\n }\n if (owner.tornDown)\n started()\n else\n owner.signal.addEventListener('abort', started, { once: true })\n })\n}\n\n/**\n * One extension's guard and root owner. Every guarded call holds a lease on\n * the owner, and the owner logs a deferred teardown on the extension's logger.\n */\nfunction createGuardedOwner(id: string, logger: Logger, stalls: StallMonitor, options: ExtensionRuntimeOptions, onTrip: (trip: GuardTrip, guard: RuntimeGuard) => void): { guard: RuntimeGuard, owner: RuntimeOwner } {\n let owner: RuntimeOwner | undefined\n const guard: RuntimeGuard = createGuard({\n extensionId: id,\n logger,\n stalls,\n ...(options.budget !== undefined ? { budget: options.budget } : {}),\n ...(options.callbackTimeoutMs !== undefined ? { timeoutMs: options.callbackTimeoutMs } : {}),\n // Set below, before any callback runs.\n lease: (label, leaseOpts) => owner!.lease(label, leaseOpts),\n onTrip: trip => onTrip(trip, guard),\n })\n const track = options.trackCalls\n if (track) {\n const call = guard.call\n guard.call = (label, fn, opts) => {\n const pending = call(label, fn, opts)\n track(pending)\n return pending\n }\n }\n owner = createOwner(undefined, {\n onError: (error, label) => guard.report(label, error),\n label: id,\n ...(options.drainTimeoutMs !== undefined ? { drainMs: options.drainTimeoutMs } : {}),\n onDrain: ({ active, ms }) => logger.warn(`unloaded with ${active.length} call${active.length === 1 ? '' : 's'} in flight (${active.join(', ')}): its registrations are withdrawn, the rest is torn down once they finish (at most ${Math.round(ms / 1000)}s)`, { active, boundMs: ms }),\n onDrainTimeout: ({ active, ms }) => logger.warn(`calls still running ${Math.round(ms / 1000)}s after unload (${active.join(', ')}): tearing down now`, { active }),\n })\n return { guard, owner }\n}\n\n/** Runs async work one at a time, in call order; a failure does not stop the next. */\nfunction createSerial(): <T>(work: () => Promise<T>) => Promise<T> {\n let queue: Promise<unknown> = Promise.resolve()\n return <T>(work: () => Promise<T>): Promise<T> => {\n const next = queue.then(work, work)\n queue = next.catch(() => undefined)\n return next\n }\n}\n\n/** What {@link reloadInPlace} needs of the runtime. */\ninterface ReloadContext {\n records: Map<string, MutableRecord>\n order: readonly string[]\n removeUi: (id: string) => void\n logger: Logger\n reimport: (entry: RuntimeEntry) => Promise<RuntimeEntry>\n disposed: () => boolean\n withdrawn: () => void\n setStatus: (r: MutableRecord, status: ExtensionInfo['status'], error?: string) => void\n activate: (r: MutableRecord) => Promise<void>\n unload: (id: string) => Promise<void>\n load: (entries: readonly RuntimeEntry[]) => Promise<readonly ExtensionInfo[]>\n}\n\n/** {@link ExtensionRuntime.reload}: the record is replaced at its place in the load order. */\nasync function reloadInPlace(c: ReloadContext, id: string, opts: { entry?: RuntimeEntry }): Promise<ExtensionInfo | undefined> {\n const r = c.records.get(id)\n if (!r || c.disposed())\n return undefined\n let entry = opts.entry\n if (!entry) {\n try {\n entry = await c.reimport(r.entry)\n }\n catch (error) {\n entry = { ...r.entry, definition: undefined, error: `Failed to import: ${error instanceof Error ? error.message : String(error)}` }\n }\n }\n if (entry.enabled === undefined && r.entry.enabled !== undefined)\n entry = { ...entry, enabled: r.entry.enabled }\n await deactivateRecord(r, c.logger, c.withdrawn)\n c.removeUi(id)\n if (c.disposed() || c.records.get(id) !== r)\n return undefined\n const known = c.order.filter(other => other !== id).map(other => c.records.get(other)!)\n const prepared = prepareLoad([entry], known, c.setStatus, c.logger)\n const next = prepared.fresh[0]!\n if (next.id !== id) {\n // The module now declares another id: the old one goes, the new one loads after the others.\n await c.unload(id)\n const [info] = await c.load([entry])\n return info\n }\n c.records.set(id, next)\n if (!prepared.sequence.includes(next))\n return next.info\n for (const warning of next.warnings)\n c.logger.warn(warning, { extension: id })\n if (entry.enabled === false) {\n c.setStatus(next, 'disabled')\n return next.info\n }\n await c.activate(next)\n return next.info\n}\n\n/**\n * The default {@link ExtensionRuntimeOptions.reimport}: an entry with a\n * folder is imported fresh from it; any other keeps its definition.\n * Discovery is loaded on first use, so a host that never reloads never\n * pays for it.\n */\nfunction defaultReimport(): (entry: RuntimeEntry) => Promise<RuntimeEntry> {\n return async (entry) => {\n if (entry.dir === undefined || entry.source === 'inline' || entry.source === 'builtin')\n return entry\n const [{ loadExtensionFolder }, { runtimeEntryOf }] = await Promise.all([import('../discovery'), import('./loaded-entry')])\n const loaded = await loadExtensionFolder(entry.dir, { source: entry.source === 'project' ? 'project' : 'user' })\n return { ...runtimeEntryOf(loaded, entry.enabled), source: entry.source }\n }\n}\n\n/**\n * Creates the extension runtime of one host.\n *\n * @param options - Host kind, paths, ports and guard settings.\n * @returns The runtime.\n */\nexport function createExtensionRuntime(options: ExtensionRuntimeOptions): ExtensionRuntime {\n const ports = options.ports ?? {}\n const baseLogger = options.logger ?? createLogger(consoleSink({ minLevel: 'warn' }))\n const memory = options.memory ?? processMemory\n const storagePort = ports.storage ?? createMemoryStoragePort()\n const settingsPort = ports.settings ?? createMemorySettingsPort()\n const records = new Map<string, MutableRecord>()\n const order: string[] = []\n let issues: readonly LoadOrderIssue[] = []\n let disposed = false\n\n const rank = (id: string): number => {\n const at = order.indexOf(id)\n return at === -1 ? Number.MAX_SAFE_INTEGER : at\n }\n\n const { outputs, services, hostListeners, refreshObservers, artifactKinds, pluginRecords, changed, statusChanged, subscribe, changeListeners, rpcBridge, release, withdrawn } = createShared(options, ports, baseLogger, records, order, rank)\n const { ui } = outputs\n\n const stalls = createStallMonitor({\n onStall: (report) => {\n baseLogger.warn(`${report.label} blocked the event loop for ${Math.round(report.durationMs)}ms`, { extension: report.extensionId, label: report.label, durationMs: report.durationMs })\n options.onStall?.(report)\n },\n })\n\n const setStatus = (r: MutableRecord, status: ExtensionInfo['status'], error?: string): void => {\n const def = r.definition\n const manifest = r.entry.manifest\n const icon = def?.icon ?? manifest?.icon\n r.info = {\n id: r.id,\n displayName: def?.displayName ?? manifest?.displayName ?? r.id,\n ...(icon !== undefined ? { icon: { ...icon } } : {}),\n ...(def?.version !== undefined ? { version: def.version } : {}),\n source: r.entry.source,\n status,\n ...(error !== undefined ? { error } : {}),\n }\n statusChanged(r.info)\n }\n\n const activate = async (r: MutableRecord): Promise<void> => {\n const def = r.definition!\n const logger = baseLogger.with({ extension: r.id })\n const { guard, owner } = createGuardedOwner(r.id, logger, stalls, options, (trip, tripped) => {\n if (r.guard !== tripped)\n return\n setStatus(r, 'failed', `Disabled: ${trip.reason}`)\n void deactivateRecord(r, baseLogger, withdrawn)\n })\n const deps: DomainDeps = { extensionId: r.id, owner, guard, logger }\n const settings = createSettingsDomain(deps, settingsPort, def.settings)\n const storage = createStorageDomain(deps, storagePort, {\n paths: options.paths,\n ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}),\n memory,\n ...(ports.currentSessionId ? { currentSessionId: ports.currentSessionId } : {}),\n })\n r.guard = guard\n r.owner = owner\n r.settings = settings\n r.storage = storage\n const preloaded = await Promise.allSettled([storage.preload('user'), storage.preload('project')])\n for (const result of preloaded) {\n if (result.status === 'rejected')\n logger.warn('storage could not be loaded before setup; reads start empty', { error: String(result.reason) })\n }\n const hooks = createHooksPort(r, ports, hostListeners, refreshObservers, changed)\n const input = {\n definition: def,\n source: r.entry.source,\n ...(r.entry.dir !== undefined ? { dir: r.entry.dir } : {}),\n paths: options.paths,\n logger,\n guard,\n hooks,\n storage,\n settings,\n }\n const outcome = await runSetup(def, o => createExtensionContext(input, services, o), owner, guard, {\n ...(options.setupTimeoutMs !== undefined ? { timeoutMs: options.setupTimeoutMs } : {}),\n })\n if (r.owner !== owner)\n return\n if (!outcome.ok) {\n logger.error('setup failed', { reason: outcome.reason, error: outcome.error })\n r.owner = undefined\n r.guard = undefined\n r.settings = undefined\n r.storage = undefined\n r.agent.clear()\n r.host.clear()\n setStatus(r, 'failed', outcome.error)\n return\n }\n for (const warning of outcome.warnings)\n logger.warn(warning)\n if (guard.tripped)\n return\n setStatus(r, 'active')\n }\n\n // load, unload and reload run one at a time: a reload racing a load would see half-built records.\n const serial = createSerial()\n\n const loadNow = async (entries: readonly RuntimeEntry[]): Promise<readonly ExtensionInfo[]> => {\n if (disposed)\n return []\n const prepared = prepareLoad(entries, order.map(id => records.get(id)!), setStatus, baseLogger)\n const { fresh, sequence } = prepared\n issues = prepared.issues\n\n // Failed records are listed too (Settings shows them), after the loadable ones.\n for (const r of sequence) {\n records.set(r.id, r)\n order.push(r.id)\n }\n for (const r of fresh) {\n if (!sequence.includes(r) && !records.has(r.id)) {\n records.set(r.id, r)\n order.push(r.id)\n }\n }\n for (const r of sequence) {\n if (disposed)\n break\n for (const warning of r.warnings)\n baseLogger.warn(warning, { extension: r.id })\n if (r.entry.enabled === false) {\n setStatus(r, 'disabled')\n continue\n }\n await activate(r)\n }\n return fresh.map(r => r.info)\n }\n\n const unloadNow = async (id: string, opts: { forget?: boolean } = {}): Promise<void> => {\n const r = records.get(id)\n if (!r)\n return\n records.delete(id)\n order.splice(order.indexOf(id), 1)\n await deactivateRecord(r, baseLogger, withdrawn)\n ui.removeExtension(id)\n if (opts.forget) {\n memory.clear(id)\n // Uninstalled: hosts delete its stored facet values (a plain unload keeps them).\n services.facets.forget(id)\n }\n statusChanged({ id, status: 'unloaded' })\n }\n\n const reimport = options.reimport ?? defaultReimport()\n const reloadContext: ReloadContext = { records, order, removeUi: id => ui.removeExtension(id), logger: baseLogger, reimport, disposed: () => disposed, withdrawn, setStatus, activate, unload: unloadNow, load: loadNow }\n\n return {\n load: entries => serial(() => loadNow(entries)),\n unload: (id, opts) => serial(() => unloadNow(id, opts)),\n reload: (id, opts) => serial(() => reloadInPlace(reloadContext, id, opts ?? {})),\n idOfDir: dir => order.find(id => records.get(id)?.entry.dir === dir),\n outputs,\n extensions: () => services.extensions.list().slice(),\n get: (id) => {\n const r = records.get(id)\n return r ? view(r) : undefined\n },\n settingsWire: () => runtimeSettingsWire({ extensions: () => order.map(id => ({ id })), get: id => records.get(id), outputs }),\n preloadSession: sessionId => preloadSessions(order.map(id => records.get(id)!), sessionId, baseLogger),\n checkStorageWrite: async (loc, area, key, value) => records.get(loc.extensionId)?.storage?.checkWrite(loc, area, key, value),\n hookHandlers: (id) => {\n const r = records.get(id)\n return { agent: r?.agent ?? new Map(), host: r?.host ?? new Map() }\n },\n artifactKinds: id => artifactKinds.filter(e => e.extensionId === id),\n plugins: id => pluginRecords.filter(p => p.extensionName === id),\n subscribe,\n hostWired: { agentHooks: ports.hooks?.agentHooks !== undefined, hostEvents: ports.hooks?.emitsHostEvents === true },\n ...(rpcBridge ? { rpcBridge } : {}),\n get issues() { return issues },\n dispose: async () => {\n if (disposed)\n return\n disposed = true\n withdrawn()\n // Before the extensions go: their facets withdrawn by a dispose must not read as withdrawn by the extension (the host would prune their values).\n services.facets.close()\n const all = [...order].reverse().map(id => records.get(id)!)\n await Promise.all(all.map(r => deactivateRecord(r, baseLogger, withdrawn)))\n for (const r of all)\n ui.removeExtension(r.id)\n records.clear()\n order.length = 0\n changeListeners.clear()\n // The shared registries (dialogs, commands, RPC) serve the calls still in flight: released once every extension tore down.\n await Promise.all(all.map(r => r.teardown))\n release()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;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