@zapier/kitcore 0.0.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/registry.ts","../src/utils/string-utils.ts","../src/utils/build-hooks.ts","../src/utils/logging.ts","../src/types/errors.ts","../src/utils/pagination-utils.ts","../src/utils/validation.ts","../src/utils/async-context.ts","../src/utils/method-scope.ts","../src/utils/function-utils.ts","../src/utils/plugin-utils.ts","../src/model/shared.ts","../src/model/types.ts","../src/model/define.ts","../src/model/exports.ts","../src/model/legacy.ts","../src/model/builtins.ts","../src/model/registry-support.ts","../src/model/materialize.ts","../src/model/resolution/controller.ts","../src/types/signals.ts","../src/model/resolution/plan.ts","../src/model/resolution/engine.ts","../src/utils/core-plugin.ts","../src/utils/schema-utils.ts"],"sourcesContent":["// Zod metadata augmentation; imported as a side-effect.\nimport \"./types/meta\";\n\nexport {\n createPluginMethod,\n createPaginatedPluginMethod,\n composePlugins,\n createPluginStack,\n} from \"./utils/plugin-utils\";\nexport type { PluginStack } from \"./utils/plugin-utils\";\n\n// Node-plugin model (src/model). The heads build on `createSdk` and bridge\n// their legacy function-plugin stacks in with `fromFunctionPlugin`. The full\n// authoring surface (`defineMethod` / `definePlugin` / etc.) is exported here.\nexport {\n addPlugin,\n CONTEXT,\n createSdk,\n fromFunctionPlugin,\n defineLegacyMerge,\n dangerousContextPlugin,\n getRegistryPlugin,\n getContext,\n // The authoring surface. `definePlugin` is a single function with two forms:\n // an object builds a new-model aggregate, a function is the legacy\n // function-plugin identity wrapper (the existing ~90 plugins).\n definePlugin,\n declarePlugin,\n defineMethod,\n defineResolver,\n defineFormatter,\n defineProperty,\n declareMethod,\n declareProperty,\n selectExports,\n // The resolution controller: a sibling layer over a built SDK that drives\n // parameter resolution (CLI / web / agent / MCP hosts).\n createController,\n} from \"./model\";\nexport type {\n LegacyPlugin,\n LegacyMergePlugin,\n SdkContext,\n LeafMeta,\n MethodPlugin,\n PropertyPlugin,\n AggregatePlugin,\n MethodAttachment,\n Formatter,\n // `Resolver` (the descriptor from defineResolver) stays internal during the\n // transition: the package already exports a legacy `Resolver` from\n // schema-utils, and two public `Resolver`s would collide. `Formatter` /\n // `MethodAttachment` have no such clash, and a head needs `Formatter` to be\n // nameable to declare a `defineFormatter` result.\n BoundResolver,\n BoundFormatter,\n ResolverType,\n ListItemsResult,\n PluginSummary,\n // Resolution controller surface.\n Controller,\n ControllerSdk,\n ControllerState,\n ControllerResult,\n ControllerError,\n ControllerIssue,\n ControllerQuestion,\n ControllerAction,\n ControllerListing,\n ControllerAnswerFn,\n ControllerParameterDescription,\n ControllerMethodSummary,\n ControllerMethodDescription,\n ControllerAffordance,\n ControllerChoice,\n ControllerPath,\n} from \"./model\";\n\nexport {\n createFunction,\n createPaginatedFunction,\n} from \"./utils/function-utils\";\n\nexport { createCorePlugin } from \"./utils/core-plugin\";\nexport type { CoreOptions } from \"./utils/core-plugin\";\n\nexport type {\n MethodHooks,\n OnMethodStart,\n OnMethodEnd,\n OnMethodStartContext,\n OnMethodEndContext,\n} from \"./utils/build-hooks\";\n\nexport {\n getCurrentDepth,\n getCurrentScope,\n isNestedMethodCall,\n runInMethodScope,\n // Back-compat aliases for the previous names.\n isTelemetryNested,\n runWithTelemetryContext,\n} from \"./utils/method-scope\";\nexport type { MethodScope } from \"./utils/method-scope\";\n\nexport { createAsyncContext } from \"./utils/async-context\";\nexport type { AsyncContext } from \"./utils/async-context\";\n\nexport { createValidator, validateOptions } from \"./utils/validation\";\n\nexport * from \"./utils/pagination-utils\";\n\n// Only the transforms a head package actually consumes are published;\n// the rest of string-utils (pluralize, pluralizeLastWord, stripPageSuffix)\n// stays internal to kitcore.\nexport { toSnakeCase, toTitleCase } from \"./utils/string-utils\";\n\nexport * from \"./utils/schema-utils\";\n\nexport { createDeprecationLogger } from \"./utils/logging\";\nexport type { DeprecationLogger } from \"./utils/logging\";\n\nexport type { Plugin, PluginMeta, PluginProvides, Sdk } from \"./types/plugin\";\n\nexport type {\n SdkPage,\n PaginatedSdkResult,\n PaginatedSdkFunction,\n} from \"./types/pagination\";\n\nexport type {\n CategoryDefinition,\n FunctionRegistryEntry,\n FunctionDeprecation,\n RegistryResult,\n} from \"./types/registry\";\n\nexport {\n CORE_ERROR_SYMBOL,\n CoreErrorCode,\n CoreError,\n createCoreError,\n isCoreError,\n getCoreErrorCode,\n getCoreErrorCause,\n} from \"./types/errors\";\nexport type {\n CoreApiError,\n CoreErrorOptions,\n AdaptErrorOptions,\n AdaptError,\n} from \"./types/errors\";\n\n// Signals: intentional control-flow throws (the sibling of errors).\nexport {\n CORE_SIGNAL_SYMBOL,\n CoreSignal,\n CoreCancelledSignal,\n isCoreSignal,\n} from \"./types/signals\";\n","import { z } from \"zod\";\nimport type { PluginMeta } from \"./types/plugin\";\nimport type { CategoryDefinition, RegistryResult } from \"./types/registry\";\nimport type { BoundFormatter, BoundResolver } from \"./model/types\";\nimport { pluralizeLastWord, toTitleCase } from \"./utils/string-utils\";\n\nexport type { RegistryResult } from \"./types/registry\";\n\n/**\n * Resolve a category reference (a bare key or an object) to a fully populated\n * definition. Any field absent on the object form (and everything, for a bare\n * key) is auto-derived: title via toTitleCase, titlePlural via\n * pluralizeLastWord. Explicit fields win, and titlePlural derives from the\n * resolved title (not the bare key), so an overridden \"HTTP Request\"\n * pluralizes to \"HTTP Requests\".\n *\n * Auto-derive gets two-letter acronyms (`http` → `Http`) and irregular plurals\n * (`child` → `childs`) wrong on purpose; categories that need a different title\n * supply it explicitly, e.g. `{ key: \"http\", title: \"HTTP Request\" }`.\n */\nfunction resolveCategoryDefinition(\n ref: string | CategoryDefinition,\n): Required<CategoryDefinition> {\n const def = typeof ref === \"string\" ? { key: ref } : ref;\n const title = def.title ?? toTitleCase(def.key);\n return {\n key: def.key,\n title,\n titlePlural: def.titlePlural ?? pluralizeLastWord(title),\n };\n}\n\n/**\n * Plugins with deprecated parameter aliases declare two schemas: a canonical\n * one (new names only, with `.meta({ aliases })` declarations) and a union\n * of the canonical + a deprecated variant for runtime input parsing. The\n * union form is what `createPluginMethod` stores in plugin meta so SDK\n * callers passing deprecated names keep validating; for the registry — and\n * all downstream consumers (command help, tool/RPC definitions, generated\n * docs) — we want only the canonical.\n *\n * Convention: when a plugin's `inputSchema` is a `z.ZodUnion`, the first\n * variant is the canonical schema. Every plugin that uses unions today\n * follows this; explicit, easy to enforce, no extra metadata needed.\n */\nfunction canonicalInputSchema(\n schema: z.ZodSchema | undefined,\n): z.ZodSchema | undefined {\n if (schema instanceof z.ZodUnion) {\n return schema.options[0] as z.ZodSchema;\n }\n return schema;\n}\n\nexport function buildRegistry({\n sdk,\n meta,\n formatters,\n boundResolvers,\n positional,\n packageFilter,\n}: {\n sdk: Record<string, unknown>;\n meta: Record<string, PluginMeta>;\n /** Per-binding bound formatters, normalized by the caller (the surface\n * builder, which has the entries + sdk). The formatter is a bound runtime\n * thing, not descriptive meta, so it's supplied separately rather than read\n * off `PluginMeta`. */\n formatters?: Record<string, BoundFormatter>;\n /** Per-binding bound resolvers from the new model, lifted off materialized\n * method entries by the caller (like `formatters`). A bound runtime thing,\n * not descriptive meta, so supplied separately rather than read off\n * `PluginMeta` (which carries only legacy `resolvers`). */\n boundResolvers?: Record<string, Record<string, BoundResolver>>;\n /** Per-binding positional projections, lifted off materialized method entries\n * by the caller (like `boundResolvers`). A runtime projection, not meta. */\n positional?: Record<string, readonly string[]>;\n packageFilter?: string;\n}): RegistryResult {\n // Collect category definitions across every plugin's meta. Object-form\n // refs win over string-form so explicit titles override auto-derive;\n // among multiple object refs for the same key, last-write-wins. \"other\"\n // is auto-included so functions with no categories still get a home.\n const definitionsByKey = new Map<string, Required<CategoryDefinition>>();\n const objectDeclaredKeys = new Set<string>();\n for (const m of Object.values(meta)) {\n for (const ref of m.categories ?? []) {\n const key = typeof ref === \"string\" ? ref : ref.key;\n if (typeof ref === \"object\") {\n objectDeclaredKeys.add(key);\n definitionsByKey.set(key, resolveCategoryDefinition(ref));\n } else if (!objectDeclaredKeys.has(key)) {\n definitionsByKey.set(key, resolveCategoryDefinition(ref));\n }\n }\n }\n if (!definitionsByKey.has(\"other\")) {\n definitionsByKey.set(\"other\", resolveCategoryDefinition(\"other\"));\n }\n const knownCategories = Array.from(definitionsByKey.keys());\n\n const functions = Object.keys(meta)\n .filter((key) => {\n const property = sdk[key];\n if (typeof property === \"function\") return true;\n const [rootKey] = key.split(\".\");\n const rootProperty = sdk[rootKey];\n return typeof rootProperty === \"object\" && rootProperty !== null;\n })\n .map((key) => {\n const m = meta[key];\n return {\n name: key,\n description: m.description,\n type: m.type,\n itemType: m.itemType,\n returnType: m.returnType,\n inputSchema: canonicalInputSchema(m.inputSchema),\n inputParameters: m.inputParameters,\n outputSchema: m.outputSchema,\n positional: positional?.[key],\n categories: (m.categories ?? []).map((c) =>\n typeof c === \"string\" ? c : c.key,\n ),\n resolvers: m.resolvers,\n boundResolvers: boundResolvers?.[key],\n formatter: formatters?.[key],\n experimental: m.experimental,\n packages: m.packages,\n confirm: m.confirm ?? (m.type === \"delete\" ? \"delete\" : undefined),\n deprecation: m.deprecation,\n aliases: m.aliases,\n supportsJsonOutput: m.supportsJsonOutput ?? true,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n\n const filteredFunctions = packageFilter\n ? functions.filter((f) => !f.packages || f.packages.includes(packageFilter))\n : functions;\n\n const filteredCategories = knownCategories\n .slice()\n .sort((a, b) => {\n if (a === \"other\") return 1;\n if (b === \"other\") return -1;\n return definitionsByKey\n .get(a)!\n .title.localeCompare(definitionsByKey.get(b)!.title);\n })\n .map((categoryKey) => {\n const categoryFunctions = filteredFunctions\n .filter(\n (f) =>\n f.categories.includes(categoryKey) ||\n (categoryKey === \"other\" &&\n !f.categories.some((c) => knownCategories.includes(c))),\n )\n .map((f) => f.name)\n .sort();\n\n const def = definitionsByKey.get(categoryKey)!;\n return {\n key: categoryKey,\n title: def.title,\n titlePlural: def.titlePlural,\n functions: categoryFunctions,\n };\n })\n .filter((category) => category.functions.length > 0);\n\n return { functions: filteredFunctions, categories: filteredCategories };\n}\n","/**\n * Generic string utilities used by the plugin framework.\n */\n\n/**\n * Converts a string to title case, handling various input formats:\n * - camelCase: \"firstName\" → \"First Name\"\n * - snake_case: \"first_name\" → \"First Name\"\n * - kebab-case: \"first-name\" → \"First Name\"\n * - mixed formats: \"first_name-value\" → \"First Name Value\"\n */\nexport function toTitleCase(input: string): string {\n return (\n input\n // insert a space before capital letters (handles camelCase)\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n // replace delimiters (underscore, dash, multiple spaces) with single space\n .replace(/[_\\-]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n // split and capitalize each word\n .split(\" \")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \")\n );\n}\n\n/**\n * Converts a string to snake_case, handling various input formats:\n * - camelCase: \"firstName\" → \"first_name\"\n * - kebab-case: \"first-name\" → \"first_name\"\n * - title case: \"First Name\" → \"first_name\"\n * - mixed formats: \"first-Name Value\" → \"first_name_value\"\n * - starts with number: \"123abc\" → \"_123abc\"\n */\nexport function toSnakeCase(input: string): string {\n let result = input\n // insert underscore before capital letters (handles camelCase)\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n // replace spaces and dashes with underscores\n .replace(/[\\s\\-]+/g, \"_\")\n // replace multiple underscores with single underscore\n .replace(/_+/g, \"_\")\n // remove leading/trailing underscores and convert to lowercase\n .replace(/^_|_$/g, \"\")\n .toLowerCase();\n\n // If the result starts with a number, prefix with underscore\n if (/^[0-9]/.test(result)) {\n result = \"_\" + result;\n }\n\n return result;\n}\n\n/**\n * Naive English pluralization, sufficient for auto-deriving category titles\n * from category keys. Three cases:\n * - already ends in \"s\" → unchanged (so \"credentials\" stays \"credentials\")\n * - consonant + \"y\" → \"ies\" (so \"utility\" → \"utilities\")\n * - everything else → adds \"s\" (so \"app\" → \"apps\")\n *\n * Irregular plurals (children, mice) and acronyms come out wrong. Callers\n * that care should supply an explicit title rather than rely on this.\n */\nfunction pluralize(word: string): string {\n if (/s$/i.test(word)) return word;\n if (/[bcdfghjklmnpqrstvwxz]y$/i.test(word)) {\n return word.slice(0, -1) + \"ies\";\n }\n return word + \"s\";\n}\n\n/**\n * Pluralize only the last whitespace-separated word in a title, leaving\n * earlier words unchanged. So \"Client Credentials\" stays as-is (already\n * ends in \"s\") and \"HTTP Request\" becomes \"HTTP Requests\".\n */\nexport function pluralizeLastWord(title: string): string {\n const words = title.split(\" \");\n return [...words.slice(0, -1), pluralize(words[words.length - 1])].join(\" \");\n}\n\n/**\n * Strips the \"Page\" suffix from a function name, used for deriving method names\n * from paginated function implementations.\n *\n * This is commonly used with `createPaginatedFunction` where the internal function\n * has a \"Page\" suffix (e.g., \"listAppsPage\") but the public method name should not\n * (e.g., \"listApps\").\n *\n * @param functionName - The function name, typically from `function.name`\n * @returns The function name with \"Page\" suffix removed, or original if no suffix\n *\n * @example\n * ```typescript\n * stripPageSuffix(\"listAppsPage\") // \"listApps\"\n * stripPageSuffix(\"listApps\") // \"listApps\" (no change)\n * stripPageSuffix(\"myPageFunction\") // \"myPageFunction\" (only strips from end)\n * ```\n */\nexport function stripPageSuffix(functionName: string): string {\n return functionName.replace(/Page$/, \"\");\n}\n","/**\n * Method-call lifecycle hooks. Plugins contribute `onMethodStart` and/or\n * `onMethodEnd` on their context; `buildHooks` composes contributions across\n * plugins so multiple observers can coexist. Composition is right-additive\n * (newer plugins fire after earlier ones); only opt-in methods built through\n * `createPluginMethod` / `createPaginatedPluginMethod` trigger the hooks.\n */\n\nexport interface OnMethodStartContext {\n methodName: string;\n args: unknown[];\n isPaginated: boolean;\n /**\n * Depth of this method invocation in the SDK call tree. 0 = outermost\n * (user-initiated) call; 1+ = called from inside another SDK method.\n * Observers can use this to ignore nested calls if they only want\n * top-level events.\n */\n depth: number;\n}\n\nexport type OnMethodStart = (ctx: OnMethodStartContext) => void;\n\nexport interface OnMethodEndContext {\n methodName: string;\n args: unknown[];\n isPaginated: boolean;\n depth: number;\n durationMs: number;\n error?: Error;\n}\n\nexport type OnMethodEnd = (ctx: OnMethodEndContext) => void;\n\nexport interface MethodHooks {\n onMethodStart?: OnMethodStart;\n onMethodEnd?: OnMethodEnd;\n}\n\n/**\n * Compose two same-shaped observer hooks into one that runs `existing`\n * then `added`. Returns the lone defined side when only one is set, or\n * `undefined` when neither is. Every method hook is a fire-and-forget\n * `(ctx) => void` observer, so this one generic covers them all.\n */\nfunction composeVoid<C>(\n existing: ((ctx: C) => void) | undefined,\n added: ((ctx: C) => void) | undefined,\n): ((ctx: C) => void) | undefined {\n if (!existing) return added;\n if (!added) return existing;\n return (ctx) => {\n existing(ctx);\n added(ctx);\n };\n}\n\n/**\n * Compose hook fields from two contexts. Returns only the keys that have a\n * defined value so callers can spread without polluting the merged context\n * with explicit `undefined`s.\n *\n * One explicit line per hook, not a key-driven loop: a loop keyed by the\n * `keyof MethodHooks` union loses the per-key context correlation, so the\n * composer call and the assignment back force an `unknown` cast that drops\n * the very type checking the loop was meant to preserve. Adding a hook is\n * its field on `MethodHooks` plus one line here.\n */\nexport function buildHooks(\n existing: MethodHooks,\n added: MethodHooks,\n): MethodHooks {\n const result: MethodHooks = {};\n const start = composeVoid(existing.onMethodStart, added.onMethodStart);\n if (start) result.onMethodStart = start;\n const end = composeVoid(existing.onMethodEnd, added.onMethodEnd);\n if (end) result.onMethodEnd = end;\n return result;\n}\n","export interface DeprecationLogger {\n logDeprecation(message: string): void;\n resetDeprecationWarnings(): void;\n}\n\n/**\n * Create a package-tagged deprecation logger. Each logger tracks its own\n * once-per-process message Set, so package heads can keep independent warning\n * channels while sharing the implementation.\n */\nexport function createDeprecationLogger(tag: string): DeprecationLogger {\n const loggedDeprecations = new Set<string>();\n\n return {\n logDeprecation(message: string): void {\n if (loggedDeprecations.has(message)) return;\n loggedDeprecations.add(message);\n\n console.warn(`[${tag}] Deprecation: ${message}`);\n },\n\n resetDeprecationWarnings(): void {\n loggedDeprecations.clear();\n },\n };\n}\n\nexport const { logDeprecation, resetDeprecationWarnings } =\n createDeprecationLogger(\"core\");\n","/**\n * Core error machinery.\n *\n * kitcore constructs errors at two internal throw sites: input\n * validation (`utils/validation.ts`) and non-Error normalization\n * (`utils/function-utils.ts`'s `normalizeError`). Heads supply a\n * `adaptError` factory via `createCorePlugin` to map kitcore's abstract\n * `CoreErrorCode` values onto their own branded error classes; if\n * no factory is supplied, kitcore falls back to constructing a plain\n * `CoreError`. Either way, every kitcore-thrown error is brand-stamped\n * with `CORE_ERROR_SYMBOL` and `coreCode` (non-enumerable),\n * so consumers can recognize core errors via `isCoreError`\n * without knowing the head's class identity.\n */\n\n/**\n * Cross-package brand for kitcore-constructed errors. `Symbol.for(key)`\n * reads from the engine-global registry, so the same value resolves\n * across realms and across multiple copies of kitcore (e.g. when one\n * package bundles kitcore and another installs it standalone). Use\n * `isCoreError` for cross-package checks.\n */\nexport const CORE_ERROR_SYMBOL = Symbol.for(\"kitcore.error\");\n\n/**\n * Abstract codes for the errors kitcore can produce. Heads receive these\n * via `AdaptErrorOptions.code` and map them onto their own named\n * error classes (e.g. `VALIDATION_ERROR` → the head's branded\n * `<Prefix>ValidationError`).\n */\nexport const CoreErrorCode = {\n Validation: \"VALIDATION_ERROR\",\n Unknown: \"UNKNOWN_ERROR\",\n} as const;\nexport type CoreErrorCode = (typeof CoreErrorCode)[keyof typeof CoreErrorCode];\n\n/**\n * Standard error envelope. kitcore doesn't generate these\n * itself; heads set `errors?: CoreApiError[]` on their error constructor\n * options when surfacing structured upstream failures.\n */\nexport interface CoreApiError {\n status: number;\n code: string;\n title: string;\n detail: string;\n source?: unknown;\n meta?: unknown;\n}\n\n/**\n * Base options for the default `CoreError` fallback. Heads' own error\n * classes typically accept a richer options bag.\n */\nexport interface CoreErrorOptions {\n statusCode?: number;\n errors?: CoreApiError[];\n cause?: unknown;\n response?: unknown;\n}\n\n/**\n * What `adaptError` factories receive. `code` is the abstract error\n * code; `details` carries type-specific extras (validation issues for\n * `VALIDATION_ERROR`, etc.).\n */\nexport interface AdaptErrorOptions {\n code: CoreErrorCode;\n message: string;\n cause?: unknown;\n details?: unknown;\n}\n\nexport type AdaptError = (options: AdaptErrorOptions) => Error;\n\n/**\n * Default error class kitcore constructs when no `adaptError` is\n * supplied. Heads typically provide their own branded classes via\n * `adaptError` and never see this. Exported so the rare head-less\n * caller (tests, scratch scripts) can recognize the fallback.\n */\nexport class CoreError extends Error {\n readonly name: string = \"CoreError\";\n public statusCode?: number;\n public errors?: CoreApiError[];\n declare public cause?: unknown;\n public response?: unknown;\n\n constructor(message: string, options: CoreErrorOptions = {}) {\n super(message);\n if (options.statusCode !== undefined) this.statusCode = options.statusCode;\n if (options.errors !== undefined) this.errors = options.errors;\n if (options.cause !== undefined) this.cause = options.cause;\n if (options.response !== undefined) this.response = options.response;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Construct a core error, optionally via a head-supplied factory.\n * Stamps the core brand and the abstract `coreCode` on the\n * returned instance (non-enumerable, so they don't pollute JSON\n * serialization). The `instanceof <HeadErrorClass>` check on the\n * result works as expected; `isCoreError` is the cross-package\n * recognizer that survives bundled/standalone splits.\n */\nexport function createCoreError(\n options: AdaptErrorOptions,\n adaptError?: AdaptError,\n): Error {\n const error =\n adaptError?.(options) ??\n new CoreError(options.message, { cause: options.cause });\n Object.defineProperty(error, CORE_ERROR_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(error, \"coreCode\", {\n value: options.code,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return error;\n}\n\n/**\n * Cross-package-safe check that `value` was produced by kitcore's\n * error construction path (i.e. through `createCoreError`). Use\n * this in code that needs to distinguish \"kitcore threw this\" from\n * \"a handler threw an unrelated `Error` subclass\" — `instanceof` checks\n * on specific head classes also work, but `isCoreError` is the\n * neutral recognizer.\n */\nexport function isCoreError(value: unknown): boolean {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as { [k: symbol]: unknown })[CORE_ERROR_SYMBOL] === true,\n );\n}\n\n/**\n * Abstract `CoreErrorCode` for an error produced via\n * `createCoreError`. Returns `undefined` for non-kitcore values.\n */\nexport function getCoreErrorCode(value: unknown): CoreErrorCode | undefined {\n if (!isCoreError(value)) return undefined;\n return (value as { coreCode?: CoreErrorCode }).coreCode;\n}\n\n/**\n * `cause` field accessor that doesn't trip the type system. Same as\n * `(value as { cause?: unknown }).cause` for kitcore-produced errors;\n * returns `undefined` for non-kitcore values.\n */\nexport function getCoreErrorCause(value: unknown): unknown {\n if (!isCoreError(value)) return undefined;\n return (value as { cause?: unknown }).cause;\n}\n","import type { SdkPage } from \"../types/pagination\";\n\n/**\n * Translates a paginated handler's raw response into a normalized\n * `SdkPage<TItem>`. Supplied per method as the `adaptPage` on\n * `createPaginatedPluginMethod` (and forwarded to `createPaginatedFunction`).\n */\nexport type AdaptPage<TResponse = unknown, TItem = unknown> = (\n response: TResponse,\n) => SdkPage<TItem>;\n\nconst CURSOR_VERSION = 1 as const;\n\nconst CURSOR_SOURCE = {\n API: \"api\",\n SDK: \"sdk\",\n} as const;\n\ninterface ApiCursorEnvelope {\n v: typeof CURSOR_VERSION;\n source: typeof CURSOR_SOURCE.API;\n cursor: string;\n}\n\ninterface SdkCursorEnvelope {\n v: typeof CURSOR_VERSION;\n source: typeof CURSOR_SOURCE.SDK;\n cursor: string | undefined;\n offset: number;\n}\n\ntype CursorEnvelope = ApiCursorEnvelope | SdkCursorEnvelope;\n\ntype TPageOptions<TOptions> = TOptions extends undefined\n ? { cursor?: string; maxItems?: number; pageSize?: number }\n : TOptions & { cursor?: string; maxItems?: number; pageSize?: number };\n\nfunction encodeBase64(str: string): string {\n return btoa(\n Array.from(new TextEncoder().encode(str), (b) =>\n String.fromCharCode(b),\n ).join(\"\"),\n );\n}\n\nfunction decodeBase64(str: string): string {\n return new TextDecoder().decode(\n Uint8Array.from(atob(str), (c) => c.charCodeAt(0)),\n );\n}\n\nfunction encodeApiCursor(cursor: string): string {\n const envelope: ApiCursorEnvelope = {\n v: CURSOR_VERSION,\n source: CURSOR_SOURCE.API,\n cursor,\n };\n return encodeBase64(JSON.stringify(envelope));\n}\n\nfunction encodeSdkCursor(offset: number, cursor: string | undefined): string {\n const envelope: SdkCursorEnvelope = {\n v: CURSOR_VERSION,\n source: CURSOR_SOURCE.SDK,\n cursor,\n offset,\n };\n return encodeBase64(JSON.stringify(envelope));\n}\n\nexport function decodeIncomingCursor(incoming?: string): {\n offset: number;\n cursor: string | undefined;\n} {\n if (!incoming) {\n return { offset: 0, cursor: undefined };\n }\n\n try {\n const decoded = decodeBase64(incoming);\n const envelope = JSON.parse(decoded) as CursorEnvelope;\n\n if (envelope.v !== CURSOR_VERSION) {\n return { offset: 0, cursor: incoming };\n }\n\n if (envelope.source === CURSOR_SOURCE.SDK) {\n return { offset: envelope.offset ?? 0, cursor: envelope.cursor };\n }\n\n if (envelope.source === CURSOR_SOURCE.API) {\n return { offset: 0, cursor: envelope.cursor };\n }\n\n return { offset: 0, cursor: incoming };\n } catch {\n return { offset: 0, cursor: incoming };\n }\n}\n\nexport function createPrefixedCursor(\n prefix: string,\n cursor: string | undefined,\n): string {\n if (!cursor) {\n return `${prefix}::`;\n }\n return `${prefix}::${cursor}`;\n}\n\nexport function splitPrefixedCursor(\n cursor: string | undefined,\n prefixes?: string[],\n): [string | undefined, string | undefined] {\n if (!cursor) {\n return [undefined, undefined];\n }\n\n const [prefix, ...rest] = cursor.split(\"::\");\n\n if (prefixes && !prefixes.includes(prefix)) {\n return [undefined, cursor];\n }\n\n cursor = rest.join(\"::\");\n\n if (!cursor) {\n return [prefix, undefined];\n }\n\n return [prefix, cursor];\n}\n\n/**\n * Internal primitive: paginates through a page function using raw (unencoded) cursors.\n * Encoding and decoding of cursors is the responsibility of the public wrappers.\n */\nasync function* paginateMaxItemsWithUnencodedCursor<\n TOptions,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TPage extends { data: any[]; nextCursor?: string },\n>(\n pageFunction: (\n options: TOptions & {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n },\n ) => Promise<TPage>,\n pageOptions?: TPageOptions<TOptions>,\n): AsyncIterableIterator<TPage> {\n let cursor = pageOptions?.cursor;\n let totalItemsYielded = 0;\n const maxItems = pageOptions?.maxItems;\n const pageSize = pageOptions?.pageSize;\n\n do {\n const options = {\n ...(pageOptions || {}),\n cursor,\n pageSize:\n maxItems !== undefined && pageSize !== undefined\n ? Math.min(pageSize, maxItems)\n : pageSize,\n } as TOptions & { cursor?: string; maxItems?: number; pageSize?: number };\n\n const page = await pageFunction(options);\n\n if (maxItems !== undefined) {\n const remainingItems = maxItems - totalItemsYielded;\n if (page.data.length >= remainingItems) {\n yield {\n ...page,\n data: page.data.slice(0, remainingItems),\n nextCursor: undefined,\n };\n break;\n }\n }\n\n yield page;\n totalItemsYielded += page.data.length;\n\n cursor = page.nextCursor;\n } while (cursor);\n}\n\n/**\n * Utility for paginating through API endpoints that return cursor-based pages.\n * Accepts and yields SDK-encoded cursor envelopes. Any incoming cursor is decoded\n * before being passed to the page function; all outgoing cursors are encoded.\n *\n * @param pageFunction - Function that fetches a single page with {data, nextCursor} structure\n * @param pageOptions - Options to pass to the page function (cursor will be managed automatically)\n * @returns Async iterator that yields pages with encoded cursors\n */\nexport async function* paginateMaxItems<\n TOptions,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TPage extends { data: any[]; nextCursor?: string },\n>(\n pageFunction: (\n options: TOptions & {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n },\n ) => Promise<TPage>,\n pageOptions?: TPageOptions<TOptions>,\n): AsyncIterableIterator<TPage> {\n const { cursor } = decodeIncomingCursor(pageOptions?.cursor);\n const options = {\n ...(pageOptions || {}),\n cursor,\n } as TPageOptions<TOptions>;\n\n for await (const page of paginateMaxItemsWithUnencodedCursor(\n pageFunction,\n options,\n )) {\n yield {\n ...page,\n nextCursor: page.nextCursor\n ? encodeApiCursor(page.nextCursor)\n : undefined,\n };\n }\n}\n\nexport async function* paginateBuffered<\n TOptions,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TPage extends { data: any[]; nextCursor?: string },\n>(\n pageFunction: (\n options: TOptions & {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n },\n ) => Promise<TPage>,\n pageOptions?: TPageOptions<TOptions>,\n): AsyncIterableIterator<TPage> {\n const pageSize = pageOptions?.pageSize;\n const { offset: cursorOffset, cursor: initialCursor } = decodeIncomingCursor(\n pageOptions?.cursor,\n );\n const requestedMaxItems = pageOptions?.maxItems;\n const options = {\n ...(pageOptions || {}),\n cursor: initialCursor,\n // SDK cursors can carry an offset into a raw backend page. Since maxItems\n // is expected to be relative to the resumed position, we add that offset\n // so raw pagination still yields enough items after offset slicing.\n maxItems:\n requestedMaxItems !== undefined && cursorOffset > 0\n ? requestedMaxItems + cursorOffset\n : requestedMaxItems,\n } as TPageOptions<TOptions>;\n\n if (!pageSize) {\n for await (const page of paginateMaxItemsWithUnencodedCursor(\n pageFunction,\n options,\n )) {\n yield {\n ...page,\n nextCursor: page.nextCursor\n ? encodeApiCursor(page.nextCursor)\n : undefined,\n };\n }\n return;\n }\n\n let bufferedPages: TPage[] = [];\n let isFirstPage = true;\n let rawCursor: string | undefined;\n\n for await (let page of paginateMaxItemsWithUnencodedCursor(\n pageFunction,\n options,\n )) {\n const nextRawCursor = page.nextCursor;\n\n if (isFirstPage) {\n isFirstPage = false;\n if (cursorOffset) {\n page = {\n ...page,\n data: page.data.slice(cursorOffset),\n };\n }\n }\n\n const bufferedLength = bufferedPages.reduce(\n (acc, p) => acc + p.data.length,\n 0,\n );\n\n // If we don't have enough to fill a page, buffer this page.\n if (bufferedLength + page.data.length < pageSize) {\n bufferedPages.push(page);\n rawCursor = nextRawCursor;\n continue;\n }\n\n // Let's yield a page from our buffered pages.\n const bufferedItems = bufferedPages.map((p) => p.data).flat();\n const allItems = [...bufferedItems, ...page.data];\n const pageItems = allItems.slice(0, pageSize);\n const remainingItems = allItems.slice(pageItems.length);\n\n // No extra items to buffer, so we can just yield a normal page with a cursor to the next one.\n if (remainingItems.length === 0) {\n yield {\n ...page,\n data: pageItems,\n nextCursor: nextRawCursor ? encodeApiCursor(nextRawCursor) : undefined,\n };\n bufferedPages = [];\n rawCursor = nextRawCursor;\n continue;\n }\n\n // Yield our items with a cursor to offset into this page.\n yield {\n ...page,\n data: pageItems,\n nextCursor: encodeSdkCursor(\n page.data.length - remainingItems.length,\n rawCursor,\n ),\n };\n\n while (remainingItems.length > pageSize) {\n const chunkItems = remainingItems.splice(0, pageSize);\n yield {\n ...page,\n data: chunkItems,\n nextCursor: encodeSdkCursor(\n page.data.length - remainingItems.length,\n rawCursor,\n ),\n };\n }\n\n bufferedPages = [\n {\n ...page,\n data: remainingItems,\n },\n ];\n\n rawCursor = nextRawCursor;\n }\n\n if (bufferedPages.length > 0) {\n const lastBufferedPage = bufferedPages.slice(-1)[0];\n const bufferedItems = bufferedPages.map((p) => p.data).flat();\n yield {\n ...lastBufferedPage,\n data: bufferedItems,\n };\n }\n}\n\nexport const paginate = paginateBuffered;\n\n// ============================================================================\n// Concat Paginated Sources\n// ============================================================================\n\ninterface PaginatedResult<TItem> {\n data: TItem[];\n nextCursor?: string;\n}\n\ntype PaginatedSource<TItem> = () => PromiseLike<PaginatedResult<TItem>> &\n AsyncIterable<PaginatedResult<TItem>>;\n\n/**\n * Concatenate multiple paginated SDK results into a single paginated stream.\n * Each source is a function returning a dual Promise+AsyncIterable (as SDK\n * paginated methods return). Sources are drained in order.\n *\n * The optional `dedupe` key extractor filters items from source N against\n * all items seen in sources 0 through N-1.\n *\n * Uses paginateBuffered internally to normalize page sizes across source\n * boundaries — e.g. if the first source only has 2 items, they'll be\n * buffered with items from the next source into a full page.\n *\n * Returns the same dual Promise+AsyncIterable shape that resolvers expect.\n */\nexport function concatPaginated<TItem>({\n sources,\n dedupe,\n pageSize = 100,\n}: {\n sources: PaginatedSource<TItem>[];\n dedupe?: (item: TItem) => string;\n pageSize?: number;\n}): PromiseLike<PaginatedResult<TItem>> &\n AsyncIterable<PaginatedResult<TItem>> {\n if (sources.length === 0) {\n const empty: PaginatedResult<TItem> = { data: [] };\n return Object.assign(Promise.resolve(empty), {\n [Symbol.asyncIterator]: async function* () {\n yield empty;\n },\n });\n }\n\n let sourceIndex = 0;\n let currentIterator: AsyncIterator<PaginatedResult<TItem>> | null = null;\n const seen = new Set<string>();\n\n const pageFunction = async (_options: {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n }): Promise<PaginatedResult<TItem>> => {\n while (sourceIndex < sources.length) {\n if (!currentIterator) {\n const result = sources[sourceIndex]();\n currentIterator = result[Symbol.asyncIterator]();\n }\n\n const next = await currentIterator.next();\n\n if (next.done) {\n sourceIndex++;\n currentIterator = null;\n continue;\n }\n\n let items = next.value.data;\n\n if (dedupe) {\n if (sourceIndex > 0) {\n items = items.filter((item) => !seen.has(dedupe(item)));\n }\n for (const item of items) {\n seen.add(dedupe(item));\n }\n }\n\n const hasMoreInSource = next.value.nextCursor != null;\n const hasMoreSources = sourceIndex < sources.length - 1;\n\n // Synthetic sentinel — not a real API cursor. It just signals to\n // paginateBuffered that more data exists (from the current source or\n // the next one). This works because concatPaginated manages its own\n // iteration state internally. Currently only used by CLI resolvers;\n // if this is ever used in user-facing SDK methods, we should replace\n // it with a stateless composite cursor (e.g. sourceIndex + inner cursor).\n return {\n data: items,\n nextCursor:\n hasMoreInSource || hasMoreSources ? \"__has_more__\" : undefined,\n };\n }\n\n return { data: [] };\n };\n\n const iterator = paginateBuffered(pageFunction, { pageSize });\n\n const firstPagePromise = iterator.next().then((result) => {\n if (result.done) {\n return { data: [] as TItem[] };\n }\n return result.value;\n });\n\n return Object.assign(firstPagePromise, {\n [Symbol.asyncIterator]: async function* () {\n yield await firstPagePromise;\n\n for await (const page of { [Symbol.asyncIterator]: () => iterator }) {\n yield page;\n }\n },\n });\n}\n\n/**\n * Strip the PromiseLike from an async iterable, returning a plain\n * AsyncIterable. This prevents async functions from unwrapping the\n * iterable (since async only unwraps PromiseLike, not AsyncIterable).\n */\nexport function toIterable<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n return { [Symbol.asyncIterator]: () => source[Symbol.asyncIterator]() };\n}\n","import type { z } from \"zod\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\n\n/**\n * Run `schema` against `input`, returning the parsed value or throwing a\n * framework error on failure. The throw routes through `createCoreError` so a\n * head's `adaptError` factory (if any) can brand it; otherwise it's a plain\n * `CoreError`.\n *\n * Shared core for the two public forms below. It's parameterized over the\n * whole schema type (`TSchema`) on purpose: that's what preserves\n * `z.infer<TSchema>` in the return for both callers. `validateOptions`'s\n * output-type generics can't be the core, handed a generic `TSchema` they\n * collapse to `unknown`, which is why this stays a separate function rather\n * than folding into either wrapper.\n */\nconst parseOrThrow = <TSchema extends z.ZodSchema>(\n schema: TSchema,\n input: unknown,\n { adaptError }: { adaptError?: AdaptError } = {},\n): z.infer<TSchema> => {\n const result = schema.safeParse(input);\n\n if (!result.success) {\n // Format Zod errors into a clean, user-friendly message\n const errorMessages = result.error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"input\";\n return `${path}: ${issue.message}`;\n });\n\n throw createCoreError(\n {\n code: CoreErrorCode.Validation,\n message: `Validation failed:\\n ${errorMessages.join(\"\\n \")}`,\n details: {\n zodErrors: result.error.issues,\n input,\n },\n },\n adaptError,\n );\n }\n\n return result.data;\n};\n\n/**\n * Deferred form: bind a schema (and `adaptError`) once, get a reusable\n * validator. Its input is `unknown` so it can validate values wider than the\n * schema's own type (e.g. paginated options that carry cursor / pageSize\n * alongside the schema-typed fields).\n */\nexport function createValidator<TSchema extends z.ZodSchema>(\n schema: TSchema,\n { adaptError }: { adaptError?: AdaptError } = {},\n) {\n return function validateFn(input: unknown): z.infer<TSchema> {\n return parseOrThrow(schema, input, { adaptError });\n };\n}\n\n/**\n * Eager form: validate `options` now and return the parsed value. The\n * `TSchemaOptions extends TOptions` generics let the call site check that the\n * value being validated matches the schema's type, which `createValidator`\n * (input `unknown`) can't.\n */\nexport const validateOptions = <TOptions, TSchemaOptions extends TOptions>(\n schema: z.ZodSchema<TSchemaOptions>,\n options: TOptions,\n { adaptError }: { adaptError?: AdaptError } = {},\n): TSchemaOptions => parseOrThrow(schema, options, { adaptError });\n","// Shared AsyncLocalStorage plumbing for every ALS-backed context in the SDK\n// (method scope, caller context, …). Centralized here so the subtle,\n// once-broken bundling details live in exactly one place.\n//\n// WHY A STATIC IMPORT — DO NOT CHANGE TO `require`: tsup converts this import\n// statement directly — to `require()` in the CJS bundle, kept as a native\n// `import` in the ESM bundle. A previous `require(\"node:async_hooks\")` pattern\n// was silently rewritten by tsup's `__require` shim in ESM, which threw at\n// runtime; the catch below then swallowed it and left ESM consumers (notably\n// the CLI) with no store at all, so every context became permanently inert —\n// e.g. nested-call detection in method-scope broke on every call. Keeping this\n// a static import is load-bearing; reverting it reintroduces that bug.\n//\n// WHY THE try/catch: browsers can't resolve `node:async_hooks` at bundle time.\n// Consumers bundling the SDK for the browser must mark this module external or\n// polyfill it; without that, instantiation fails and the context falls back to\n// inert-but-safe (every `run` just calls `fn`, every `get` returns undefined).\n// The catch also covers any other instantiation failure.\nimport {\n AsyncLocalStorage,\n type AsyncLocalStorage as AsyncLocalStorageType,\n} from \"node:async_hooks\";\n\n/**\n * A typed wrapper around a single `AsyncLocalStorage` instance. Centralizes the\n * `node:async_hooks` plumbing (bundler-safe static import, browser fallback) so\n * consumers don't each hand-roll it and drift apart.\n *\n * The wrapper holds no merge or depth policy: `run` simply activates `store`\n * for the duration of `fn`, and `get` returns whatever is active. Consumers\n * layer their own semantics (e.g. depth counting, parent merging) on top.\n */\nexport interface AsyncContext<T> {\n /** Run `fn` with `store` active. Returns whatever `fn` returns; `fn`'s errors propagate. */\n run<R>(store: T, fn: () => R): R;\n /** The active store, or `undefined` if no scope is active or ALS is unavailable. */\n get(): T | undefined;\n /**\n * `false` only where `node:async_hooks` could not be loaded (e.g. browsers),\n * leaving the context inert. Lets callers distinguish \"ALS unavailable\" from\n * the also-`undefined` \"ALS available but no active scope\".\n */\n readonly available: boolean;\n}\n\n/** Create an isolated {@link AsyncContext} backed by one `AsyncLocalStorage`. */\nexport function createAsyncContext<T>(): AsyncContext<T> {\n let store: AsyncLocalStorageType<T> | null = null;\n try {\n store = new AsyncLocalStorage<T>();\n } catch {\n // Non-Node environment (browser, etc.) — context is inert.\n store = null;\n }\n\n return {\n available: store !== null,\n run(value, fn) {\n return store ? store.run(value, fn) : fn();\n },\n get() {\n return store?.getStore();\n },\n };\n}\n","/**\n * Per-invocation scope for SDK method calls. Each top-level SDK method call\n * runs in its own AsyncLocalStorage scope (via `runInMethodScope`), isolating\n * its depth counter and any plugin-specific state from concurrent calls.\n *\n * The toolkit reserves the `depth` field; anything else on the scope is\n * opaque key/value storage that plugins can use (e.g. eventEmission stores\n * its `MethodMetadata` under its own key).\n */\n\nimport { createAsyncContext } from \"./async-context\";\n\n/**\n * The per-call scope object held in ALS. Toolkit owns `depth`; everything\n * else is open for plugin-specific use.\n */\nexport interface MethodScope {\n depth: number;\n [key: string]: unknown;\n}\n\nconst scope = createAsyncContext<MethodScope>();\n\n/**\n * Read the current scope object, or `undefined` if no scope is active or\n * AsyncLocalStorage isn't available. Plugins use this to read/write their\n * own scoped state under their own key.\n */\nexport function getCurrentScope(): MethodScope | undefined {\n return scope.get();\n}\n\n/**\n * Current depth of the SDK method-call stack. 0 = outermost call,\n * 1+ = invoked from inside another SDK method. Returns 0 when no scope\n * is active (e.g. raw callers outside the framework).\n */\nexport function getCurrentDepth(): number {\n return getCurrentScope()?.depth ?? 0;\n}\n\n/**\n * True when the current call is nested inside another SDK method.\n * Preserves the legacy \"no store = nested\" fallback used by browser\n * builds to suppress hook firing when async_hooks isn't available.\n */\nexport function isNestedMethodCall(): boolean {\n if (!scope.available) return true;\n const store = scope.get();\n return store !== undefined && store.depth > 0;\n}\n\n/**\n * Run `fn` inside a new method scope. Nested invocations see an incremented\n * `depth`. When no scope store is available (e.g. browsers without\n * async_hooks), `fn` is called directly with no scope tracking.\n */\nexport function runInMethodScope<T>(fn: () => T): T {\n if (!scope.available) return fn();\n const currentDepth = scope.get()?.depth ?? -1;\n return scope.run({ depth: currentDepth + 1 }, fn);\n}\n\n// Back-compat aliases for the previous names. Toolkit-internal callers\n// should prefer the unprefixed names; external callers that imported\n// the legacy names from the package keep working.\nexport const runWithTelemetryContext = runInMethodScope;\nexport const isTelemetryNested = isNestedMethodCall;\n","/**\n * Generic utility functions for creating SDK-method wrappers.\n *\n * Both `createFunction` and `createPaginatedFunction` accept the SDK\n * as a parameter and read framework state (`hooks`, `core.adaptError`)\n * live from `sdk.context.*` at method-invocation time. Plugins registered\n * after a method is built still observe and configure it; ordering of\n * plugin registration doesn't change runtime semantics. (Pagination's\n * `adaptPage` is passed in per method, not read from context.)\n */\n\nimport type { z } from \"zod\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport { paginate } from \"./pagination-utils\";\nimport { createValidator, validateOptions } from \"./validation\";\nimport { getCurrentDepth, runInMethodScope } from \"./method-scope\";\nimport type { MethodHooks } from \"./build-hooks\";\nimport type { CoreOptions } from \"./core-plugin\";\n\n/**\n * Minimal SDK shape the function wrappers accept. The wrappers only\n * touch `context.hooks` and `context.core.*`, but we keep `context`\n * typed as `unknown` so any kitcore-built SDK (whose context type\n * widens unpredictably as plugins layer on) flows through without\n * upstream type narrowing. Each read inside is asserted at the use\n * site against the small slice we actually need.\n */\ntype FunctionSdk = { context: unknown };\n\ntype HooksContext = { hooks?: MethodHooks };\ntype CoreContext = { core?: CoreOptions };\n\n/**\n * Pass `Error` instances (including any subclass) straight through, so a\n * handler's typed error keeps its class identity at the consumer. Only\n * non-`Error` throws (raw strings, plain objects, etc.) get wrapped via\n * `createCoreError`, which routes through the head's `adaptError`\n * factory (if supplied) or falls back to a plain `CoreError`.\n *\n * Wrapping native or third-party `Error` subclasses would hide their\n * identity (consumers couldn't `instanceof TypeError` / `MyAppError`\n * anymore). Kitcore-typed throws and userland `Error` subclasses both\n * bubble unchanged.\n */\nfunction normalizeError(error: unknown, adaptError?: AdaptError): Error {\n if (error instanceof Error) return error;\n // Best-effort message extraction for hostile throws (`throw \"oops\"`,\n // `throw { message: \"X\" }`, etc.). `String(error)` alone would\n // produce \"[object Object]\" for plain objects with a useful\n // `message` field, so prefer that field when it's a string.\n const message =\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as { message: unknown }).message === \"string\"\n ? (error as { message: string }).message\n : String(error);\n return createCoreError(\n {\n code: CoreErrorCode.Unknown,\n message,\n cause: error,\n },\n adaptError,\n );\n}\n\n/**\n * Wrap a core async function with input validation, error normalization,\n * and method-call lifecycle hooks. Hooks and `adaptError` are read live\n * from `sdk.context.*` at every invocation, so a plugin registered\n * after this method is built still observes and configures it.\n *\n * @param coreFn - the underlying async function to wrap\n * @param options.sdk - the SDK (or sub-SDK view) providing `context.hooks`\n * and `context.core`\n * @param options.schema - optional Zod schema for input validation\n */\nexport function createFunction<\n TOptions,\n TResult,\n TSchemaOptions extends TOptions = TOptions,\n>(\n coreFn: (options: TOptions) => Promise<TResult>,\n options: {\n sdk: FunctionSdk;\n schema?: z.ZodSchema<TSchemaOptions>;\n name?: string;\n },\n) {\n const { sdk, schema, name } = options;\n const functionName = name || coreFn.name;\n\n // Create a named function using dynamic property access\n const namedFunctions = {\n [functionName]: async function (callOptions?: TOptions): Promise<TResult> {\n return runInMethodScope(async () => {\n const startTime = Date.now();\n const normalizedOptions = (callOptions ?? {}) as TOptions;\n const args: unknown[] = [normalizedOptions];\n const depth = getCurrentDepth();\n // Read live: a plugin contributing hooks or adaptError after\n // this method was constructed should still apply.\n const hooks = (sdk.context as HooksContext).hooks;\n const adaptError = (sdk.context as CoreContext).core?.adaptError;\n\n hooks?.onMethodStart?.({\n methodName: functionName,\n args,\n isPaginated: false,\n depth,\n });\n\n try {\n let result: TResult;\n if (schema) {\n const validatedOptions = validateOptions(\n schema,\n normalizedOptions,\n {\n adaptError,\n },\n );\n result = await coreFn({\n ...normalizedOptions,\n ...validatedOptions,\n });\n } else {\n result = await coreFn(normalizedOptions);\n }\n\n hooks?.onMethodEnd?.({\n methodName: functionName,\n args,\n isPaginated: false,\n depth,\n durationMs: Date.now() - startTime,\n });\n\n return result;\n } catch (error) {\n const normalizedError = normalizeError(error, adaptError);\n\n hooks?.onMethodEnd?.({\n methodName: functionName,\n args,\n isPaginated: false,\n depth,\n durationMs: Date.now() - startTime,\n error: normalizedError,\n });\n\n throw normalizedError;\n }\n });\n },\n };\n\n return namedFunctions[functionName];\n}\n\n/**\n * Narrow an unknown value to `SdkPage<TItem>`: an object whose ONLY keys are\n * `data` (an array) and optionally `nextCursor` (a string). The exact-key check\n * matters because a handler's shape is gated at compile time but `adaptPage`'s\n * output is not (TS skips excess-property checks through that inference path).\n * Rejecting a stray key (e.g. a raw envelope's `links`/`next`, or a `nextCursor`\n * typo) makes a mistyped page fail loudly here rather than silently dropping the\n * cursor and paginating wrong.\n */\nfunction isSdkPage<TItem>(value: unknown): value is SdkPage<TItem> {\n if (typeof value !== \"object\" || value === null) return false;\n const page = value as { data?: unknown; nextCursor?: unknown };\n if (!Array.isArray(page.data)) return false;\n if (page.nextCursor !== undefined && typeof page.nextCursor !== \"string\") {\n return false;\n }\n return Object.keys(page).every((k) => k === \"data\" || k === \"nextCursor\");\n}\n\n/**\n * Higher-order function that resolves a core handler's response to a canonical\n * `SdkPage<TItem>`. The adapter is part of the typed contract: when supplied,\n * `adaptPage` translates the handler's raw response into the page (`TItem` is\n * sourced from the response, not the adapter — the adapter is item-agnostic);\n * when omitted, the handler must already return an `SdkPage<TItem>`. Either\n * way the result must be `{ data: TItem[], nextCursor? }`; a non-page result\n * throws (the caller should supply `adaptPage`). The guard backs the loose\n * direct-caller path — plugin methods enforce the page shape at compile time.\n */\nfunction createPageFunction<TOptions, TResponse, TItem>(\n coreFn: (options: TOptions) => Promise<TResponse>,\n {\n sdk,\n adaptPage,\n }: {\n sdk: FunctionSdk;\n adaptPage?: (response: TResponse) => SdkPage<TItem>;\n },\n) {\n const functionName = coreFn.name + \"Page\";\n\n // Create a named function using dynamic property access\n const namedFunctions = {\n [functionName]: async function (\n options: TOptions & {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n },\n ): Promise<SdkPage<TItem>> {\n try {\n const response = await coreFn(options);\n const page = adaptPage ? adaptPage(response) : response;\n\n if (!isSdkPage<TItem>(page)) {\n throw new Error(\n `${functionName}: paginated result must be exactly { data: TItem[], nextCursor? } ` +\n `(produced by the handler or its \\`adaptPage\\`); got keys ` +\n `[${page && typeof page === \"object\" ? Object.keys(page).join(\", \") : typeof page}]. ` +\n `If the handler returns a raw shape, set \\`adaptPage\\` to translate it; ` +\n `if \\`adaptPage\\` already runs, it must return only \\`data\\`/\\`nextCursor\\`.`,\n );\n }\n\n return page;\n } catch (error) {\n throw normalizeError(\n error,\n (sdk.context as CoreContext).core?.adaptError,\n );\n }\n },\n };\n\n return namedFunctions[functionName];\n}\n\n/**\n * Higher-order function that creates a paginated function that wraps\n * results in `SdkPage<TItem>`.\n *\n * @param coreFn - Function that returns T directly or throws errors\n * @returns A function that normalizes errors and wraps results in `SdkPage`\n */\n\n/**\n * Extract the item type from a page handler's return shape. The handler\n * may return a flat `{ data: TItem[] }` (or single `data: TItem`), a bare\n * array, or anything else; in all cases the wrapper normalizes to\n * `SdkPage<TItem>` and this resolves the right `TItem`.\n */\ntype ItemType<TResult> = TResult extends { data: infer TData }\n ? TData extends readonly (infer TItem)[]\n ? TItem\n : TData\n : TResult extends readonly (infer TItem)[]\n ? TItem\n : TResult;\n\nexport function createPaginatedFunction<\n TUserOptions,\n TResponse,\n TItem = ItemType<TResponse>,\n>(\n coreFn: (\n options: TUserOptions & { cursor?: string; pageSize?: number },\n ) => Promise<TResponse>,\n options: {\n sdk: FunctionSdk;\n schema?: z.ZodSchema<TUserOptions>;\n name?: string;\n defaultPageSize?: number;\n /**\n * Translate the handler's raw `TResponse` into `SdkPage<TItem>`. `TItem`\n * is wrapped in `NoInfer`: it is sourced from `TResponse` (via the\n * `ItemType` default), not from this adapter, which is item-agnostic (it\n * relocates the cursor; items are finalized in the handler's `data`).\n * Without `NoInfer`, a generic adapter (e.g. `<T>(r) => SdkPage<T>`)\n * would collapse `TItem` to `unknown`.\n */\n adaptPage?: (response: TResponse) => SdkPage<NoInfer<TItem>>;\n },\n): (\n options?: TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n },\n) => PaginatedSdkResult<TItem> {\n const { sdk, schema, name, defaultPageSize, adaptPage } = options;\n const pageFunction = createPageFunction(coreFn, { sdk, adaptPage });\n const functionName = name || coreFn.name;\n\n // Create the main paginated function\n const namedFunctions = {\n [functionName]: function (\n callOptions?: TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n },\n ) {\n return runInMethodScope(() => {\n const startTime = Date.now();\n // Convert undefined options to empty object\n const normalizedOptions = (callOptions ?? {}) as TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n };\n const args: unknown[] = [normalizedOptions];\n\n const depth = getCurrentDepth();\n // Read live framework state once per invocation. The same `hooks`\n // is used for both onMethodStart and the later onMethodEnd that\n // fires after the first page settles; reading once per call keeps\n // the pair symmetric.\n const hooks = (sdk.context as HooksContext).hooks;\n const adaptError = (sdk.context as CoreContext).core?.adaptError;\n\n hooks?.onMethodStart?.({\n methodName: functionName,\n args,\n isPaginated: true,\n depth,\n });\n\n // Validate options if schema provided (validated fields take precedence).\n // Validator is created per-call so it picks up the live `adaptError`\n // every time; the schema closes over `unknown` input internally,\n // which decouples the schema's narrow type from the call's wider\n // options shape (cursor / pageSize / maxItems).\n const validatedOptions = {\n ...normalizedOptions,\n ...(schema\n ? createValidator(schema, { adaptError })(normalizedOptions)\n : normalizedOptions),\n };\n\n const pageSize = validatedOptions.pageSize ?? defaultPageSize;\n const optimizedOptions = {\n ...validatedOptions,\n pageSize,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const iterator = paginate(pageFunction, optimizedOptions as any);\n\n // Get a promise for the first iteration\n const firstPagePromise = iterator.next().then((result) => {\n if (result.done) {\n throw new Error(\"Paginate should always iterate at least once\");\n }\n return result.value;\n });\n\n // Fire onMethodEnd after the first page resolves (or rejects).\n if (hooks?.onMethodEnd) {\n firstPagePromise\n .then(() => {\n hooks.onMethodEnd!({\n methodName: functionName,\n args,\n isPaginated: true,\n depth,\n durationMs: Date.now() - startTime,\n });\n })\n .catch((error) => {\n hooks.onMethodEnd!({\n methodName: functionName,\n args,\n isPaginated: true,\n depth,\n durationMs: Date.now() - startTime,\n error:\n error instanceof Error ? error : new Error(String(error)),\n });\n });\n }\n\n // The first page is fetched once at construction and buffered in\n // `firstPagePromise`, which `await` / `.then()` read without advancing\n // the cursor, so awaiting is a repeatable peek.\n //\n // Pages and items are two views over ONE page stream: it emits the\n // buffered first page, then the rest of the shared cursor. The page\n // face hands back this single stream; `.items()` is a view that pulls\n // the same stream and flattens each page. Because the buffered page is\n // emitted by exactly one stream, consuming either view drains the\n // other (the second sees nothing) rather than replaying page 1 over an\n // exhausted cursor (the AICG-2044 bug). A result is consumed once.\n const pageStream = (async function* () {\n yield await firstPagePromise;\n for await (const page of iterator) {\n yield page;\n }\n })();\n\n // Add Symbol.asyncIterator to make the promise iterable\n return Object.assign(firstPagePromise, {\n [Symbol.asyncIterator]() {\n return pageStream;\n },\n items: function () {\n return {\n [Symbol.asyncIterator]: async function* () {\n for await (const page of pageStream) {\n for (const item of page.data) {\n yield item;\n }\n }\n },\n };\n },\n });\n });\n },\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return namedFunctions[functionName] as any;\n}\n","/**\n * ------------------------------\n * Plugin authoring helpers\n * ------------------------------\n *\n * - `createPluginMethod` / `createPaginatedPluginMethod`: per-method\n * primitives that sit inside a `definePlugin` callback and build the\n *\n * { [name]: wrappedFn, context: { meta: { [name]: meta } } }\n *\n * fragment a plugin returns for a single method, wiring up\n * `createFunction` / `createPaginatedFunction`, the method-call hooks,\n * and the doubled `name` (function key + meta key) in one place.\n *\n * Two method helpers (rather than one with a `paginated: true` discriminant)\n * because the handler signature changes shape across pagination, and\n * discriminated unions on optional booleans produce noisy TS errors.\n */\n\nimport type { z } from \"zod\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport type { Plugin, PluginMeta, PluginProvides, Sdk } from \"../types/plugin\";\nimport { buildRegistry, type RegistryResult } from \"../registry\";\nimport { buildHooks } from \"./build-hooks\";\nimport type { MethodHooks } from \"./build-hooks\";\nimport { logDeprecation } from \"./logging\";\nimport { createFunction, createPaginatedFunction } from \"./function-utils\";\nimport type { ResolverMetadata, ValidResolvers } from \"./schema-utils\";\n\n/**\n * Method-level meta fields. Mirrors `PluginMeta` minus `inputSchema`, which is\n * passed at the top level alongside the handler and merged into the meta by\n * the helpers themselves.\n */\ntype MethodMeta<TSdk> = Omit<PluginMeta<TSdk>, \"inputSchema\">;\n\n/**\n * The plugin's own method signature, synthesized from the method config.\n * Mixed into the resolver-side SDK so a resolver may freely reference the\n * host plugin's own method (e.g. `appKeyResolver` calling `sdk.getApp`)\n * without forcing the plugin to declare a circular dependency on itself.\n *\n * Uses `any` for options and return: we only need to assert the method\n * exists on `sdk`, not pin its full signature. Using `TInput`/`TResult`\n * here would create a circular inference (TSdk depends on TInput/TResult\n * via the resolvers slot, TInput/TResult are inferred from the handler\n * which depends on TSdk), and TS resolves the cycle by widening to\n * `unknown`. With `any`, the resolver check still verifies the method's\n * presence on the SDK; signature precision for self is the plugin\n * author's responsibility.\n *\n * Not mixed into the handler's `sdk`: handlers run against the SDK that\n * existed when the plugin was added to the stack (closure-captured), so\n * self-method access there would be a lie at runtime.\n */\ntype SelfMethod<TName extends string> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in TName]: (options?: any) => any;\n};\n\ninterface PluginMethodConfig<\n TSdk,\n TInput,\n TResult,\n TName extends string,\n TResolvers,\n> extends Omit<MethodMeta<TSdk>, \"resolvers\"> {\n name: TName;\n /**\n * Schema for runtime input validation; drives the handler's `options`\n * type. For plugins that accept deprecated parameter aliases this is a\n * `z.union([CanonicalSchema, DeprecatedSchema])` — the registry\n * unwraps unions and exposes only the first variant (canonical) to\n * documentation and downstream consumer surfaces.\n */\n inputSchema?: z.ZodSchema<TInput>;\n handler: (args: { sdk: TSdk; options: TInput }) => Promise<TResult>;\n /**\n * Per-parameter resolvers. Each entry's `TSdk` requirement is checked\n * against the plugin's own `TSdk` (plus the plugin's own method via\n * {@link SelfMethod}) using {@link ValidResolvers}; mismatches surface\n * at the offending key. `NoInfer` pins `TSdk` to the `sdk` argument so\n * resolver entries don't widen the inferred `TSdk`.\n */\n resolvers?: ValidResolvers<NoInfer<TSdk & SelfMethod<TName>>, TResolvers> &\n TResolvers;\n}\n\ntype PluginMethodReturn<TName extends string, TInput, TResult> = {\n [K in TName]: (options?: TInput) => Promise<TResult>;\n} & {\n context: { meta: { [K in TName]: PluginMeta } };\n};\n\n/**\n * Build the method fragment for a non-paginated SDK method. Used inside a\n * `definePlugin(...)` callback:\n *\n * export const getProfilePlugin = definePlugin(\n * (sdk: ApiPluginProvides & EventEmissionProvides) =>\n * createPluginMethod(sdk, {\n * name: \"getProfile\",\n * categories: [\"account\"],\n * inputSchema: GetProfileSchema,\n * handler: async ({ sdk }) => { ... },\n * }),\n * );\n */\nexport function createPluginMethod<\n const TName extends string,\n TSdk extends { context: unknown },\n TInput,\n TResult,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const TResolvers extends Record<string, ResolverMetadata<any, any, any>> = {},\n>(\n sdk: TSdk,\n config: PluginMethodConfig<TSdk, TInput, TResult, TName, TResolvers>,\n): PluginMethodReturn<TName, TInput, TResult> {\n const { name, inputSchema, handler, ...metaFields } = config;\n\n // Preserve the method name on the inner function so the hook payload\n // and any `function.name`-based diagnostics see the right value.\n const namedHandlers = {\n [name]: async function (options: TInput): Promise<TResult> {\n return handler({ sdk, options });\n },\n };\n\n const wrappedFn = createFunction(namedHandlers[name], {\n sdk,\n schema: inputSchema,\n });\n\n return {\n [name]: wrappedFn,\n context: {\n meta: {\n [name]: {\n ...metaFields,\n ...(inputSchema ? { inputSchema } : {}),\n },\n },\n },\n } as PluginMethodReturn<TName, TInput, TResult>;\n}\n\ninterface PaginatedPluginMethodConfigBase<\n TSdk,\n TInput,\n TName extends string,\n TResolvers,\n> extends Omit<MethodMeta<TSdk>, \"resolvers\"> {\n name: TName;\n /** Same semantics as `createPluginMethod`'s `inputSchema`. */\n inputSchema?: z.ZodSchema<TInput>;\n /**\n * Optional default page size when the caller doesn't pass one. Mirrors\n * `createPaginatedFunction`'s `defaultPageSize` arg.\n */\n defaultPageSize?: number;\n /** See {@link PluginMethodConfig.resolvers}. */\n resolvers?: ValidResolvers<NoInfer<TSdk & SelfMethod<TName>>, TResolvers> &\n TResolvers;\n}\n\n/**\n * A page whose *only* own keys are `data` / `nextCursor`. Used to constrain\n * the Standard overload: a raw envelope with extra keys (a JSON:API\n * `links`/`meta`, a top-level `next`, etc.) is NOT a `StrictPage`, so it falls\n * through to the Adapted overload and `adaptPage` becomes required. Each excess\n * key is mapped to `?: never`, which a real value (e.g. `links: {...}`) can't\n * satisfy — that's what a plain `SdkPage` assignability check (which allows\n * excess keys structurally) misses.\n */\ntype StrictPage<TResponse> = SdkPage<unknown> & {\n [K in Exclude<keyof TResponse, keyof SdkPage<unknown>>]?: never;\n};\n\n/**\n * Config for a paginated method whose handler already returns a clean page\n * (`{ data, nextCursor? }` and nothing else — see `StrictPage`, enforced on\n * the overload). No `adaptPage` needed; `TItem` is sourced from the handler's\n * `data`. Interface extension keeps this a single flattened object type (not\n * an intersection), preserving clean inference of the `resolvers` /\n * `TResolvers` slot.\n */\ninterface PaginatedPluginMethodConfigStandard<\n TSdk,\n TInput,\n TResponse,\n TName extends string,\n TResolvers,\n> extends PaginatedPluginMethodConfigBase<TSdk, TInput, TName, TResolvers> {\n handler: (args: {\n sdk: TSdk;\n options: TInput & { cursor?: string; pageSize?: number };\n }) => Promise<TResponse>;\n /** No adapter: the handler already returns a page. */\n adaptPage?: undefined;\n}\n\n/**\n * Config for a paginated method whose handler returns a raw upstream shape\n * (`TResponse`, e.g. a JSON:API `links.next` envelope). `adaptPage` is required\n * to translate it into a page. `TItem` is sourced from `TResponse` (`ItemOf`),\n * not the adapter — the adapter is item-agnostic (relocates the cursor; items\n * are finalized in the handler's `data`), hence `NoInfer`, so a generic adapter\n * (e.g. `<T>(r) => SdkPage<T>`) doesn't collapse `TItem` to `unknown`.\n */\ninterface PaginatedPluginMethodConfigAdapted<\n TSdk,\n TInput,\n TResponse,\n TItem,\n TName extends string,\n TResolvers,\n> extends PaginatedPluginMethodConfigBase<TSdk, TInput, TName, TResolvers> {\n handler: (args: {\n sdk: TSdk;\n options: TInput & { cursor?: string; pageSize?: number };\n }) => Promise<TResponse>;\n adaptPage: (response: TResponse) => SdkPage<NoInfer<TItem>>;\n}\n\ntype ItemOf<TResponse> =\n TResponse extends SdkPage<infer TItem>\n ? TItem\n : TResponse extends { data: readonly (infer TItem)[] }\n ? TItem\n : never;\n\ntype PaginatedPluginMethodReturn<TName extends string, TInput, TItem> = {\n [K in TName]: (\n options?: TInput & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n },\n ) => PaginatedSdkResult<TItem>;\n} & {\n context: { meta: { [K in TName]: PluginMeta } };\n};\n\n/**\n * Paginated variant of `createPluginMethod`. Two overloads enforce the\n * response contract at compile time:\n *\n * - **Standard** — the handler returns a strict `SdkPage<TItem>`\n * (`{ data, nextCursor? }` and nothing else); no `adaptPage`.\n * - **Adapted** — the handler returns a raw upstream shape and `adaptPage` is\n * *required* to translate it.\n *\n * A handler that returns neither a page-like shape nor pairs a raw shape with\n * `adaptPage` matches no overload and is a compile error.\n *\n * createPaginatedPluginMethod(sdk, {\n * name: \"listThings\",\n * inputSchema: ListThingsSchema,\n * adaptPage: (res) => ({ data: res.items, nextCursor: res.next }),\n * handler: ({ sdk, options }) => sdk.context.api.get(\"/things\", { ... }),\n * });\n */\nexport function createPaginatedPluginMethod<\n const TName extends string,\n TSdk extends { context: unknown },\n TInput,\n TResponse extends StrictPage<TResponse>,\n TItem = ItemOf<TResponse>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const TResolvers extends Record<string, ResolverMetadata<any, any, any>> = {},\n>(\n sdk: TSdk,\n config: PaginatedPluginMethodConfigStandard<\n TSdk,\n TInput,\n TResponse,\n TName,\n TResolvers\n >,\n): PaginatedPluginMethodReturn<TName, TInput, TItem>;\nexport function createPaginatedPluginMethod<\n const TName extends string,\n TSdk extends { context: unknown },\n TInput,\n TResponse,\n TItem = ItemOf<TResponse>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const TResolvers extends Record<string, ResolverMetadata<any, any, any>> = {},\n>(\n sdk: TSdk,\n config: PaginatedPluginMethodConfigAdapted<\n TSdk,\n TInput,\n TResponse,\n TItem,\n TName,\n TResolvers\n >,\n): PaginatedPluginMethodReturn<TName, TInput, TItem>;\nexport function createPaginatedPluginMethod(\n sdk: { context: unknown },\n config: {\n name: string;\n inputSchema?: z.ZodSchema<unknown>;\n defaultPageSize?: number;\n handler: (args: { sdk: unknown; options: unknown }) => Promise<unknown>;\n adaptPage?: (response: unknown) => SdkPage<unknown>;\n [key: string]: unknown;\n },\n): PaginatedPluginMethodReturn<string, unknown, unknown> {\n const {\n name,\n inputSchema,\n handler,\n adaptPage,\n defaultPageSize,\n ...metaFields\n } = config;\n\n // Named so `function.name`-based diagnostics see the method name. The raw\n // handler response flows to `createPaginatedFunction`, which applies\n // `adaptPage` (if any) and normalizes the result — this helper no longer\n // runs the adapter itself.\n const namedHandlers = {\n [name]: function (options: unknown): Promise<unknown> {\n return handler({ sdk, options });\n },\n };\n\n const wrappedFn = createPaginatedFunction(namedHandlers[name], {\n sdk,\n schema: inputSchema,\n name,\n defaultPageSize,\n adaptPage,\n });\n\n return {\n [name]: wrappedFn,\n context: {\n meta: {\n [name]: {\n ...metaFields,\n ...(inputSchema ? { inputSchema } : {}),\n },\n },\n },\n } as PaginatedPluginMethodReturn<string, unknown, unknown>;\n}\n\n// ----------------------------------------------------------------------------\n// composePlugins — type-level helpers\n// ----------------------------------------------------------------------------\n// These types let the function signature derive the composed plugin's TSdk\n// and TProvides automatically from the tuple of sub-plugins passed in.\n//\n// Two-step pipeline for each direction (TSdk and TProvides):\n// 1. Map the tuple of plugins to a tuple of one slot from each plugin\n// (e.g. their TSdk requirements, or their TProvides outputs).\n// 2. Intersect every member of that tuple into a single combined type.\n\n/**\n * Maps a tuple of plugins to a tuple of their TSdk requirement types.\n *\n * SdkRequirementsOf<[Plugin<{ api }, _>, Plugin<{ options }, _>]>\n * = [{ api }, { options }]\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype SdkRequirementsOf<T extends readonly Plugin<any, any>[]> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends Plugin<infer Sdk, any> ? Sdk : never;\n};\n\n/**\n * Maps a tuple of plugins to a tuple of their TProvides output types.\n *\n * ProvidesOf<[Plugin<_, { hello }>, Plugin<_, { goodbye }>]>\n * = [{ hello }, { goodbye }]\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ProvidesOf<T extends readonly Plugin<any, any>[]> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends Plugin<any, infer Provides> ? Provides : never;\n};\n\n/**\n * Intersects every member of a tuple into a single combined type. The\n * result is an object that has every property of every member at once.\n *\n * IntersectAll<[{ api }, { options }]> = { api } & { options }\n * IntersectAll<[]> = {}\n *\n * Walks recursively: head & IntersectAll<tail>, base case is the empty\n * tuple. Why intersection (`&`) and not union (`|`): the composed plugin\n * must require ALL of the sub-plugins' needs at once — an SDK that has\n * both `api` AND `options` — not \"either api or options.\"\n */\ntype IntersectAll<T extends readonly unknown[]> = T extends readonly [\n infer Head,\n ...infer Tail,\n]\n ? Head & IntersectAll<Tail>\n : {};\n\n/**\n * The TSdk a composed plugin requires: every sub-plugin's TSdk requirement,\n * all at once. Composing a plugin that needs `{ api }` with one that needs\n * `{ options }` yields a composed plugin that needs `{ api } & { options }`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ComposeSdk<T extends readonly Plugin<any, any>[]> = IntersectAll<\n SdkRequirementsOf<T>\n>;\n\n/**\n * What a composed plugin provides: every sub-plugin's TProvides combined.\n * Composing a plugin that provides `{ hello }` with one that provides\n * `{ goodbye }` yields `{ hello } & { goodbye }`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ComposeProvides<T extends readonly Plugin<any, any>[]> = IntersectAll<\n ProvidesOf<T>\n>;\n\n// ----------------------------------------------------------------------------\n// Shared plugin-contribution helpers\n// ----------------------------------------------------------------------------\n// The plugin-registration merge work is the same in two places: buildSdk's\n// per-call addPlugin (deprecated chain) and buildPluginStack's per-step\n// `.use` accumulation. Both need to (a) split the plugin result into canonical\n// fragments, (b) merge each fragment into a target with collision checks,\n// (c) compose hooks. The only thing that differs is what the target is:\n// buildSdk seeds it from the prior SDK state and wraps the result in a\n// new buildSdk closure; createPluginStack carries one target across the\n// whole walk. PluginAccumulator + applyPluginContribution let both call\n// sites share the body and just differ at the boundaries.\n\n/**\n * Canonical breakdown of a plugin's return value. The four groups every\n * caller needs in order to merge a contribution into an accumulator: the\n * root-level method bindings, the per-method meta (`context.meta`), the\n * lifecycle hooks (`context.hooks`, composed rather than collided), and\n * the remaining context fields (plugin state at `context.*`).\n */\nexport interface SplitPluginContribution {\n rootKeys: Record<string, unknown>;\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n contextRest: Record<string, unknown>;\n}\n\nexport function splitPluginContribution(\n result: PluginProvides,\n): SplitPluginContribution {\n const { context, ...rootKeys } = result;\n const { meta, hooks, ...contextRest } = (context ?? {}) as {\n meta?: Record<string, PluginMeta>;\n hooks?: MethodHooks;\n [key: string]: unknown;\n };\n return {\n rootKeys: rootKeys as Record<string, unknown>,\n meta: (meta ?? {}) as Record<string, PluginMeta>,\n hooks: (hooks ?? {}) as MethodHooks,\n contextRest,\n };\n}\n\n/**\n * Reserved root-level keys that the SDK shape itself uses. Plugins can't\n * contribute methods with these names; doing so would either shadow a\n * framework accessor (chain path) or get silently dropped (stack path).\n * Either way the user wouldn't see what they expected, so we throw at\n * registration with a clearer message than \"duplicate root key\".\n */\nconst RESERVED_ROOT_KEYS: ReadonlySet<string> = new Set([\n \"context\",\n \"getRegistry\",\n]);\n\n/**\n * `Object.prototype.hasOwnProperty.call(obj, key)` shim. Used for\n * collision checks instead of `key in target` because `in` walks the\n * prototype chain, which would make a plugin's first contribution of a\n * method named `toString`, `constructor`, etc. falsely collide with\n * Object.prototype.\n */\nfunction hasOwn(obj: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Assign an own data property to `target` regardless of the key's name.\n * Plain `target[key] = value` interprets `__proto__` as the prototype\n * setter; `Object.defineProperty` creates an actual own property even\n * for that key.\n */\nexport function setOwn(target: object, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * Validate `source` keys against `target` and reserved-key rules\n * without mutating anything. Throws on duplicate keys (unless\n * `override`) or on reserved root keys (always). Split from the\n * apply step so a caller (e.g. {@link mergeContribution}) can check\n * every category before writing any of them, giving the merge as\n * a whole atomic semantics: either all writes happen or none do.\n */\nfunction checkCollisions(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n kind: \"root key\" | \"context.meta key\" | \"context key\",\n callerLabel: string,\n override: boolean,\n): void {\n if (kind === \"root key\") {\n checkRootKeyCollisions(target, Object.keys(source), override, callerLabel);\n return;\n }\n for (const key of Object.keys(source)) {\n if (!override && hasOwn(target, key)) {\n throw new Error(\n `${callerLabel}: duplicate ${kind} \"${key}\". ` +\n `If the override is intentional, pass { override: true } in the options.`,\n );\n }\n }\n}\n\n/**\n * Preflight a set of root-key assignments without mutating: a reserved root\n * key always throws; an existing own key throws unless `override`. Shared by\n * the legacy merge ({@link checkCollisions}) and the module-model incremental\n * `addPlugin` path so both agree on reserved/collision/override semantics.\n */\nexport function checkRootKeyCollisions(\n target: Record<string, unknown>,\n keys: readonly string[],\n override: boolean,\n callerLabel: string,\n): void {\n for (const key of keys) {\n if (RESERVED_ROOT_KEYS.has(key)) {\n throw new Error(\n `${callerLabel}: plugin attempted to register reserved root key \"${key}\". ` +\n `The SDK uses this key for its own accessor; rename the plugin's method.`,\n );\n }\n if (!override && hasOwn(target, key)) {\n throw new Error(\n `${callerLabel}: duplicate root key \"${key}\". ` +\n `If the override is intentional, pass { override: true } in the options.`,\n );\n }\n }\n}\n\n/**\n * Write every key in `source` onto `target` as an own data property.\n * Assumes {@link checkCollisions} has already passed for the same\n * `(target, source)` pair; performs no validation of its own.\n */\nfunction applyOwnProperties(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key of Object.keys(source)) {\n setOwn(target, key, source[key]);\n }\n}\n\n/**\n * The working state the stack's `toPlugin` walk mutates as it\n * applies plugins. `view` is an SDK-shaped object (root methods\n * at the top, `context` as a sub-property) that plugins receive\n * directly so they don't need to be re-spread on every iteration.\n * `context` is a reference to `view.context` for convenience.\n *\n * The target objects themselves are the registration record: collision\n * detection in `applyPluginContribution` checks own properties rather\n * than carrying parallel `Set<string>` trackers.\n */\nexport interface PluginAccumulator {\n view: Record<string, unknown> & {\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n [key: string]: unknown;\n };\n };\n context: PluginAccumulator[\"view\"][\"context\"];\n}\n\n/**\n * Seed a fresh `PluginAccumulator` from existing properties/context. The\n * `view` and `context` are shallow clones so callers mutate them safely;\n * `meta` and `hooks` get their own clones so the framework-owned\n * namespaces don't share references with the inputs.\n */\nexport function createPluginAccumulator(\n initialProperties: Record<string, unknown> = {},\n initialContext: {\n meta?: Record<string, PluginMeta>;\n hooks?: MethodHooks;\n [key: string]: unknown;\n } = {},\n): PluginAccumulator {\n const initialMeta = (initialContext.meta ?? {}) as Record<string, PluginMeta>;\n const initialHooks = (initialContext.hooks ?? {}) as MethodHooks;\n const context: PluginAccumulator[\"context\"] = {\n ...initialContext,\n meta: { ...initialMeta },\n hooks: { ...initialHooks },\n };\n const view = { ...initialProperties, context } as PluginAccumulator[\"view\"];\n return { view, context };\n}\n\n/**\n * Single merge orchestrator. All four sub-merges (root keys, meta keys,\n * non-meta context keys, hooks) live here so every code path that\n * registers a plugin's contribution goes through the same logic. The\n * targets are passed in by reference: the caller decides whether they\n * own mutable working copies (chain spread) or a long-lived accumulator\n * (stack walk). Either way the merge primitive is identical.\n */\nexport function mergeContribution(\n propertiesTarget: Record<string, unknown>,\n contextTarget: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n [key: string]: unknown;\n },\n contribution: SplitPluginContribution,\n options: { callerLabel: string; override: boolean },\n): void {\n // Phase 1: validate all three categories without touching any\n // target. If any check throws, no mutation has happened anywhere,\n // so the caller can catch the error and the target objects stay\n // consistent. Required by the extension-loader pattern: try each\n // extension's addPlugin in a loop, skip failures, the sdk stays\n // coherent regardless of which extensions failed.\n checkCollisions(\n propertiesTarget,\n contribution.rootKeys,\n \"root key\",\n options.callerLabel,\n options.override,\n );\n checkCollisions(\n contextTarget.meta,\n contribution.meta,\n \"context.meta key\",\n options.callerLabel,\n options.override,\n );\n checkCollisions(\n contextTarget,\n contribution.contextRest,\n \"context key\",\n options.callerLabel,\n options.override,\n );\n // Phase 2: apply. None of these can throw on their own (they're\n // plain `Object.defineProperty` writes against keys we've already\n // validated, plus the function-composition `buildHooks`).\n applyOwnProperties(propertiesTarget, contribution.rootKeys);\n applyOwnProperties(contextTarget.meta, contribution.meta);\n applyOwnProperties(contextTarget, contribution.contextRest);\n contextTarget.hooks = buildHooks(contextTarget.hooks, contribution.hooks);\n}\n\n/**\n * Merge a plugin's already-split contribution into a `PluginAccumulator`.\n * Thin shim over {@link mergeContribution} that targets the accumulator's\n * `view` (for root keys) and `context` (for meta/non-meta/hooks).\n */\nexport function applyPluginContribution(\n acc: PluginAccumulator,\n contribution: SplitPluginContribution,\n options: { callerLabel: string; override: boolean },\n): void {\n mergeContribution(acc.view, acc.context, contribution, options);\n}\n\n// ----------------------------------------------------------------------------\n// SDK shape wrappers\n// ----------------------------------------------------------------------------\n\n/**\n * Build the public SDK shape from a properties bag + a context: spread the root\n * properties, set `context`, and add a `getRegistry` accessor. Used by every\n * path that materializes an SDK (the stack's `toSdk` and the legacy bridge). The\n * sdk and context are mutable so the top-level `addPlugin(sdk, plugin)` can\n * extend the live objects in place; `getRegistry` rebuilds against the current\n * `sdk` + `context.meta` on every call so newly-added methods show up.\n */\nexport function wrapAsSdk<\n P extends Record<string, unknown>,\n C extends {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n [key: string]: unknown;\n },\n>(\n properties: P,\n context: C,\n): P & {\n context: C;\n getRegistry(opts?: { package?: string }): RegistryResult;\n};\nexport function wrapAsSdk(\n properties: Record<string, unknown>,\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n [key: string]: unknown;\n },\n): Record<string, unknown> {\n const sdk: Record<string, unknown> = {\n ...properties,\n context,\n getRegistry(qopts?: { package?: string }): RegistryResult {\n // Build fresh on each call; addPlugin mutates `sdk` and\n // `context.meta` in place, so caching would go stale. Registry\n // build is O(N methods); we'll add versioned caching back if\n // profiling shows a hot path.\n return buildRegistry({\n sdk,\n meta: context.meta,\n packageFilter: qopts?.package,\n });\n },\n };\n return sdk;\n}\n\nfunction wrapAccumulatorAsSdk(acc: PluginAccumulator): Record<string, unknown> {\n // Strip the context back-reference off the root view: it's an\n // accumulator-internal detail (lets sub-plugins read context via\n // `view.context`), but the public sdk shape sets `context` directly\n // as its own property in `wrapAsSdk`.\n const { context: _ctx, ...rootKeys } = acc.view;\n return wrapAsSdk(\n rootKeys as Record<string, unknown>,\n acc.context,\n ) as unknown as Record<string, unknown>;\n}\n\n/**\n * Apply one plugin to an already-built `Sdk`, mutating the sdk and its\n * context in place. The plugin runs against the live sdk reference,\n * its contribution is split, and the result merges into `sdk` (root\n * methods) and `sdk.context` (meta, hooks, other context fields) via\n * the same `mergeContribution` primitive the stack walk uses. Used\n * by {@link addPlugin}; no rewrap, no second sdk identity.\n */\nexport function applyPluginToSdk(\n sdk: Record<string, unknown>,\n plugin: Plugin<unknown, PluginProvides>,\n options: { override?: boolean },\n): SplitPluginContribution {\n const context = sdk.context as {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n [key: string]: unknown;\n };\n const contribution = splitPluginContribution(\n plugin(sdk as never) as PluginProvides,\n );\n mergeContribution(sdk, context, contribution, {\n callerLabel: \"addPlugin\",\n override: options.override === true,\n });\n // The caller (addPlugin) keeps context.plugins/context.surface authoritative\n // from this; mergeContribution itself only touches sdk + context.meta/hooks.\n return contribution;\n}\n\n/**\n * One stack registration, resolved to its application slot. `apply` is the\n * plugin function; `override` lets it replace an earlier root/meta key.\n */\ninterface OrderedStackEntry {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n apply: Plugin<any, any>;\n override: boolean;\n}\n\n/**\n * Resolve a stack's cons list into application order: registration order,\n * oldest first. A legacy stack is a flat list of function plugins; dependency\n * ordering belongs to the new model's `createSdk`.\n */\nfunction resolveStack(head: PluginStackNode | null): OrderedStackEntry[] {\n const entries: OrderedStackEntry[] = [];\n let node = head;\n while (node) {\n entries.unshift({ apply: node.entry, override: node.override });\n node = node.prev;\n }\n return entries;\n}\n\n/** Compose hook contributions in registration order. */\nfunction composeStackHooks(hooks: MethodHooks[]): MethodHooks {\n let composed: MethodHooks = {};\n for (const h of hooks) composed = buildHooks(composed, h);\n return composed;\n}\n\n/**\n * Collapse resolved stack entries into a single bare plugin function:\n * the setup of the definition `toPlugin` emits, and the return value of\n * the deprecated `composePlugins`. Runs every entry against a view\n * seeded from the outer sdk and emits only this stack's contributions.\n */\nfunction collapseStackEntries(\n entries: OrderedStackEntry[],\n callerLabel: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Plugin<any, PluginProvides> {\n return ((outerSdk: unknown) => {\n // Two accumulators per collapse. `viewAcc` carries outerSdk's\n // properties so each sub-plugin can read what came in plus what\n // earlier sub-plugins added; sub-plugins receive `viewAcc.view`\n // directly (mutating, one allocation). `contribsAcc` tracks only\n // this stack's additions, since the returned plugin's value is\n // just the contributions and outerSdk's own keys are not re-emitted.\n const { context: outerContext, ...outerProperties } = (outerSdk ??\n {}) as Record<string, unknown> & {\n context?: {\n meta?: Record<string, PluginMeta>;\n [key: string]: unknown;\n };\n };\n const viewAcc = createPluginAccumulator(outerProperties, outerContext);\n const contribsAcc = createPluginAccumulator();\n const hooks: MethodHooks[] = [];\n\n for (const { apply, override } of entries) {\n const contribution = splitPluginContribution(\n apply(viewAcc.view as never) as PluginProvides,\n );\n // Hooks are withheld and composed once below: methods read\n // `context.hooks` live per call, so composing after the walk is fine.\n const hookless = { ...contribution, hooks: {} };\n applyPluginContribution(viewAcc, hookless, { callerLabel, override });\n applyPluginContribution(contribsAcc, hookless, { callerLabel, override });\n hooks.push(contribution.hooks);\n }\n\n const stackHooks = composeStackHooks(hooks);\n viewAcc.context.hooks = buildHooks(viewAcc.context.hooks, stackHooks);\n contribsAcc.context.hooks = stackHooks;\n\n // Strip the back-reference to context off the root view (it's an\n // accumulator-internal detail) and emit only what this stack\n // contributed at the root, plus the contributed context.\n const { context: _ignored, ...contributedRoot } = contribsAcc.view;\n return {\n ...contributedRoot,\n context: contribsAcc.context,\n } as never;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as Plugin<any, PluginProvides>;\n}\n\n/**\n * Walk a stack's resolved application order into a single populated\n * `PluginAccumulator`. Used by `toSdk` to materialize an SDK eagerly.\n * Differs from `toPlugin`'s emitted lazy plugin in two ways: there's no\n * outer sdk to seed from (the stack is the root), and we keep only one\n * accumulator (we don't need to separate \"outer's keys\" from \"this\n * stack's contributions\" because the stack IS the whole sdk).\n *\n * Hook contributions are withheld during the walk and composed once at\n * the end (see composeStackHooks): hook firing order is not application\n * order. Methods read `context.hooks` live per call, so composing after\n * the walk changes nothing for them.\n */\nfunction buildStackAccumulator(\n head: PluginStackNode | null,\n callerLabel: string,\n): PluginAccumulator {\n const entries = resolveStack(head);\n const acc = createPluginAccumulator();\n const hooks: MethodHooks[] = [];\n for (const { apply, override } of entries) {\n const contribution = splitPluginContribution(\n apply(acc.view as never) as PluginProvides,\n );\n applyPluginContribution(\n acc,\n { ...contribution, hooks: {} },\n { callerLabel, override },\n );\n hooks.push(contribution.hooks);\n }\n acc.context.hooks = composeStackHooks(hooks);\n return acc;\n}\n\n/**\n * @deprecated Use {@link createPluginStack} instead. It carries the same\n * collision-detection and hook-composition behavior and supports\n * per-step `{ override: true }` for intentional duplicates. Migration\n * (note the stack emits a definition, not a bare function):\n *\n * composePlugins(a, b, c)\n * // →\n * createPluginStack().use(a).use(b).use(c).toPlugin({ name: \"bundle\" })\n *\n * Bundles N plugins into a single plugin so a consumer can call\n * `.use(combined)` once on a stack. Bag mode: sub-plugins must not\n * depend on each other; TSdk on sub-plugins is the intersection of\n * every sub-plugin's requirements (so the type system never exposes\n * one sub-plugin's contributions to another).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function composePlugins<const Ts extends readonly Plugin<any, any>[]>(\n ...plugins: Ts\n): Plugin<ComposeSdk<Ts>, ComposeProvides<Ts>> {\n logDeprecation(\n \"composePlugins(...) is deprecated. Use createPluginStack().use(a).use(b).use(c).toPlugin({ name }) instead. \" +\n \"The stack carries the same collision-detection and hook-composition behavior \" +\n \"and supports per-step { override: true } for intentional duplicates.\",\n );\n // Route through the same linked-list machinery createPluginStack uses,\n // but collapse straight to the bare function: composePlugins predates\n // definitions and its consumers expect a callable plugin, not a\n // definition. composePlugins's \"bag mode\" contract holds because of\n // the type signature: TSdk on sub-plugins is ComposeSdk<Ts> (the\n // intersection of every sub-plugin's requirements), so the type system\n // never exposes one sub-plugin's contributions to another.\n let head: PluginStackNode | null = null;\n for (const plugin of plugins) {\n head = { entry: plugin, override: false, prev: head };\n }\n const entries = resolveStack(head);\n return collapseStackEntries(entries, \"composePlugins\") as Plugin<\n ComposeSdk<Ts>,\n ComposeProvides<Ts>\n >;\n}\n\n// ----------------------------------------------------------------------------\n// createPluginStack\n// ----------------------------------------------------------------------------\n// A lazy, immutable, linked-list-backed builder over plugin definitions and\n// bare plugin functions. Definitions apply in dependency order; bare\n// functions apply afterward in registration order (their pre-definition\n// semantics, kept until every plugin in every repo is a definition). Type\n// checking is deferred: `.use` accumulates needs and provides, and\n// `toPlugin` / `toSdk` become uncallable when a need is unprovided.\n\ninterface PluginStackNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Plugin<any, any>;\n override: boolean;\n prev: PluginStackNode | null;\n}\n\n/**\n * A typed builder that accumulates plugins into an immutable linked list.\n * Each `.use` returns a new stack instance (cons-style); the original\n * stack stays usable for branching. Call `toPlugin()` to collapse the\n * accumulated chain into a single `Plugin<TRequires, TProvides>`.\n *\n * Type params: `TRequires` is the external surface declared on\n * `createPluginStack<TRequires>()` (what the outer sdk will provide);\n * `TProvides` accumulates every registration's provides.\n */\nexport interface PluginStack<TRequires, TProvides extends PluginProvides> {\n /**\n * Register a bare plugin function. Its required surface is constrained\n * to `TRequires & TProvides` (the external requirements plus everything\n * provided by earlier `.use` calls), so registration order is enforced\n * per step: a plugin that reads a dependency at construction can only be\n * registered after a plugin that provides it. This stack collapses to a\n * single function plugin and runs its entries in registration order, so\n * the type-level order matches the runtime order.\n *\n * `{ override: true }` lets a registration replace an earlier root/meta\n * key it would otherwise collide with.\n */\n use<TNewProvides extends PluginProvides>(\n plugin: Plugin<TRequires & TProvides, TNewProvides>,\n options?: { override?: boolean },\n ): PluginStack<TRequires, TProvides & TNewProvides>;\n\n /**\n * Collapse the accumulated registrations into a single bare function\n * plugin. Its TSdk is `TRequires` (the declared external surface);\n * in-stack inter-plugin dependencies are resolved when its setup runs.\n * A head lifts it into the module model with `fromFunctionPlugin`.\n */\n toPlugin(): Plugin<TRequires, TProvides>;\n\n /**\n * Build the stack into a sealed, ready-to-use SDK. Eagerly applies the\n * resolved order: each plugin runs once during `toSdk`, contributions\n * merge into a single accumulator, and the result is wrapped as an\n * `Sdk<TRequires & TProvides>`. The returned SDK has `context` and\n * `getRegistry`, but no plugin-registration method.\n * To extend a built SDK, use the top-level {@link addPlugin}.\n */\n toSdk(): Sdk<TRequires & TProvides>;\n}\n\n/**\n * Create an empty plugin stack. Pass a type parameter to declare external\n * SDK requirements that every plugin in the stack can rely on:\n *\n * const tablesPlugin = createPluginStack<FetchPluginProvides>()\n * .use(apiPlugin)\n * .use(listTablesPlugin)\n * .use(getTablePlugin)\n * .toPlugin({ name: \"tables\" });\n *\n * const sdk = createPluginStack()\n * .use(fetchPlugin) // provides FetchPluginProvides\n * .use(tablesPlugin) // PluginDefinition<FetchPluginProvides, ...>\n * .toSdk();\n *\n * The stack itself is immutable: calling `.use` returns a new stack\n * without mutating the original, so you can branch off a base stack for\n * different consumers. Until the stack materializes, no plugin functions\n * run.\n */\nexport function createPluginStack<TRequires = object>(): PluginStack<\n TRequires,\n {\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n };\n }\n> {\n return buildPluginStack<\n TRequires,\n {\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n };\n }\n >(null, \"createPluginStack\");\n}\n\nfunction buildPluginStack<TRequires, TProvides extends PluginProvides>(\n head: PluginStackNode | null,\n callerLabel: string,\n): PluginStack<TRequires, TProvides> {\n const stack = {\n use(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n plugin: Plugin<any, any>,\n options?: { override?: boolean },\n ) {\n const next: PluginStackNode = {\n entry: plugin,\n override: options?.override === true,\n prev: head,\n };\n return buildPluginStack(next, callerLabel) as never;\n },\n\n toPlugin() {\n // Resolve application order once (so duplicate-name and cycle errors\n // surface here, not when the collapsed plugin runs), then return the\n // collapsed function plugin. A function keeps nested composition working\n // (`.use()` accepts a `toPlugin()` output) and existing consumers'\n // `Plugin<...>` annotations correct; a head lifts it into the new model\n // with `fromFunctionPlugin`.\n const entries = resolveStack(head);\n return collapseStackEntries(entries, callerLabel);\n },\n\n toSdk() {\n return wrapAccumulatorAsSdk(\n buildStackAccumulator(head, callerLabel),\n ) as unknown as Sdk<TRequires & TProvides>;\n },\n };\n return stack as unknown as PluginStack<TRequires, TProvides>;\n}\n","/** What an id segment names: a `leaf` name is a dot-accessed binding; an\n * `aggregate` name is identity only (never a binding). */\nexport type IdKind = \"leaf\" | \"aggregate\";\n\n/** Split an id into its binding `name` (the last segment) and `namespace` (the\n * rest), the inverse of `makeId`. Used by `declare*`, which address a plugin by\n * its full id rather than separate name/namespace. */\nexport function parseId(id: string): {\n name: string;\n namespace: string | undefined;\n} {\n const at = id.lastIndexOf(\"/\");\n return at === -1\n ? { name: id, namespace: undefined }\n : { name: id.slice(at + 1), namespace: id.slice(0, at) };\n}\n\n/** A plugin's id: `namespace/name`, or bare `name` when un-namespaced. */\nexport function makeId(\n name: string,\n namespace: string | undefined,\n kind: IdKind = \"leaf\",\n): string {\n validateName(name, kind);\n if (namespace !== undefined) validateNamespace(namespace);\n return namespace ? `${namespace}/${name}` : name;\n}\n\n/** A leaf's name is the dot-accessed binding (`sdk.name`, `imports.name`), so it\n * must be a valid JS identifier. */\nconst NAME_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** A package-like id segment: letters, digits, `.`, `_`, `-`, with an optional\n * leading `@` (npm scope). Used for namespace segments and aggregate names,\n * which are identity, not bindings. No `/` (it is the id separator), so a name\n * is always the final segment and `namespace/name` splits unambiguously. */\nconst SEGMENT_RE = /^@?[A-Za-z0-9._-]+$/;\n\nfunction validateName(name: string, kind: IdKind): void {\n if (name === \"\") throw new Error(\"Plugin name must not be empty.\");\n if (kind === \"leaf\") {\n if (!NAME_RE.test(name)) {\n throw new Error(\n `Plugin name \"${name}\" must be a valid JS identifier (it is the binding name).`,\n );\n }\n } else if (!SEGMENT_RE.test(name)) {\n throw new Error(\n `Plugin name \"${name}\" must be package-like (letters, digits, \".\", \"_\", ` +\n `\"-\", optional leading \"@\") with no \"/\".`,\n );\n }\n}\n\nfunction validateNamespace(namespace: string): void {\n if (namespace === \"\") throw new Error(\"Plugin namespace must not be empty.\");\n for (const segment of namespace.split(\"/\")) {\n if (!SEGMENT_RE.test(segment)) {\n throw new Error(\n `Plugin namespace \"${namespace}\" is invalid: each \"/\"-separated segment ` +\n `must be package-like (letters, digits, \".\", \"_\", \"-\", optional leading \"@\").`,\n );\n }\n }\n}\n","import type { z } from \"zod\";\nimport type { PluginMeta, PluginProvides } from \"../types/plugin\";\nimport type { MethodHooks } from \"../utils/build-hooks\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport type { RegistryResult } from \"../registry\";\nimport type {\n CategoryDefinition,\n FunctionDeprecation,\n} from \"../types/registry\";\nimport type {\n FormattedItem,\n ResolverPromptConfig,\n} from \"../utils/schema-utils\";\n\n/**\n * Descriptive metadata a leaf carries for the registry / CLI / MCP / docs:\n * description, categories, type, formatter, resolvers, etc.\n * Reuses the shipped `PluginMeta` minus `inputSchema`, which is a first-class\n * descriptor field (it also drives `input` typing and runtime validation).\n */\nexport type LeafMeta = Omit<PluginMeta, \"inputSchema\">;\n\n/**\n * The descriptive registry fields a `defineMethod` / `defineProperty` author\n * sets directly on the config (hoisted, not nested under a `meta` wrapper).\n * The impl folds whichever are present back into the stored `LeafMeta`. This is\n * the strict, explicit subset of `PluginMeta` (no `[key: string]: any` escape\n * hatch, no `inputSchema` / `formatter` / `resolvers` — those are first-class\n * config fields of their own).\n */\nexport interface LeafMetaFields {\n description?: string;\n categories?: (string | CategoryDefinition)[];\n type?: \"list\" | \"item\" | \"create\" | \"update\" | \"delete\" | \"function\";\n itemType?: string;\n returnType?: string;\n outputSchema?: z.ZodSchema;\n inputParameters?: Array<{ name: string; schema: z.ZodSchema }>;\n packages?: string[];\n experimental?: boolean;\n confirm?: \"create-secret\" | \"delete\";\n deprecation?: FunctionDeprecation;\n aliases?: Record<string, string>;\n supportsJsonOutput?: boolean;\n}\n\n/** The runtime keys of {@link LeafMetaFields}, used to fold the hoisted\n * fields back into the stored `LeafMeta`. Kept in sync with the interface. */\nexport const LEAF_META_KEYS = [\n \"description\",\n \"categories\",\n \"type\",\n \"itemType\",\n \"returnType\",\n \"outputSchema\",\n \"inputParameters\",\n \"packages\",\n \"experimental\",\n \"confirm\",\n \"deprecation\",\n \"aliases\",\n \"supportsJsonOutput\",\n] as const satisfies readonly (keyof LeafMetaFields)[];\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyMethodPlugin = MethodPlugin<string, any, any, readonly string[]>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyPropertyPlugin = PropertyPlugin<string, any>;\n/** A leaf plugin: a method (callable) or a property (value). */\nexport type AnyLeafPlugin = AnyMethodPlugin | AnyPropertyPlugin;\n\n/**\n * How a module declares its imports: an array. Each element binds under its own\n * name (a leaf under its name, a module under each of its export names); a\n * `selectExports(...)` element contributes its chosen bindings. To rename or\n * subset, wrap an element in `selectExports`; there is no alias-map form.\n */\nexport type ImportsInput = readonly AnyPlugin[];\n\n/** A resolved import edge: the local binding name and the plugin id it reads\n * from `context.plugins` (id, not identity, so a swap stays transparent). */\nexport interface ImportBinding {\n binding: string;\n id: string;\n}\n\n/**\n * Collapse a union to an intersection. Turns the per-dependency\n * `{ name: signature }` union into one `imports` object type.\n */\nexport type UnionToIntersection<U> = (\n U extends unknown ? (x: U) => void : never\n) extends (x: infer I) => void\n ? I\n : never;\n\n/**\n * A method's callable signature. A method with no declared input infers\n * `TInput = unknown`; make its input optional so it is callable with no\n * argument. An input whose properties are all optional (e.g. a `list` method\n * whose only input is the framework's `cursor` / `pageSize` / `maxItems`) is\n * also callable with no argument. A real required input keeps the arg required.\n */\nexport type MethodCall<TInput, TOutput> = [unknown] extends [TInput]\n ? (input?: TInput) => TOutput\n : {} extends TInput\n ? (input?: TInput) => TOutput\n : (input: TInput) => TOutput;\n\n/**\n * Project the canonical input through an ordered list of key names into a\n * positional argument tuple, preserving trailing-optionality: a key that is\n * optional in `TInput` becomes an optional argument (so `fetch(url)` is legal\n * when `init` is optional). A name that is not a key of `TInput` is an error.\n */\nexport type PositionalArgs<\n TInput,\n TNames extends readonly PropertyKey[],\n> = TNames extends readonly [\n infer Head extends keyof TInput,\n ...infer Tail extends readonly (keyof TInput)[],\n]\n ? {} extends Pick<TInput, Head>\n ? [arg?: TInput[Head], ...PositionalArgs<TInput, Tail>]\n : [arg: TInput[Head], ...PositionalArgs<TInput, Tail>]\n : [];\n\n/**\n * The public call signature of a method on the surface and in `imports`. With\n * no positional projection it is the canonical single-object `MethodCall`; with\n * one it is the positional signature derived from the input. Middleware does\n * NOT use this (its bag carries one canonical `input`); see `MiddlewareMap`.\n */\nexport type SurfaceCall<\n TInput,\n TOutput,\n TPositional extends readonly string[],\n> = TPositional extends readonly []\n ? MethodCall<TInput, TOutput>\n : (...args: PositionalArgs<TInput, TPositional>) => TOutput;\n\n/**\n * The bindings one array-form dependency contributes to `imports`: a leaf under\n * its own name (method callable or property value), an aggregate under each of\n * its export names.\n */\nexport type BindingsOf<TDep> =\n TDep extends MethodPlugin<\n infer TName,\n infer TInput,\n infer TOutput,\n infer TPositional\n >\n ? { [P in TName]: SurfaceCall<TInput, TOutput, TPositional> }\n : TDep extends PropertyPlugin<infer TName, infer TValue>\n ? { [P in TName]: TValue }\n : TDep extends AggregatePlugin<string, infer TExports>\n ? { [K in keyof TExports]: ExportSurface<TExports[K]> }\n : never;\n\n/**\n * The `imports` a body receives. Each element contributes its bindings\n * (`BindingsOf`); empty imports yield an empty object.\n */\nexport type ImportsOf<TImports extends ImportsInput> =\n TImports extends readonly []\n ? Record<never, never>\n : UnionToIntersection<\n { [K in keyof TImports]: BindingsOf<TImports[K]> }[number]\n >;\n\n/**\n * The bag a method body receives. `imports` is the dependency-narrowed reach;\n * `state` is the plugin's private constructor result (undefined when none);\n * `input` is the canonical call argument.\n */\nexport interface MethodRunBag<TImports, TInput, TState = unknown> {\n imports: TImports;\n state: TState;\n input: TInput;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Method attachments: input resolvers, output formatters. */\n/* */\n/* A resolver/formatter is NOT a node — it has no id, no surface, and nothing */\n/* imports it. It is an attachment that lives on a method's `resolvers` / */\n/* `formatter` field and declares its own `imports` (which is why it gets a */\n/* `define*` wrapper and `importBindings`, unlike middleware, which borrows */\n/* its owner's imports). At materialization the graph reaches an attachment's */\n/* imports (so they materialize + dedup) but they never enter the host */\n/* method's `importBindings`, so they cannot widen its run-bag or form a */\n/* `setup` cycle (a resolver may even import its own host method, the classic */\n/* exact-match-validation case). The materializer binds each attachment in a */\n/* late pass — capturing its imports — into the `Bound*` runtime forms the */\n/* registry / CLI / MCP consume with input only, no sdk. */\n/* -------------------------------------------------------------------------- */\n\n/** Shared plumbing for the method attachments: each declares its own\n * dependencies. Resolvers and formatters are otherwise separate concepts. */\nexport interface MethodAttachment {\n imports: readonly AnyPlugin[];\n /** Binding-name to plugin-id edges, normalized from `imports`; what the\n * narrowed bag captured at materialization is built from. */\n importBindings: readonly ImportBinding[];\n}\n\n/**\n * A resolver's kind, the discriminant of the {@link Resolver} union. Scalars\n * (`dynamic` / `static` / `constant`) resolve one value; `info` resolves none\n * (display-only); `object` / `array` compose nested resolvers. Names borrow\n * JSON Schema's structural vocabulary (`object`/`array`/`properties`/`items`),\n * but a resolver carries behavior (fetch/prompt), not validation.\n */\nexport type ResolverType =\n | \"dynamic\"\n | \"static\"\n | \"constant\"\n | \"info\"\n | \"object\"\n | \"array\";\n\n/**\n * A reference from a field (or array `items`) to a reusable resolver in the\n * nearest `definitions` block. `input` are merged into the referenced\n * resolver's `input` (e.g. the field key a shared choices-fetcher needs).\n * Used when a fetch-built field needs an import-bearing resolver, which can't\n * be inlined at fetch time (its imports bind at materialization).\n */\nexport interface ResolverRef {\n ref: string;\n input?: Record<string, unknown>;\n}\n\n/**\n * One member of an object resolver's `properties` (literal or fetch-built): the\n * resolver for the value plus its per-occurrence meta. `required` / `valueType`\n * live here, not on the resolver, because the same resolver can be required in\n * one object and optional in another, and a fetch-built field (no schema) has\n * nowhere else to carry them.\n */\nexport interface Field {\n resolver: Resolver | ResolverRef;\n label?: string;\n required?: boolean;\n valueType?: string;\n}\n\n/** Shared gates for resolvers that resolve a value: the attachment plumbing\n * plus the param-dataflow prerequisite. (`info` skips these.) */\nexport interface ResolverBase extends MethodAttachment {\n /** Sibling parameters that must resolve before this resolver runs (it reads\n * their values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. */\n requireParameters?: readonly string[];\n}\n\n/** List candidate items and prompt the user to pick one. */\nexport interface DynamicResolver extends ResolverBase {\n type: \"dynamic\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n /** Compute side-context once, before `listItems`, with the narrowed `imports`\n * bag (no items yet — it runs pre-fetch so it can shape the fetch). The result\n * flows into `listItems` and `prompt` as `context`. Use it to resolve, in one\n * place, anything both the fetch and the render need (e.g. a capability gate:\n * compute `includeShared` here, gate the fetch in `listItems`, surface a\n * `notes` hint in `prompt`). May run more than once across re-asks, so keep it\n * cheap/idempotent. */\n getContext?: (bag: {\n imports: Record<string, unknown>;\n input: Record<string, unknown>;\n }) => PromiseLike<unknown>;\n /** Produce the candidate list. Behaves like an SDK list method: returns a\n * paginated result (await for the first page + `nextCursor`, or iterate pages),\n * never a bare array. `cursor` is the stateless re-entry hook for \"load more\":\n * an in-process host iterates the result; a distributed host awaits one page,\n * carries `nextCursor`, and calls again with `cursor`. */\n listItems?: (bag: {\n imports: Record<string, unknown>;\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n /** Free-text term injected by the CLI for search-mode resolvers. A separate\n * key, not part of `input`, so it never collides with a method parameter\n * also named `search`. */\n search?: string;\n cursor?: string;\n }) => ListItemsResult<unknown>;\n prompt?: (bag: {\n items: unknown[];\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n }) => ResolverPromptConfig;\n /** Resolve with no user input at all (e.g. a configured default), skipping the\n * prompt. Runs before prompting; used always in non-interactive mode and as a\n * \"can we skip asking?\" check otherwise. Returns null to fall through to a prompt. */\n tryResolveWithoutPrompt?: (bag: {\n imports: Record<string, unknown>;\n input: Record<string, unknown>;\n }) => Promise<{ resolvedValue: unknown } | null>;\n /** Search-mode exact match: the user typed `search`; if it already names a\n * valid value (e.g. validated via the API), return it to skip the picker.\n * Distinct from `tryResolveWithoutPrompt` (no input) — this is interactive,\n * mid-prompt, with the typed term. Returns null to fall through to `listItems`. */\n tryResolveFromSearch?: (bag: {\n imports: Record<string, unknown>;\n input: Record<string, unknown>;\n search?: string;\n }) => Promise<{ resolvedValue: unknown } | null>;\n}\n\n/** Free-text input, no candidate list. */\nexport interface StaticResolver extends ResolverBase {\n type: \"static\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n}\n\n/** A fixed value, no prompt. */\nexport interface ConstantResolver extends ResolverBase {\n type: \"constant\";\n value: unknown;\n}\n\n/** Display-only text; resolves no value (its key is skipped in the result). */\nexport interface InfoResolver extends MethodAttachment {\n type: \"info\";\n text: string;\n}\n\n/** A keyed object. `properties` are known up front; `getProperties` builds them\n * when the key set is dynamic (re-invoked as `input` grow, for depends-on\n * fields). Returns the property map raw (no envelope: nothing to paginate).\n * `definitions` holds reusable resolvers reached by `{ ref }` from built fields\n * that need an import. */\nexport interface ObjectResolver extends ResolverBase {\n type: \"object\";\n properties?: Record<string, Field>;\n getProperties?: (bag: {\n imports: Record<string, unknown>;\n input: Record<string, unknown>;\n }) => PromiseLike<Record<string, Field>>;\n definitions?: Record<string, Resolver>;\n}\n\n/** A homogeneous list: each element resolves through `items`. */\nexport interface ArrayResolver extends ResolverBase {\n type: \"array\";\n items: Resolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n /** Coarse value type of each element, so a free-text item answer coerces\n * (e.g. `\"5\"` → `5` for `z.array(z.number())`) the way object fields do via\n * `Field.valueType`. `items` is a bare resolver with no `valueType` slot of\n * its own, so the element type rides here. */\n itemValueType?: string;\n definitions?: Record<string, Resolver>;\n}\n\n/**\n * An input resolver descriptor (produced by `defineResolver`, attached to a\n * method parameter). A discriminated union on `type`; composites (`object` /\n * `array`) recurse. Callbacks take a narrowed `imports` bag; the materializer\n * captures it and produces a {@link BoundResolver}. Stored loosely (the precise\n * `imports` / item / param types live on the `defineResolver` config), like\n * `MethodPlugin.run`.\n */\nexport type Resolver =\n | DynamicResolver\n | StaticResolver\n | ConstantResolver\n | InfoResolver\n | ObjectResolver\n | ArrayResolver;\n\n/**\n * An output formatter descriptor (produced by `defineFormatter`, attached to a\n * method's output). `getContext` reaches the narrowed `imports` bag; the\n * materializer captures it and produces a {@link BoundFormatter}. Stored\n * loosely, like {@link Resolver}. Both callbacks receive the method's `input`\n * (the formatter runs post-execution, so the input is complete, unlike a\n * resolver's partial `input`).\n */\nexport interface Formatter extends MethodAttachment {\n getContext?: (bag: {\n imports: Record<string, unknown>;\n items: unknown[];\n input: Record<string, unknown>;\n context?: unknown;\n }) => Promise<unknown>;\n format: (bag: {\n item: unknown;\n input: Record<string, unknown>;\n context?: unknown;\n }) => FormattedItem;\n}\n\n/** What a dynamic resolver's `listItems` yields: an SDK list-method result\n * (`await` for the first page + `nextCursor`, or iterate pages in-process), or a\n * plain page / promise of one. No bare array and no scalar: it behaves like any\n * other list method, and exact-match short-circuits live on `tryResolveFromSearch`. */\nexport type ListItemsResult<TItem> =\n | PaginatedSdkResult<TItem>\n | SdkPage<TItem>\n | Promise<SdkPage<TItem>>;\n\n/** A bound object resolver's literal property: its resolver is already bound\n * (or a `{ ref }` the CLI resolves against `definitions` at runtime). */\nexport interface BoundField {\n resolver: BoundResolver | ResolverRef;\n label?: string;\n required?: boolean;\n valueType?: string;\n}\n\n/**\n * The runtime resolver `defineResolver` binds to: its imports are already\n * captured, so the CLI calls these with input (and `search`) only, no sdk.\n * `prompt` stays pure (no SDK reach).\n *\n * Carries every kind's fields on one loose interface, discriminated by `type`.\n * The CLI rewrite (the consumer) narrows this into per-kind shapes; until then\n * a single shape keeps the binder simple. `listItems` produces the candidate\n * list for `dynamic`; `getProperties` builds the (unbound) property map for\n * `object`. `properties` / `definitions` are bound; `items` is bound (or a ref).\n */\nexport interface BoundResolver {\n type: ResolverType;\n /** Sibling parameters that must resolve before this resolver runs (it reads\n * their values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. */\n requireParameters?: readonly string[];\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n value?: unknown;\n text?: string;\n properties?: Record<string, BoundField>;\n definitions?: Record<string, BoundResolver>;\n items?: BoundResolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n /** For an array: the element's coarse value type, used to coerce a free-text\n * item answer before validation (see {@link ArrayResolver.itemValueType}). */\n itemValueType?: string;\n getContext?: (bag: {\n input: Record<string, unknown>;\n }) => PromiseLike<unknown>;\n listItems?: (bag: {\n input: Record<string, unknown>;\n context?: unknown;\n search?: string;\n cursor?: string;\n }) => ListItemsResult<unknown>;\n getProperties?: (bag: {\n input: Record<string, unknown>;\n }) => PromiseLike<Record<string, Field>>;\n prompt?: (bag: {\n items: unknown[];\n input: Record<string, unknown>;\n context?: unknown;\n }) => ResolverPromptConfig;\n tryResolveWithoutPrompt?: (bag: {\n input: Record<string, unknown>;\n }) => Promise<{ resolvedValue: unknown } | null>;\n tryResolveFromSearch?: (bag: {\n input: Record<string, unknown>;\n search?: string;\n }) => Promise<{ resolvedValue: unknown } | null>;\n}\n\n/**\n * The runtime formatter `defineFormatter` binds to: `getContext` runs once per\n * rendered batch (imports captured, no sdk) to build shared context; `format`\n * is pure and synchronous, turning one item + context into a `FormattedItem`.\n */\nexport interface BoundFormatter<\n TItem = unknown,\n TInput = Record<string, unknown>,\n TContext = unknown,\n> {\n getContext?: (bag: {\n items: TItem[];\n input: TInput;\n context?: TContext;\n }) => Promise<TContext>;\n format: (bag: {\n item: TItem;\n input: TInput;\n context?: TContext;\n }) => FormattedItem;\n}\n\n/**\n * A leaf plugin that is a single function: it IS the method. `pluginType` is\n * the node-kind discriminant; `name` is its identity and default\n * binding name. `imports` are the other plugins it depends on. The stored\n * `run` is loosely typed for `imports` (the precise type lives on the\n * `defineMethod` authoring surface, like the shipped definePlugin).\n */\nexport interface MethodPlugin<\n TName extends string = string,\n TInput = unknown,\n TOutput = unknown,\n TPositional extends readonly string[] = readonly [],\n> {\n pluginType: \"method\";\n name: TName;\n namespace?: string;\n /** `namespace/name`, or bare `name`. The `context.plugins` key. */\n id: string;\n /** True for a `declareMethod` stand-in: a typed reference with no real\n * implementation. A real plugin under the same id satisfies it. */\n standIn?: boolean;\n imports: readonly AnyPlugin[];\n /** Binding-name to plugin-id edges, normalized from `imports`;\n * what the `imports` bag is built from. */\n importBindings: readonly ImportBinding[];\n /** Optional per-materialization constructor: runs once at createSdk\n * (dependencies first), may side-effect, and returns the method's private\n * state (delivered to `run` as `bag.state`). */\n setup?: (bag: { imports: Record<string, unknown> }) => unknown;\n /** Validates `input` before `run` and drives the authoring `input` type. */\n inputSchema?: z.ZodType;\n /** Descriptive metadata for the registry / CLI / MCP / docs (carry-only at\n * runtime). */\n meta?: LeafMeta;\n /** Per-parameter input resolvers (method attachments). Reached for\n * materialization and bound into the entry at createSdk; a reachability-only\n * edge whose imports never enter this method's `importBindings`. */\n resolvers?: Record<string, Resolver>;\n /** Output formatter (method attachment). Bound into the entry at createSdk. */\n formatter?: Formatter;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: (bag: MethodRunBag<any, TInput, any>) => TOutput;\n /** How `run`'s result is shaped into the public surface (see Output in the\n * design doc). Omitted is \"raw\". Stored loosely; the precise per-mode typing\n * lives on the `defineMethod` overloads. */\n output?: OutputConfig;\n /** Positional projection (see Output): ordered keys of the canonical input\n * that the public surface and imports take as positional arguments. The\n * framework packs them back into `{ input }` before validation, middleware,\n * and `run`, so internals stay canonical. The runtime reads this loose field;\n * the precise names ride the `TPositional` type param for surface typing. */\n positional?: readonly string[];\n /**\n * Phantom: carries the positional names as a tuple type so `BindingsOf` /\n * `ExportSurface` can render the positional signature. Never present at\n * runtime; the loose `positional` field above is the runtime carrier.\n * @internal\n */\n readonly [POSITIONAL_NAMES]?: TPositional;\n}\n\n/** Phantom-only key (see `MethodPlugin`); never set at runtime. */\ndeclare const POSITIONAL_NAMES: unique symbol;\n\n/** A method's output mode: raw passthrough, a `{ data }` item envelope, or a\n * paginated list. */\nexport type OutputMode = \"raw\" | \"item\" | \"list\";\n\n/** The authoring value for `output`: a bare mode string, or the object form\n * (which carries list options). */\nexport type OutputConfig =\n | OutputMode\n | { type: \"raw\" }\n | { type: \"item\" }\n | {\n type: \"list\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n adaptPage?: (response: any) => SdkPage<any>;\n defaultPageSize?: number;\n };\n\n/** Normalized output config: always the object form with a resolved `type`. */\nexport interface NormalizedOutput {\n type: OutputMode;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n adaptPage?: (response: any) => SdkPage<any>;\n defaultPageSize?: number;\n}\n\n/** Framework-injected page controls a list method's `run` receives. */\nexport type PageFetchInput = { cursor?: string; pageSize?: number };\n/** Page controls a list method's public caller may pass. */\nexport type PaginatedCallInput = PageFetchInput & { maxItems?: number };\n\n/**\n * A response whose only own keys are `data` / `nextCursor`. Gates the\n * list-standard overload: a raw envelope with extra keys is not a `StrictPage`\n * and falls through to the adapted overload, where `adaptPage` is required.\n */\nexport type StrictPage<TResponse> = SdkPage<unknown> & {\n [K in Exclude<keyof TResponse, keyof SdkPage<unknown>>]?: never;\n};\n\n/** Item type sourced from a page-ish response. */\nexport type ItemOf<TResponse> =\n TResponse extends SdkPage<infer TItem>\n ? TItem\n : TResponse extends { data: readonly (infer TItem)[] }\n ? TItem\n : never;\n\n/** The loose, mode-agnostic config the overloads all collapse to; what the\n * `defineMethod` implementation actually consumes. Each `defineMethod` overload\n * is a typed view over this. */\nexport interface DefineMethodConfig extends LeafMetaFields {\n name: string;\n namespace?: string;\n imports?: ImportsInput;\n inputSchema?: z.ZodType;\n output?: OutputConfig;\n positional?: readonly string[];\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: any) => unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: (bag: any) => unknown;\n}\n\n/**\n * A leaf plugin that is a single value (not a function). `value` is a static\n * constant; `get({ imports })` computes the value from imports. Like a\n * method's `setup`, `get` runs eagerly at createSdk (dependencies first), so a\n * module-level value is built on import. An imported/surfaced property yields\n * the value, not a callable.\n */\nexport interface PropertyPlugin<\n TName extends string = string,\n TValue = unknown,\n> {\n pluginType: \"property\";\n name: TName;\n namespace?: string;\n /** `namespace/name`, or bare `name`. The `context.plugins` key. */\n id: string;\n /** True for a `declareProperty` stand-in: a typed reference with no value. A\n * real property under the same id satisfies it. */\n standIn?: boolean;\n imports: readonly AnyPlugin[];\n /** Binding-name to plugin-id edges, normalized from `imports`;\n * what the `imports` bag is built from. */\n importBindings: readonly ImportBinding[];\n /** Optional once-eager constructor (the property twin of a method's `setup`):\n * runs once at createSdk (dependencies first), may side-effect, and returns the\n * private state delivered to `get` as `bag.state`. */\n setup?: (bag: { imports: Record<string, unknown> }) => unknown;\n value?: TValue;\n /** A live getter: computes the value from imports and `setup` state on each\n * read (not once). The stored shape is loose; the precise typing lives on the\n * `defineProperty` overloads. */\n get?: (bag: { imports: Record<string, unknown>; state: unknown }) => TValue;\n /** Descriptive metadata for the registry / CLI / MCP / docs (carry-only). */\n meta?: LeafMeta;\n /** A built-in whose value is the live `SdkContext`, injected at\n * materialization. Reserved for kitcore's own plugins;\n * authors use `value` / `get`. */\n privileged?: boolean;\n}\n\n/**\n * A middleware function wrapping one of the aggregate's imported methods.\n * `next` invokes the next layer (an inner wrap, ultimately the core method);\n * `imports` is the middleware plugin's own dependency reach; `input` is the\n * canonical call argument. It must preserve the target's contract; the\n * `MiddlewareMap` typing on `definePlugin` enforces that statically.\n */\nexport type MiddlewareFn = (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n next: (input: any) => any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * The authoring type for an aggregate's `middleware`: a map\n * whose keys are the method bindings among `imports` (you can only wrap a\n * method you import) and whose values are contract-preserving wraps. `next` and\n * `input` take the target's input and the wrap must return the target's output,\n * so a wrap that changes the public signature, or that targets a non-imported /\n * non-method binding, does not compile.\n */\nexport type MiddlewareMap<TImports> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof TImports as TImports[K] extends (input: any) => any\n ? K\n : never]?: TImports[K] extends (input: infer TInput) => infer TOutput\n ? (bag: {\n imports: TImports;\n next: (input: TInput) => TOutput;\n input: TInput;\n }) => TOutput\n : never;\n};\n\n/**\n * An aggregate plugin: it re-exports child plugins under binding names. Has no\n * body of its own; composition is \"declare what to re-export\".\n * `exports` keys are binding names; re-exporting a child implies a dependency\n * on it (it is pulled into the graph). `imports` lists extra internal\n * plugins to materialize that are not re-exported. `middleware` wraps imported\n * methods, keyed by the target's binding name.\n */\n/**\n * How a module declares its `exports`: an array, mirroring {@link ImportsInput}. A\n * leaf binds under its own `name`; a module (or `selectExports(...)`)\n * contributes each of its export bindings (spread). A binding-name collision\n * throws (wrap one in `selectExports` to rename).\n */\nexport type ExportsInput = readonly (AnyLeafPlugin | AnyAggregatePlugin)[];\n\n/** The export record one array element contributes: a leaf under its own name,\n * a module under each of its export bindings. */\ntype ElementExports<E> =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n E extends MethodPlugin<infer N, any, any, any>\n ? { [K in N]: E }\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n E extends PropertyPlugin<infer N, any>\n ? { [K in N]: E }\n : E extends AggregatePlugin<string, infer TE>\n ? TE\n : never;\n\n/**\n * The canonical export record an aggregate stores: each array element's\n * bindings merged, so every downstream consumer sees a `Record<binding, leaf>`.\n */\nexport type ArrayExports<\n T extends readonly (AnyLeafPlugin | AnyAggregatePlugin)[],\n> = T extends readonly []\n ? Record<never, never>\n : UnionToIntersection<{ [I in keyof T]: ElementExports<T[I]> }[number]>;\n\nexport interface AggregatePlugin<\n TName extends string = string,\n TExports extends Record<string, AnyLeafPlugin> = Record<\n string,\n AnyLeafPlugin\n >,\n> {\n pluginType: \"aggregate\";\n name: TName;\n namespace?: string;\n /** `namespace/name`, or bare `name`. The `context.plugins` key. */\n id: string;\n /** True for a `declarePlugin` stand-in: a typed reference to a whole module\n * with no implementation. A real aggregate under the same id satisfies it. */\n standIn?: boolean;\n imports: readonly AnyPlugin[];\n /** Binding-name to plugin-id edges, normalized from `imports`; what a\n * middleware wrap's `imports` is built from, and how a middleware target\n * binding resolves to a method id. */\n importBindings: readonly ImportBinding[];\n exports: TExports;\n middleware?: Record<string, MiddlewareFn>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyAggregatePlugin = AggregatePlugin<string, Record<string, any>>;\n\n/**\n * A legacy bridge plugin: wraps an old function plugin\n * (`(sdk) => provides`) so it materializes inside the new graph. At\n * materialization it runs `run` against a live compat view, merges the\n * returned context contributions into the shared `SdkContext`, and synthesizes\n * a `context.plugins` entry per root key. `TSurface` is the surfaced shape (the\n * provides minus `context`). This is the single shape `createPluginStack()\n * .toPlugin()` emits; there is no separate interim definition format.\n */\nexport interface LegacyPlugin<TSurface = Record<string, unknown>> {\n pluginType: \"legacy\";\n name: string;\n namespace?: string;\n /** `namespace/name`, or bare `name`. The `context.plugins` key. */\n id: string;\n imports: readonly AnyPlugin[];\n importBindings: readonly ImportBinding[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: (sdk: any) => PluginProvides;\n /** Type-only carrier for the surfaced shape; never set at runtime. */\n readonly __surface?: TSurface;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyLegacyPlugin = LegacyPlugin<any>;\nexport type AnyPlugin = AnyLeafPlugin | AnyAggregatePlugin | AnyLegacyPlugin;\n\n/**\n * A transitional root that merges a legacy function-plugin stack with the\n * module-model plugins migrated off it (see Migration order). At `createSdk` it\n * lifts and runs the legacy stack (like `fromFunctionPlugin`), materializes the\n * module-model `plugin`, and surfaces the union: the legacy stack's methods plus\n * the module plugin's exports. The migrated plugins live in one `plugin`\n * aggregate, so each migration only edits that aggregate's exports, not the\n * heads. Deleted once every plugin is module-model.\n */\nexport interface LegacyMergePlugin<\n TProvides extends PluginProvides = PluginProvides,\n TPlugin extends AnyPlugin = AnyPlugin,\n> {\n pluginType: \"legacy-merge\";\n name: string;\n namespace?: string;\n id: string;\n /** The lifted legacy stack (one node). */\n legacy: LegacyPlugin<\n TProvides & {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n }\n >;\n /** The module-model plugins migrated off the legacy stack. */\n plugin: TPlugin;\n}\n\n/** One middleware layer on a method's chain: the wrap and its owning aggregate\n * (whose `imports` the wrap receives, built live at call time). */\nexport interface MiddlewareWrap {\n run: MiddlewareFn;\n owner: AnyAggregatePlugin;\n}\n\n/** A materialized method: a stable callable `value` that folds `chain` around\n * the core at call time. The chain is ordered dependents-outermost; it is\n * mutable so post-seal `addPlugin` middleware can append. */\nexport interface MethodEntry {\n pluginType: \"method\";\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value: (input: any) => any;\n chain: MiddlewareWrap[];\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n inputSchema?: z.ZodType;\n meta?: LeafMeta;\n /** Resolved output mode; the registry derives presentation from it. */\n output?: NormalizedOutput;\n /** Positional input projection (see Output): ordered canonical-input keys the\n * public callable / imports take as positional args. */\n positional?: readonly string[];\n /** Bound input resolvers (their imports captured at materialization), keyed by\n * param name. The CLI calls these with input only, no sdk. */\n resolvers?: Record<string, BoundResolver>;\n /** Bound output formatter (imports captured at materialization). */\n formatter?: BoundFormatter;\n}\n\n/** A materialized property: a static `value`, or a live `getValue` thunk that\n * re-derives the value per read (consumers install it as a getter on the surface\n * and on `imports`). Exactly one of `value` / `getValue` is set. */\nexport interface PropertyEntry {\n pluginType: \"property\";\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getValue?: () => any;\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n meta?: LeafMeta;\n}\n\n/** A materialized aggregate: its resolved export bindings to child values\n * (a method's callable or a property's value). */\nexport interface AggregateEntry {\n pluginType: \"aggregate\";\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exports: Record<string, any>;\n}\n\n/** An entry in `context.plugins`. The `value`\n * of a method entry is its callable; of a property entry, its value. */\nexport type PluginEntry = MethodEntry | PropertyEntry | AggregateEntry;\n\n/**\n * The materialization substrate: every reachable plugin keyed by\n * id, plus the legacy-compat surface used during migration. The\n * compat fields let adapted function plugins read/write `context` exactly as\n * they do on the shipped stack: `meta` is the per-method registry source, `hooks`\n * the composed lifecycle hooks, and the index signature covers arbitrary legacy\n * fields a function plugin contributes (`api`, `options`, `manifest` helpers,\n * ...). A pure module-model SDK leaves `meta`/`hooks` empty and uses entry-level\n * metadata instead.\n */\nexport interface SdkContext {\n plugins: Record<string, PluginEntry>;\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n /** The SDK surface: each callable/value binding name mapped to the leaf plugin\n * id it resolves to. This is what the consumer actually calls (the root's\n * re-exports plus `addPlugin` additions), so the registry reports entries by\n * binding (with meta from the leaf) rather than dumping `plugins` by id. An\n * aliased re-export (`{ hi: greet }`) appears here as `hi -> \"greet\"`. */\n surface: Record<string, string>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\n/** The surfaced shape of one re-exported child: a method's callable or a\n * property's value. */\nexport type ExportSurface<TChild extends AnyLeafPlugin> =\n TChild extends MethodPlugin<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n infer TInput,\n infer TOutput,\n infer TPositional\n >\n ? SurfaceCall<TInput, TOutput, TPositional>\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TChild extends PropertyPlugin<any, infer TValue>\n ? TValue\n : never;\n\n/**\n * The framework-owned access an SDK carries beyond its string surface: the\n * legacy `context` string key (back-compat, narrows away later). The off-surface\n * `[CONTEXT]` symbol is attached at runtime (reach it via `getContext`) but kept\n * out of this type so it never leaks into a consumer's emitted declarations.\n */\nexport type SdkInternals = { context: SdkContext };\n\n/**\n * The materialized SDK for a leaf root: the root's callable (method) or value\n * (property) under its name, plus framework access.\n */\nexport type Sdk<\n TName extends string,\n TInput,\n TOutput,\n TPositional extends readonly string[] = readonly [],\n> = {\n [K in TName]: SurfaceCall<TInput, TOutput, TPositional>;\n} & SdkInternals;\n\n/** The materialized SDK for a property root: the value under its name. */\nexport type PropertySdk<TName extends string, TValue> = {\n [K in TName]: TValue;\n} & SdkInternals;\n\n/**\n * The materialized SDK for an aggregate root: each export binding becomes a\n * surface entry, typed from the re-exported child (callable for a method,\n * value for a property).\n */\nexport type AggregateSdk<TExports extends Record<string, AnyLeafPlugin>> = {\n [K in keyof TExports]: ExportSurface<TExports[K]>;\n} & SdkInternals;\n\n/**\n * The surface a plugin adds to an SDK when passed to `addPlugin`: a method\n * under its name, a property's value, an aggregate's export bindings, or a\n * legacy function plugin's root provides (minus `context`).\n */\nexport type AddedSurface<P> =\n P extends MethodPlugin<\n infer TName,\n infer TInput,\n infer TOutput,\n infer TPositional\n >\n ? { [K in TName]: SurfaceCall<TInput, TOutput, TPositional> }\n : P extends PropertyPlugin<infer TName, infer TValue>\n ? { [K in TName]: TValue }\n : P extends AggregatePlugin<string, infer TExports>\n ? { [K in keyof TExports]: ExportSurface<TExports[K]> }\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n P extends (sdk: any) => infer TProvides\n ? TProvides extends PluginProvides\n ? Omit<TProvides, \"context\">\n : Record<never, never>\n : Record<never, never>;\n\n/* -------------------------------------------------------------------------- */\n/* Compile-time dependency completeness (the requirements ledger). */\n/* */\n/* A `define*` return intersects a `PluginSummary` carrying, in the type, the */\n/* ids its subgraph still needs (`Requires`) and the ids it provides */\n/* (`Provides`). These are computed at the define call, where the `imports` / */\n/* `exports` tuple is still precise, so `createSdk` can verify completeness */\n/* without re-reading the stored (widened `readonly AnyPlugin[]`) field. */\n/* -------------------------------------------------------------------------- */\n\n/** `T` when it is a specific string literal, else `never`. Used on a stand-in's\n * `name` so the id is always captured as a literal: a widened `string` (or the\n * stale `declareMethod<TInput, TOutput>(...)` call shape, where the contract\n * lands in the name slot) is rejected at the call rather than silently\n * weakening the requirements ledger. */\nexport type LiteralString<T extends string> = string extends T ? never : T;\n\ndeclare const REQUIRES: unique symbol;\ndeclare const PROVIDES: unique symbol;\n\n/** Phantom carriers for the requirements ledger; never present at runtime. */\nexport interface PluginSummary<\n TRequires extends string = never,\n TProvides extends string = never,\n> {\n /** Declaration ids the plugin's subgraph still needs. @internal */\n readonly [REQUIRES]?: TRequires;\n /** Ids the plugin and its subgraph provide. @internal */\n readonly [PROVIDES]?: TProvides;\n}\n\n/** The declaration ids a plugin still needs (reads the phantom carrier). */\nexport type RequiresOf<P> = P extends { readonly [REQUIRES]?: infer R }\n ? Extract<R, string>\n : never;\n/** The ids a plugin and its subgraph provide (reads the phantom carrier). */\nexport type ProvidesOf<P> = P extends { readonly [PROVIDES]?: infer R }\n ? Extract<R, string>\n : never;\n\n/** Union the requires / provides across an inline imports or exports tuple. */\nexport type RequiresIn<T extends readonly unknown[]> = RequiresOf<T[number]>;\nexport type ProvidesIn<T extends readonly unknown[]> = ProvidesOf<T[number]>;\n\n/**\n * Reject an `imports` / `exports` value whose type widened to a non-tuple\n * `Plugin[]`: a literal tuple has a literal `length`, a widened array has\n * `length: number`. Identity in the good (tuple) case, so `T & StaticList<T>`\n * infers `T` unchanged; an error brand in the bad case, which the passed array\n * is not assignable to.\n */\nexport type StaticList<T extends readonly unknown[]> =\n number extends T[\"length\"]\n ? {\n readonly __kitcoreError: \"must be a fixed inline list of plugins, not a widened Plugin[]; declare them inline so the dependency graph stays statically known\";\n }\n : T;\n\n/** A leaf provides its own name plus whatever its imports provide. */\nexport type LeafProvides<\n TName extends string,\n TImports extends readonly unknown[],\n> = TName | ProvidesIn<TImports>;\n/** A leaf requires its imports' requirements, minus what it provides. */\nexport type LeafRequires<\n TName extends string,\n TImports extends readonly unknown[],\n> = Exclude<RequiresIn<TImports>, LeafProvides<TName, TImports>>;\n\n/** An aggregate provides its own name plus its imports' and exports' provides. */\nexport type AggregateProvides<\n TName extends string,\n TImports extends readonly unknown[],\n TExports extends readonly unknown[],\n> = TName | ProvidesIn<TImports> | ProvidesIn<TExports>;\n/** An aggregate requires its imports' and exports' requirements, minus provides. */\nexport type AggregateRequires<\n TName extends string,\n TImports extends readonly unknown[],\n TExports extends readonly unknown[],\n> = Exclude<\n RequiresIn<TImports> | RequiresIn<TExports>,\n AggregateProvides<TName, TImports, TExports>\n>;\n\n/** A plugin's id as a type: `namespace/name`, or bare `name` when the namespace\n * is empty. The ledger keys on this (matching runtime id resolution), not the\n * bare name, so same-named plugins in different namespaces stay distinct. */\nexport type IdOf<\n TNamespace extends string,\n TName extends string,\n> = TNamespace extends \"\" ? TName : `${TNamespace}/${TName}`;\n\n/** The binding name of an id: its last `/`-separated segment. The inverse view\n * of `IdOf`, used by `declare*` to derive the bare binding from a full id. */\nexport type LastSegment<TId extends string> =\n TId extends `${string}/${infer Rest}` ? LastSegment<Rest> : TId;\n\n/** The `PluginSummary` a leaf carries, keyed on its full id. */\nexport type LeafSummary<\n TNamespace extends string,\n TName extends string,\n TImports extends readonly unknown[],\n> = PluginSummary<\n LeafRequires<IdOf<TNamespace, TName>, TImports>,\n LeafProvides<IdOf<TNamespace, TName>, TImports>\n>;\n\n/** The `PluginSummary` an aggregate carries, keyed on its full id. */\nexport type AggregateSummary<\n TNamespace extends string,\n TName extends string,\n TImports extends readonly unknown[],\n TExports extends readonly unknown[],\n> = PluginSummary<\n AggregateRequires<IdOf<TNamespace, TName>, TImports, TExports>,\n AggregateProvides<IdOf<TNamespace, TName>, TImports, TExports>\n>;\n\n/** Surfaced by `createSdk` when reachable declarations have no provider. */\nexport interface MissingDependencies<TIds extends string> {\n readonly __kitcoreError: \"Missing concrete provider(s) for required declaration id(s)\";\n readonly missing: TIds;\n}\n\n/**\n * `unknown` when every reachable declaration is provided, otherwise a\n * `MissingDependencies` brand. `createSdk` takes `root: P & CompletenessOf<P>`,\n * so a complete root infers `P` unchanged (intersect `unknown`) while an\n * incomplete one fails to assign (the argument lacks `missing`).\n */\nexport type CompletenessOf<P> = [\n Exclude<RequiresOf<P>, ProvidesOf<P>>,\n] extends [never]\n ? unknown\n : MissingDependencies<Exclude<RequiresOf<P>, ProvidesOf<P>>>;\n\n/** Recover the materialized SDK type for a checked root (the summary that\n * rides on the `define*` return is transparent to these). */\nexport type MethodSdkOf<P> =\n P extends MethodPlugin<infer TName, infer TInput, infer TOutput, infer TPos>\n ? Sdk<TName, TInput, TOutput, TPos>\n : never;\nexport type PropertySdkOf<P> =\n P extends PropertyPlugin<infer TName, infer TValue>\n ? PropertySdk<TName, TValue>\n : never;\nexport type AggregateSdkOf<P> =\n P extends AggregatePlugin<string, infer TExports>\n ? AggregateSdk<TExports>\n : never;\n","import type { z } from \"zod\";\nimport type { PluginMeta, PluginProvides } from \"../types/plugin\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport type {\n FormattedItem,\n PromptConfig,\n ResolverPromptConfig,\n} from \"../utils/schema-utils\";\nimport { makeId, parseId } from \"./shared\";\nimport { LEAF_META_KEYS } from \"./types\";\nimport type {\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyPlugin,\n AggregatePlugin,\n ArrayExports,\n DefineMethodConfig,\n Formatter,\n ImportsInput,\n ExportsInput,\n ImportBinding,\n ImportsOf,\n ItemOf,\n LeafMeta,\n LeafMetaFields,\n MethodPlugin,\n MethodRunBag,\n MiddlewareFn,\n MiddlewareMap,\n PageFetchInput,\n PaginatedCallInput,\n PropertyPlugin,\n Resolver,\n ResolverRef,\n ListItemsResult,\n ResolverType,\n Field,\n DynamicResolver,\n StaticResolver,\n ConstantResolver,\n InfoResolver,\n ObjectResolver,\n ArrayResolver,\n StrictPage,\n PluginSummary,\n StaticList,\n LiteralString,\n IdOf,\n LastSegment,\n LeafSummary,\n AggregateSummary,\n} from \"./types\";\n\n/**\n * Normalize the imports array to the plugin list (for the graph walk) and the\n * binding edges (for `imports`). A leaf binds under its own name; a module (or a\n * `selectExports` synthetic) contributes each of its export bindings. A\n * duplicate binding throws, pointing at `selectExports` to rename one.\n */\nexport function normalizeImports(deps: ImportsInput | undefined): {\n plugins: readonly AnyPlugin[];\n bindings: readonly ImportBinding[];\n} {\n if (!deps) return { plugins: [], bindings: [] };\n const seen = new Map<string, string>();\n const bindings: ImportBinding[] = [];\n // Same name + same id is just the same value bound twice (dedup); same name +\n // a different id is a real collision the author must rename with selectExports.\n const add = (binding: string, id: string): void => {\n const priorId = seen.get(binding);\n if (priorId !== undefined && priorId !== id) {\n throw new Error(\n `Import binding \"${binding}\" is declared twice. Two different plugins ` +\n `(\"${priorId}\" and \"${id}\") bind the same name; wrap one in ` +\n `selectExports to rename it.`,\n );\n }\n if (priorId === undefined) {\n seen.set(binding, id);\n bindings.push({ binding, id });\n }\n };\n for (const plugin of deps) {\n if (plugin.pluginType === \"aggregate\") {\n // A module (or selectExports synthetic) contributes its export bindings,\n // each resolving to the re-exported child's id.\n for (const [binding, child] of Object.entries(plugin.exports)) {\n add(binding, child.id);\n }\n } else {\n add(plugin.name, plugin.id);\n }\n }\n return { plugins: deps, bindings };\n}\n\n/**\n * Fold the descriptive fields an author set directly on a `defineMethod` /\n * `defineProperty` config (`description`, `categories`, `outputSchema`, ...)\n * into the stored `LeafMeta` the registry reads. Returns `undefined` when none\n * are set, so a method with no descriptive metadata stays meta-less (the same\n * shape as before the fields were hoisted out of a `meta` wrapper).\n */\nfunction collectLeafMeta(config: LeafMetaFields): LeafMeta | undefined {\n let meta: Record<string, unknown> | undefined;\n for (const key of LEAF_META_KEYS) {\n if (config[key] !== undefined) (meta ??= {})[key] = config[key];\n }\n return meta as LeafMeta | undefined;\n}\n\n/**\n * Define a method leaf. The plugin IS the function; `createSdk` (or a\n * dependent's `imports`) binds it under its bare `name`. `imports` is typed\n * from the declared `imports` array. `namespace` sets the plugin's id\n * (`namespace/name`).\n *\n * The `output` mode shapes `run`'s result into the public surface and drives\n * the overload that types the call: raw (default, passthrough), `item`\n * (`run` returns `T`, surfaced as `Promise<{ data: T }>`), or `list` (`run`\n * returns one `SdkPage`, surfaced as `PaginatedSdkResult`). See Output.\n */\n// raw (default): the surface is whatever `run` returns. `positional` projects\n// named input keys onto the public arg list (the surface and imports); internals\n// (validation, middleware, run) still see the canonical `{ input }`.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TOutput,\n const TPositional extends readonly (keyof TInput & string)[] = readonly [],\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n TState = undefined,\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n /** Validates `input` and drives its type: when given, `input` is the schema's\n * output and no `run` annotation is needed. */\n inputSchema?: z.ZodType<TInput>;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n output?: \"raw\" | { type: \"raw\" };\n positional?: TPositional;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n run: (bag: MethodRunBag<ImportsOf<TImports>, TInput, TState>) => TOutput;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput, TOutput, TPositional> &\n LeafSummary<TNamespace, TName, TImports>;\n// item: `run` returns the bare value; the framework wraps it in `{ data }`.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TData,\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n TState = undefined,\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n inputSchema?: z.ZodType<TInput>;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n output: \"item\" | { type: \"item\" };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n run: (bag: MethodRunBag<ImportsOf<TImports>, TInput, TState>) => TData;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput, Promise<{ data: Awaited<TData> }>> &\n LeafSummary<TNamespace, TName, TImports>;\n// list, standard: `run` returns a strict `SdkPage`; no `adaptPage`.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TResponse extends StrictPage<TResponse>,\n TItem = ItemOf<TResponse>,\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n TState = undefined,\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n inputSchema?: z.ZodType<TInput>;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n output:\n | \"list\"\n | { type: \"list\"; adaptPage?: undefined; defaultPageSize?: number };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput & PaginatedCallInput, PaginatedSdkResult<TItem>> &\n LeafSummary<TNamespace, TName, TImports>;\n// list, adapted: `run` returns a raw envelope; `adaptPage` normalizes it and\n// sources the item type (the adapter produces the canonical page).\nexport function defineMethod<\n const TName extends string,\n TInput,\n TResponse,\n TItem,\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n TState = undefined,\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n inputSchema?: z.ZodType<TInput>;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n output: {\n type: \"list\";\n adaptPage: (response: TResponse) => SdkPage<TItem>;\n defaultPageSize?: number;\n };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput & PaginatedCallInput, PaginatedSdkResult<TItem>> &\n LeafSummary<TNamespace, TName, TImports>;\nexport function defineMethod(config: DefineMethodConfig): MethodPlugin {\n const deps = normalizeImports(config.imports);\n return {\n pluginType: \"method\",\n name: config.name,\n namespace: config.namespace,\n id: makeId(config.name, config.namespace),\n imports: deps.plugins,\n importBindings: deps.bindings,\n inputSchema: config.inputSchema,\n meta: collectLeafMeta(config),\n resolvers: config.resolvers,\n formatter: config.formatter,\n output: config.output,\n positional: config.positional,\n setup: config.setup as MethodPlugin[\"setup\"],\n run: config.run as MethodPlugin[\"run\"],\n };\n}\n\n/**\n * Define an input resolver: a method attachment for one of its parameters. Like\n * `defineMethod` it declares its own `imports`, and its callbacks receive a\n * narrowed `imports` bag, NOT the whole SDK. The graph reaches its imports\n * (materialize + dedup) but they never enter the host method's run-bag, so a\n * resolver may even import its own host method. At createSdk the imports are\n * captured, so the CLI later calls `listItems(input)` / `tryResolveWithoutPrompt\n * (input)` with no sdk argument.\n *\n * The `type` selects the kind (a {@link Resolver} union member); the config\n * narrows to it. `requireParameters` names sibling parameters that must resolve\n * first (it reads their values from `input`), independent of `imports` (the\n * SDK-capability graph). `object` / `array` resolvers compose nested resolvers;\n * an import-bearing resolver reached from a built field lives in `definitions`\n * (reached by `{ ref }`), since it can't be inlined when the field set is built\n * dynamically.\n */\n// dynamic (default): list candidate items, prompt to pick one.\nexport function defineResolver<\n const TImports extends ImportsInput = readonly [],\n TItem = unknown,\n TInput = Record<string, unknown>,\n TContext = unknown,\n>(config: {\n type?: \"dynamic\";\n imports?: TImports & StaticList<TImports>;\n requireParameters?: readonly string[];\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n /** Compute side-context once, before `listItems` (pre-fetch, no items yet),\n * with the narrowed `imports`. Its result flows into `listItems` and `prompt`\n * as `context`, so one place resolves what both the fetch and the render need\n * (e.g. a capability gate). May re-run across re-asks; keep it cheap. */\n getContext?: (bag: {\n imports: ImportsOf<TImports>;\n input: TInput;\n }) => PromiseLike<TContext>;\n /** Produce the candidate list. Behaves like an SDK list method (returns a page\n * / paginated result, never a bare array). `cursor` is the stateless \"load\n * more\" re-entry hook. */\n listItems?: (bag: {\n imports: ImportsOf<TImports>;\n input: TInput;\n /** The value `getContext` returned, if any. */\n context?: TContext;\n /** Free-text term the CLI injects for search-mode resolvers; a separate key\n * from `input`, so it never collides with a parameter named `search`. */\n search?: string;\n cursor?: string;\n }) => ListItemsResult<TItem>;\n prompt?: (bag: {\n items: TItem[];\n input: TInput;\n /** The value `getContext` returned, if any. */\n context?: TContext;\n }) => ResolverPromptConfig;\n /** Resolve with no user input (e.g. a configured default), skipping the prompt. */\n tryResolveWithoutPrompt?: (bag: {\n imports: ImportsOf<TImports>;\n input: TInput;\n }) => Promise<{ resolvedValue: unknown } | null>;\n /** Search-mode exact match: the typed `search` already names a valid value, so\n * return it and skip the picker. Returns null to fall through to `listItems`. */\n tryResolveFromSearch?: (bag: {\n imports: ImportsOf<TImports>;\n input: TInput;\n search?: string;\n }) => Promise<{ resolvedValue: unknown } | null>;\n}): DynamicResolver;\n// static: free-text input, no candidate list.\nexport function defineResolver(config: {\n type: \"static\";\n requireParameters?: readonly string[];\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n}): StaticResolver;\n// constant: a fixed value, no prompt.\nexport function defineResolver(config: {\n type: \"constant\";\n value: unknown;\n requireParameters?: readonly string[];\n}): ConstantResolver;\n// info: display-only text, resolves no value.\nexport function defineResolver(config: {\n type: \"info\";\n text: string;\n}): InfoResolver;\n// object: keyed members, literal (`properties`) or fetch-built; `definitions`\n// holds reusable resolvers reached by `{ ref }`.\nexport function defineResolver<\n const TImports extends ImportsInput = readonly [],\n TInput = Record<string, unknown>,\n>(config: {\n type: \"object\";\n imports?: TImports & StaticList<TImports>;\n requireParameters?: readonly string[];\n properties?: Record<string, Field>;\n /** Build the property map when the key set is dynamic (re-invoked as `input`\n * grow). Returns the map raw, no envelope. */\n getProperties?: (bag: {\n imports: ImportsOf<TImports>;\n input: TInput;\n }) => PromiseLike<Record<string, Field>>;\n definitions?: Record<string, Resolver>;\n}): ObjectResolver;\n// array: a homogeneous list resolved through `items`.\nexport function defineResolver(config: {\n type: \"array\";\n requireParameters?: readonly string[];\n items: Resolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n /** Coarse value type of each element, so a free-text item answer coerces\n * (e.g. `\"5\"` → `5`) like object fields do via `Field.valueType`. */\n itemValueType?: string;\n definitions?: Record<string, Resolver>;\n}): ArrayResolver;\nexport function defineResolver(config: {\n type?: ResolverType;\n imports?: ImportsInput;\n requireParameters?: readonly string[];\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n value?: unknown;\n text?: string;\n properties?: Record<string, Field>;\n definitions?: Record<string, Resolver>;\n items?: Resolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n itemValueType?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getContext?: (bag: any) => any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n listItems?: (bag: any) => any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getProperties?: (bag: any) => any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n prompt?: (bag: any) => PromptConfig;\n tryResolveWithoutPrompt?: (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n bag: any,\n ) => Promise<{ resolvedValue: unknown } | null>;\n tryResolveFromSearch?: (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n bag: any,\n ) => Promise<{ resolvedValue: unknown } | null>;\n}): Resolver {\n const deps = normalizeImports(config.imports);\n const base = { imports: deps.plugins, importBindings: deps.bindings };\n const gates = {\n requireParameters: config.requireParameters,\n };\n switch (config.type) {\n case \"static\":\n return {\n ...base,\n ...gates,\n type: \"static\",\n inputType: config.inputType,\n placeholder: config.placeholder,\n };\n case \"constant\":\n return { ...base, ...gates, type: \"constant\", value: config.value };\n case \"info\":\n return { ...base, type: \"info\", text: config.text ?? \"\" };\n case \"object\":\n return {\n ...base,\n ...gates,\n type: \"object\",\n properties: config.properties,\n definitions: config.definitions,\n getProperties: config.getProperties as ObjectResolver[\"getProperties\"],\n };\n case \"array\":\n return {\n ...base,\n ...gates,\n type: \"array\",\n items: config.items as ArrayResolver[\"items\"],\n minItems: config.minItems,\n maxItems: config.maxItems,\n itemValueType: config.itemValueType,\n definitions: config.definitions,\n };\n default:\n return {\n ...base,\n ...gates,\n type: \"dynamic\",\n inputType: config.inputType,\n placeholder: config.placeholder,\n getContext: config.getContext as DynamicResolver[\"getContext\"],\n listItems: config.listItems as DynamicResolver[\"listItems\"],\n prompt: config.prompt as DynamicResolver[\"prompt\"],\n tryResolveWithoutPrompt:\n config.tryResolveWithoutPrompt as DynamicResolver[\"tryResolveWithoutPrompt\"],\n tryResolveFromSearch:\n config.tryResolveFromSearch as DynamicResolver[\"tryResolveFromSearch\"],\n };\n }\n}\n\n/**\n * Define an output formatter: a method attachment for its output. `getContext`\n * runs once per rendered page with the narrowed `imports` bag (no sdk); it\n * receives the items on the page and the context accumulated from prior pages,\n * and returns the (possibly extended) context — so page-independent context\n * (e.g. field labels) is fetched once, while per-item context grows as pages\n * arrive. `format` is pure and synchronous, turning one item + context into a\n * `FormattedItem`. Anything needing SDK data belongs in `getContext`, not\n * `format`. Both callbacks get the method's `input` (complete, since the\n * formatter runs after the method).\n */\nexport function defineFormatter<\n const TImports extends ImportsInput = readonly [],\n TItem = unknown,\n TInput = Record<string, unknown>,\n TContext = unknown,\n>(config: {\n imports?: TImports & StaticList<TImports>;\n getContext?: (bag: {\n imports: ImportsOf<TImports>;\n items: TItem[];\n input: TInput;\n context?: TContext;\n }) => Promise<TContext>;\n format: (bag: {\n item: TItem;\n input: TInput;\n context?: TContext;\n }) => FormattedItem;\n}): Formatter {\n const deps = normalizeImports(config.imports);\n return {\n imports: deps.plugins,\n importBindings: deps.bindings,\n getContext: config.getContext as Formatter[\"getContext\"],\n format: config.format as Formatter[\"format\"],\n };\n}\n\n/**\n * Declare a stand-in for a method registered elsewhere (a configured factory\n * plugin, or just a different module). You reference it by `id` (`namespace/name`,\n * or a bare name); the binding is the id's last segment, and resolution by id\n * binds the real implementation at materialization (constraints 3-4). Its `run`\n * throws, since a stand-in must never be the implementation.\n */\nexport function declareMethod<\n const TId extends string,\n TInput = unknown,\n TOutput = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): MethodPlugin<LastSegment<TId>, TInput, TOutput> &\n PluginSummary<TId, never> {\n const { name, namespace } = parseId(config.id);\n const id = makeId(name, namespace);\n return {\n pluginType: \"method\",\n name,\n namespace,\n id,\n standIn: true,\n imports: [],\n importBindings: [],\n run: () => {\n throw new Error(\n `Plugin \"${id}\" is a stand-in (declareMethod) with no implementation. ` +\n `Register the real plugin under this id.`,\n );\n },\n } as unknown as MethodPlugin<LastSegment<TId>, TInput, TOutput> &\n PluginSummary<TId, never>;\n}\n\n/**\n * Define a property leaf. Either a static `value` or a computed `get` (eager,\n * dependencies first, like `setup`). `createSdk`, a dependent's `imports`, or\n * an aggregate's re-export binds it under its bare `name` and yields the value.\n */\nexport function defineProperty<\n const TName extends string,\n TValue,\n const TNamespace extends string = \"\",\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n value: TValue;\n } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> &\n PluginSummary<never, IdOf<TNamespace, TName>>;\nexport function defineProperty<\n const TName extends string,\n TValue,\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n TState = undefined,\n>(\n config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n get: (bag: { imports: ImportsOf<TImports>; state: TState }) => TValue;\n } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> & LeafSummary<TNamespace, TName, TImports>;\nexport function defineProperty(\n config: {\n name: string;\n namespace?: string;\n imports?: ImportsInput;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: any) => unknown;\n value?: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get?: (bag: any) => unknown;\n } & LeafMetaFields,\n): PropertyPlugin {\n const deps = normalizeImports(config.imports);\n return {\n pluginType: \"property\",\n name: config.name,\n namespace: config.namespace,\n id: makeId(config.name, config.namespace),\n imports: deps.plugins,\n importBindings: deps.bindings,\n setup: config.setup as PropertyPlugin[\"setup\"],\n value: config.value,\n get: config.get as PropertyPlugin[\"get\"],\n meta: collectLeafMeta(config),\n };\n}\n\n/**\n * Declare a stand-in for a property registered elsewhere (a configured factory\n * plugin, e.g. the api client built from options). Carries only a name and a\n * provides type; dependents reference it for typing, and resolution by id binds\n * the real property at materialization (constraints 3-4, the property twin of\n * `declareMethod`). A stand-in left with no real implementation is a missing\n * dependency (a runtime error from `createSdk`).\n */\nexport function declareProperty<\n const TId extends string,\n TValue = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): PropertyPlugin<LastSegment<TId>, TValue> & PluginSummary<TId, never> {\n const { name, namespace } = parseId(config.id);\n return {\n pluginType: \"property\",\n name,\n namespace,\n id: makeId(name, namespace),\n standIn: true,\n imports: [],\n importBindings: [],\n } as unknown as PropertyPlugin<LastSegment<TId>, TValue> &\n PluginSummary<TId, never>;\n}\n\n/**\n * Declare a stand-in for a whole aggregate (module) registered elsewhere: the\n * aggregate twin of `declareMethod` / `declareProperty`. `exports` is an array\n * of leaf stand-ins describing the module's surface, so dependents that import\n * it get typed bindings; resolution by id binds the real aggregate at\n * materialization, and a stand-in left with no implementation is a missing\n * dependency. Use it to depend on a module abstractly and provide the concrete\n * one at the composition root (the tree-shakeable / swappable shape).\n */\nexport function declarePlugin<\n const TId extends string,\n const TExports extends readonly AnyLeafPlugin[] = readonly [],\n>(config: {\n id: LiteralString<TId>;\n exports?: TExports & StaticList<TExports>;\n}): AggregatePlugin<LastSegment<TId>, ArrayExports<TExports>> &\n PluginSummary<TId, never> {\n const { name, namespace } = parseId(config.id);\n return {\n pluginType: \"aggregate\",\n name,\n namespace,\n id: makeId(name, namespace, \"aggregate\"),\n standIn: true,\n imports: [],\n importBindings: [],\n exports: normalizeExports(config.exports),\n } as unknown as AggregatePlugin<LastSegment<TId>, ArrayExports<TExports>> &\n PluginSummary<TId, never>;\n}\n\n/**\n * Define a plugin. Two forms, one function:\n *\n * - **Object form** — a module that re-exports child plugins and may wrap\n * imported methods with `middleware`. `exports` mirrors `imports`: an\n * array where a leaf binds under its own name (`[greet]` binds \"greet\"), a\n * module spreads its bindings, and `selectExports(dep, { hi: \"greet\" })`\n * subsets/renames. It is optional, so a pure-middleware module can omit it.\n * Re-exporting implies a dependency on the child. A middleware key names the\n * target's binding, a direct dependency.\n * - **Function form** — the legacy function-plugin identity wrapper: it returns\n * the function unchanged but constrains its return to `PluginProvides` and\n * preserves the narrow inferred shape, so callers derive `*PluginProvides`\n * via `ReturnType<typeof plugin>`. This is how the existing ~90 plugins are\n * written; they run on the module model through the legacy bridge.\n */\nexport function definePlugin<TSdk, TProvides extends PluginProvides>(\n fn: (\n sdk: TSdk & { context: { meta: Record<string, PluginMeta> } },\n ) => TProvides,\n): (sdk: TSdk & { context: { meta: Record<string, PluginMeta> } }) => TProvides;\n// Module form: `exports` is an array of inline declarations and re-exports\n// (a leaf binds under its own name, a module or `selectExports(...)` spreads its\n// bindings). Optional, so a pure-middleware module can omit it.\nexport function definePlugin<\n const TName extends string,\n const TImports extends ImportsInput = readonly [],\n const TNamespace extends string = \"\",\n const TExports extends readonly (\n | AnyLeafPlugin\n | AnyAggregatePlugin\n )[] = readonly [],\n>(config: {\n name: TName;\n namespace?: TNamespace;\n imports?: TImports & StaticList<TImports>;\n exports?: TExports & StaticList<TExports>;\n middleware?: MiddlewareMap<ImportsOf<TImports>>;\n}): AggregatePlugin<TName, ArrayExports<TExports>> &\n AggregateSummary<TNamespace, TName, TImports, TExports>;\nexport function definePlugin(\n fnOrConfig:\n | // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ((sdk: any) => PluginProvides)\n | {\n name: string;\n namespace?: string;\n imports?: ImportsInput;\n exports?: ExportsInput;\n // The object-form overload constrains this to `MiddlewareMap<...>`,\n // which has no string index signature and so isn't assignable to\n // `Record<string, MiddlewareFn>`; the impl stays permissive and casts.\n middleware?: unknown;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): ((sdk: any) => PluginProvides) | AggregatePlugin {\n if (typeof fnOrConfig === \"function\") return fnOrConfig;\n const config = fnOrConfig;\n const deps = normalizeImports(config.imports);\n return {\n pluginType: \"aggregate\",\n name: config.name,\n namespace: config.namespace,\n id: makeId(config.name, config.namespace, \"aggregate\"),\n imports: deps.plugins,\n importBindings: deps.bindings,\n exports: normalizeExports(config.exports),\n middleware: config.middleware as Record<string, MiddlewareFn> | undefined,\n };\n}\n\n/**\n * Normalize the `exports` array to the canonical `{ binding: leaf }` record: a\n * leaf binds under its own `name`; a module (or `selectExports` synthetic)\n * spreads each of its export bindings. A duplicate binding throws, pointing at\n * `selectExports` to rename one (the export twin of {@link normalizeImports}).\n */\nfunction normalizeExports(\n exports: ExportsInput | undefined,\n): Record<string, AnyLeafPlugin> {\n if (!exports) return {};\n const out: Record<string, AnyLeafPlugin> = {};\n const add = (binding: string, leaf: AnyLeafPlugin): void => {\n const existing = out[binding];\n if (existing && existing.id !== leaf.id) {\n throw new Error(\n `definePlugin: duplicate export binding \"${binding}\". Two different ` +\n `plugins (\"${existing.id}\" and \"${leaf.id}\") bind the same name; ` +\n `wrap one in selectExports to rename it.`,\n );\n }\n out[binding] = leaf;\n };\n for (const element of exports) {\n if (element.pluginType === \"aggregate\") {\n for (const [binding, child] of Object.entries(element.exports)) {\n add(binding, child);\n }\n } else {\n add(element.name, element);\n }\n }\n return out;\n}\n","import { makeId } from \"./shared\";\nimport type {\n AggregatePlugin,\n AnyLeafPlugin,\n UnionToIntersection,\n} from \"./types\";\n\n/**\n * A `selectExports` spec: a bare export name to keep (`\"getApp\"`), or a rename\n * map whose key is the resulting binding and value the source export name\n * (`{ getUser: \"getProfile\" }` is `export { getProfile as getUser }`).\n */\nexport type SelectSpec<TExports> =\n | (keyof TExports & string)\n | { [newName: string]: keyof TExports & string };\n\n/** The export record one spec contributes: a kept name maps to its own leaf; a\n * rename map keys each new name to the leaf at the source name. */\ntype ResolveSpec<TExports extends Record<string, AnyLeafPlugin>, S> = S extends\n | string\n | number\n ? S extends keyof TExports\n ? { [K in S]: TExports[S] }\n : never\n : { [K in keyof S]: S[K] extends keyof TExports ? TExports[S[K]] : never };\n\n/** Ensure the computed export record satisfies the `AggregatePlugin` constraint\n * (an empty/degenerate selection collapses to a bare exports record). */\ntype AsExports<T> =\n T extends Record<string, AnyLeafPlugin> ? T : Record<string, AnyLeafPlugin>;\n\n/** Unique-id source for the synthetic re-export aggregate `selectExports`\n * builds, so two `selectExports` calls never collide in the graph even when\n * they select the same names from the same source. */\nlet selectSeq = 0;\n\n/**\n * Select (and optionally rename) a subset of a module's exports, the ES\n * `{ a, b, c as d }` clause. Works the same in `imports` (import) and\n * `exports` (re-export): each spec is a bare name to keep or a `{ new: \"old\" }`\n * rename map. An unknown source name throws. Returns a re-export descriptor (a\n * synthetic aggregate over the chosen bindings) that drops straight into either\n * array; the selected bindings keep the source module's identity.\n */\nexport function selectExports<\n TExports extends Record<string, AnyLeafPlugin>,\n const TSpecs extends readonly SelectSpec<TExports>[],\n>(\n source: AggregatePlugin<string, TExports>,\n ...specs: TSpecs\n): AggregatePlugin<\n string,\n AsExports<\n UnionToIntersection<\n { [I in keyof TSpecs]: ResolveSpec<TExports, TSpecs[I]> }[number]\n >\n >\n> {\n const selected: Record<string, AnyLeafPlugin> = {};\n const pick = (binding: string, fromName: string): void => {\n const child = source.exports[fromName];\n if (!child) {\n throw new Error(\n `selectExports: \"${source.id}\" has no export \"${fromName}\".`,\n );\n }\n selected[binding] = child;\n };\n for (const spec of specs) {\n if (typeof spec === \"string\") {\n pick(spec, spec);\n } else {\n for (const [newName, fromName] of Object.entries(spec)) {\n pick(newName, fromName);\n }\n }\n }\n const id = `${source.id}#select:${selectSeq++}`;\n return {\n pluginType: \"aggregate\",\n name: makeId(`select`, source.name, \"aggregate\"),\n id,\n // Depend on the source so it is materialized; the selected bindings resolve\n // to the source's own leaves (kept identity).\n imports: [source],\n importBindings: [],\n exports: selected,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as AggregatePlugin<string, any>;\n}\n","import type { PluginMeta, PluginProvides } from \"../types/plugin\";\nimport type { RegistryResult } from \"../registry\";\nimport { makeId } from \"./shared\";\nimport type {\n AnyPlugin,\n LegacyMergePlugin,\n LegacyPlugin,\n MethodEntry,\n LeafMeta,\n PropertyEntry,\n} from \"./types\";\n\n/**\n * Lift a legacy function plugin into the module model. The\n * returned plugin runs `fn` at materialization and surfaces its root methods;\n * `createPluginStack().toPlugin()` is built on this, and `addPlugin` uses it for\n * external function plugins. `fn`'s `context` contributions merge into the live\n * `SdkContext`; its other root keys become the surface.\n */\nexport function fromFunctionPlugin<TProvides extends PluginProvides>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fn: (sdk: any) => TProvides,\n config: { name: string; namespace?: string },\n): LegacyPlugin<\n TProvides & {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n }\n> {\n return {\n pluginType: \"legacy\",\n name: config.name,\n namespace: config.namespace,\n id: makeId(config.name, config.namespace, \"aggregate\"),\n imports: [],\n importBindings: [],\n run: fn,\n };\n}\n\n/**\n * Build a {@link LegacyMergePlugin}: pass the collapsed legacy stack\n * (`stack.toPlugin()`) as `legacy` and the migrated module-model plugins as\n * `plugin`. `createSdk(defineLegacyMerge({...}))` surfaces both.\n */\nexport function defineLegacyMerge<\n TProvides extends PluginProvides,\n const TPlugin extends AnyPlugin,\n>(args: {\n name: string;\n namespace?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n legacy: (sdk: any) => TProvides;\n plugin: TPlugin;\n}): LegacyMergePlugin<TProvides, TPlugin> {\n return {\n pluginType: \"legacy-merge\",\n name: args.name,\n namespace: args.namespace,\n id: makeId(args.name, args.namespace, \"aggregate\"),\n legacy: fromFunctionPlugin(args.legacy, {\n name: args.name,\n namespace: args.namespace,\n }),\n plugin: args.plugin,\n };\n}\n\n/**\n * Build the `context.plugins` entry for one legacy contribution key. The legacy\n * bridge stores per-method registry data in `context.meta`; this also splits\n * that `PluginMeta` onto the graph entry (`inputSchema` as a first-class field,\n * the rest as `meta`) so a surface-driven reader (`getRegistryPlugin`) reports a\n * legacy method with the same metadata the head reads from `context.meta`.\n */\nexport function legacyGraphEntry(\n name: string,\n value: unknown,\n pluginMeta: PluginMeta | undefined,\n): MethodEntry | PropertyEntry {\n const { inputSchema, ...rest } = pluginMeta ?? {};\n const meta = Object.keys(rest).length ? (rest as LeafMeta) : undefined;\n if (typeof value === \"function\") {\n return {\n pluginType: \"method\",\n name,\n value: value as (input: unknown) => unknown,\n chain: [],\n ...(inputSchema ? { inputSchema } : {}),\n ...(meta ? { meta } : {}),\n };\n }\n return { pluginType: \"property\", name, value, ...(meta ? { meta } : {}) };\n}\n","import { z } from \"zod\";\nimport { defineMethod } from \"./define\";\nimport { buildSurfaceRegistry } from \"./registry-support\";\nimport type { PropertyPlugin, SdkContext } from \"./types\";\n\n/**\n * Escape hatch. A built-in privileged plugin whose value is the live\n * `SdkContext`: the raw plugin graph plus the legacy compat fields. Importing it\n * (`imports.context`) lets a body reach internals the model otherwise keeps\n * private.\n *\n * Prefer not to depend on this. The `SdkContext` shape is an implementation\n * detail and may change without notice; import the specific plugins you need,\n * and use `getRegistryPlugin` for surface introspection. It exists mainly so a\n * not-yet-migrated plugin can read legacy `context.*` fields during migration.\n * Its value is injected at materialization, not authored.\n */\nexport const dangerousContextPlugin: PropertyPlugin<\"context\", SdkContext> = {\n pluginType: \"property\",\n name: \"context\",\n namespace: \"kitcore\",\n id: \"kitcore/context\",\n imports: [],\n importBindings: [],\n privileged: true,\n};\n\n/**\n * A built-in that reports the live SDK surface as the canonical\n * {@link RegistryResult}. It is just a method depending on `dangerousContextPlugin` (no\n * new privilege): re-export it to put `getRegistry()` on the SDK surface. Reads\n * `context.surface` at call time, so it reflects any post-seal `addPlugin`\n * additions, and produces the same registry shape the heads (CLI / MCP / docs)\n * consume.\n */\nexport const getRegistryPlugin = defineMethod({\n name: \"getRegistry\",\n namespace: \"kitcore\",\n imports: [dangerousContextPlugin],\n inputSchema: z.object({ package: z.string().optional() }).optional(),\n run: ({ imports, input }) =>\n buildSurfaceRegistry(imports.context, input?.package),\n});\n","import { buildRegistry, type RegistryResult } from \"../registry\";\nimport type { PluginMeta } from \"../types/plugin\";\nimport type { OutputFormatter } from \"../utils/schema-utils\";\nimport type {\n BoundFormatter,\n BoundResolver,\n MethodEntry,\n PluginEntry,\n PropertyEntry,\n SdkContext,\n} from \"./types\";\n\n/**\n * Wrap a legacy `OutputFormatter` (sdk passed positionally, `fetch` called once\n * per item folding `context`) into the current `BoundFormatter`, capturing the\n * sdk so consumers call it with no sdk. The per-item fold is reproduced inside\n * `getContext` (run once per batch) so rendered output is unchanged; `format`\n * adapts the positional call to the bag.\n */\nfunction adaptLegacyFormatter(\n legacy: OutputFormatter<unknown, unknown, Record<string, unknown>, unknown>,\n sdk: unknown,\n): BoundFormatter {\n const legacyFetch = legacy.fetch;\n return {\n getContext: legacyFetch\n ? async ({ items, input, context }) => {\n let ctx = context;\n for (const item of items) {\n ctx = await legacyFetch(sdk, input, item, ctx);\n }\n return ctx;\n }\n : undefined,\n format: ({ item, context }) => legacy.format(item, context),\n };\n}\n\n/**\n * The single bound formatter for a method entry: the new attachment slot\n * (`entry.formatter`) if present, else the legacy `meta.formatter` adapted with\n * the sdk. The registry surfaces one `BoundFormatter` shape regardless of plugin\n * vintage; the slot is the discriminator. Non-methods / no formatter → undefined.\n */\nexport function normalizeFormatter(\n entry: PluginEntry,\n sdk: unknown,\n): BoundFormatter | undefined {\n if (entry.pluginType !== \"method\") return undefined;\n if (entry.formatter) return entry.formatter;\n const legacy = entry.meta?.formatter as\n | OutputFormatter<unknown, unknown, Record<string, unknown>, unknown>\n | undefined;\n return legacy ? adaptLegacyFormatter(legacy, sdk) : undefined;\n}\n\n/**\n * The bound resolvers a method entry carries (their imports captured at\n * materialization), keyed by param name. Already in bound form on the entry —\n * unlike formatters there's no legacy adaptation here: legacy resolvers stay on\n * `meta.resolvers` as `ResolverMetadata` and flow to the registry's separate\n * `resolvers` field untouched. Non-methods / no resolvers → undefined.\n */\nexport function normalizeBoundResolvers(\n entry: PluginEntry,\n): Record<string, BoundResolver> | undefined {\n if (entry.pluginType !== \"method\") return undefined;\n return entry.resolvers;\n}\n\n/**\n * The positional projection a method entry declares (ordered input keys the\n * public surface takes as positional args), lifted off the materialized entry\n * like {@link normalizeBoundResolvers}. Non-methods / no projection → undefined.\n */\nexport function methodPositional(\n entry: PluginEntry,\n): readonly string[] | undefined {\n if (entry.pluginType !== \"method\") return undefined;\n return entry.positional;\n}\n\n/**\n * A materialized leaf entry's registry meta: its `meta` bag with `inputSchema`\n * folded back in (methods carry the schema as a first-class field, the registry\n * wants it inside the `PluginMeta`). Undefined when the entry carries no meta.\n * Shared by the surface reader (`getRegistryPlugin`) and the legacy synth so\n * both turn a materialized entry into registry meta the same way.\n */\nexport function pluginEntryMeta(\n entry: MethodEntry | PropertyEntry,\n): PluginMeta | undefined {\n if (entry.pluginType === \"method\" && entry.meta) {\n return entry.inputSchema\n ? { ...entry.meta, inputSchema: entry.inputSchema }\n : entry.meta;\n }\n if (entry.pluginType === \"property\" && entry.meta) return entry.meta;\n return undefined;\n}\n\n/**\n * Build the canonical {@link RegistryResult} from the live SDK surface: one\n * meta entry per `context.surface` binding (what the consumer calls), resolved\n * to the leaf it surfaces, then handed to `buildRegistry`. An aliased re-export\n * (`{ hi: greet }`) is reported as `hi` with greet's meta; aggregates and\n * non-surfaced internals are excluded. This is the pure module-model\n * `getRegistry`; read at call time, so it reflects post-build `addPlugin`\n * additions.\n */\nexport function buildSurfaceRegistry(\n context: SdkContext,\n packageFilter?: string,\n): RegistryResult {\n const meta: Record<string, PluginMeta> = {};\n const surface: Record<string, unknown> = {};\n const entries: Record<string, PluginEntry> = {};\n for (const [binding, id] of Object.entries(context.surface)) {\n const entry = context.plugins[id];\n if (!entry || entry.pluginType === \"aggregate\") continue;\n surface[binding] = entry.value;\n entries[binding] = entry;\n const m = pluginEntryMeta(entry);\n if (m) meta[binding] = m;\n }\n // Normalize formatters after `surface` is fully built, so the adapter for a\n // legacy formatter captures a complete sdk to call through at render time.\n const formatters: Record<string, BoundFormatter> = {};\n const boundResolvers: Record<string, Record<string, BoundResolver>> = {};\n const positional: Record<string, readonly string[]> = {};\n for (const [binding, entry] of Object.entries(entries)) {\n const f = normalizeFormatter(entry, surface);\n if (f) formatters[binding] = f;\n const r = normalizeBoundResolvers(entry);\n if (r) boundResolvers[binding] = r;\n const p = methodPositional(entry);\n if (p) positional[binding] = p;\n }\n return buildRegistry({\n sdk: surface,\n meta,\n formatters,\n boundResolvers,\n positional,\n packageFilter,\n });\n}\n","import { buildHooks } from \"../utils/build-hooks\";\nimport {\n applyPluginToSdk,\n checkRootKeyCollisions,\n splitPluginContribution,\n} from \"../utils/plugin-utils\";\nimport {\n createFunction,\n createPaginatedFunction,\n} from \"../utils/function-utils\";\nimport { buildRegistry, type RegistryResult } from \"../registry\";\nimport type { PluginMeta, Plugin, PluginProvides } from \"../types/plugin\";\nimport { legacyGraphEntry } from \"./legacy\";\nimport {\n normalizeBoundResolvers,\n normalizeFormatter,\n pluginEntryMeta,\n} from \"./registry-support\";\nimport type {\n AddedSurface,\n AggregateEntry,\n AggregatePlugin,\n AggregateSdkOf,\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyMethodPlugin,\n AnyPropertyPlugin,\n AnyPlugin,\n BoundField,\n BoundFormatter,\n BoundResolver,\n CompletenessOf,\n Field,\n Formatter,\n ImportBinding,\n ResolverRef,\n MethodSdkOf,\n PropertySdkOf,\n LegacyMergePlugin,\n LegacyPlugin,\n MethodEntry,\n NormalizedOutput,\n Resolver,\n OutputConfig,\n PluginEntry,\n PropertyEntry,\n SdkContext,\n SdkInternals,\n} from \"./types\";\n\nfunction normalizeOutput(output: OutputConfig | undefined): NormalizedOutput {\n if (output === undefined) return { type: \"raw\" };\n if (typeof output === \"string\") return { type: output };\n return output;\n}\n\n/**\n * The external escape-hatch key for an SDK's context. A Symbol,\n * not a string, so it stays off the string surface (which is exactly the root's\n * exports) and is collision-free and clearly internal. It is attached at\n * runtime but kept OUT of the public SDK type (a `unique symbol` in an exported\n * type can't be named in a consumer's emitted `.d.ts`); reach it through the\n * typed `getContext(sdk)` accessor.\n */\nexport const CONTEXT: unique symbol = Symbol(\"kitcore.context\");\n\n/** The off-surface escape hatch to an SDK's `SdkContext`. */\nexport function getContext(sdk: unknown): SdkContext {\n return (sdk as { [CONTEXT]: SdkContext })[CONTEXT];\n}\n\n/** Whether a field / array-items slot is a `{ ref }` into `definitions` rather\n * than an inline resolver. */\nfunction isResolverRef(value: Resolver | ResolverRef): value is ResolverRef {\n return \"ref\" in value;\n}\n\n/** The inline (non-ref) resolvers nested directly in a composite: an object's\n * literal `properties` and `definitions`, an array's `items` and `definitions`.\n * Fetch-built fields are runtime-only, so their imports must come through\n * `definitions` (static, and walked here). */\nfunction nestedResolvers(resolver: Resolver): Resolver[] {\n const out: Resolver[] = [];\n if (resolver.type === \"object\") {\n for (const field of Object.values(resolver.properties ?? {})) {\n if (!isResolverRef(field.resolver)) out.push(field.resolver);\n }\n out.push(...Object.values(resolver.definitions ?? {}));\n } else if (resolver.type === \"array\") {\n if (!isResolverRef(resolver.items)) out.push(resolver.items);\n out.push(...Object.values(resolver.definitions ?? {}));\n }\n return out;\n}\n\n/** The imports a resolver (and its nested inline resolvers + definitions) reach,\n * so the graph walk pulls them in for materialization. */\nfunction resolverImportEdges(resolver: Resolver): AnyPlugin[] {\n const out: AnyPlugin[] = [...resolver.imports];\n for (const child of nestedResolvers(resolver)) {\n out.push(...resolverImportEdges(child));\n }\n return out;\n}\n\n/** A method's attachment reachability edges: every import its resolvers and\n * formatter (and nested child resolvers) depend on. These are reachability-only:\n * they pull the imports into the graph but are NOT part of the method's own\n * `importBindings`, so they never widen its run-bag or its `setup` dependency\n * order (a resolver may even import its own host method without forming a\n * cycle). The late `bindAttachments` pass binds them against the materialized\n * entries. */\nfunction methodAttachmentEdges(plugin: AnyMethodPlugin): AnyPlugin[] {\n const out: AnyPlugin[] = [];\n if (plugin.resolvers) {\n for (const resolver of Object.values(plugin.resolvers)) {\n out.push(...resolverImportEdges(resolver));\n }\n }\n if (plugin.formatter) out.push(...plugin.formatter.imports);\n return out;\n}\n\n/** Graph edges for the reachability walk: a leaf's or legacy plugin's deps, an\n * aggregate's re-exported children plus its extra deps. A method also reaches\n * its attachments' imports (reachability only; see `methodAttachmentEdges`). */\nfunction edgesOf(plugin: AnyPlugin): readonly AnyPlugin[] {\n if (plugin.pluginType === \"aggregate\") {\n return [...Object.values(plugin.exports), ...plugin.imports];\n }\n if (plugin.pluginType === \"method\") {\n return [...plugin.imports, ...methodAttachmentEdges(plugin)];\n }\n return plugin.imports;\n}\n\n/** A stand-in is a typed reference with no implementation (`declareMethod` /\n * `declareProperty` / `declarePlugin`); a real plugin under the same id\n * satisfies it. */\nfunction isStandIn(plugin: AnyPlugin): boolean {\n return (\n (plugin.pluginType === \"method\" ||\n plugin.pluginType === \"property\" ||\n plugin.pluginType === \"aggregate\") &&\n plugin.standIn === true\n );\n}\n\n/**\n * Topological order of the collected plugins, dependencies before dependents\n * (DFS post-order). Used to sequence middleware contributions so wraps land on\n * each target innermost-first. Cycles are already rejected by\n * `materialize`; a back-edge here is simply skipped by the visited guard.\n */\nfunction topoOrder(descriptors: Map<string, AnyPlugin>): string[] {\n const order: string[] = [];\n const visited = new Set<string>();\n const visit = (id: string): void => {\n if (visited.has(id)) return;\n visited.add(id);\n const descriptor = descriptors.get(id);\n if (descriptor) for (const edge of edgesOf(descriptor)) visit(edge.id);\n order.push(id);\n };\n for (const id of descriptors.keys()) visit(id);\n return order;\n}\n\n/**\n * Walk the graph from `root`, collecting every reachable plugin by id\n * (`namespace/name`), resolving each id to its real implementation.\n * Resolution is by id, not identity: a real plugin replaces a stand-in under\n * the same id (the swap path), regardless of visitation order. Two different\n * real plugins under one id throw. An id left with only a stand-in after the\n * walk is a missing dependency.\n */\nfunction collectPlugins(\n root: AnyPlugin,\n materialized: ReadonlySet<string> = new Set(),\n): Map<string, AnyPlugin> {\n const byId = new Map<string, AnyPlugin>();\n const visit = (plugin: AnyPlugin): void => {\n // An id already in the live graph (incremental addPlugin) is a boundary:\n // it is materialized, so it satisfies a stand-in and is not re-collected.\n if (materialized.has(plugin.id)) return;\n const existing = byId.get(plugin.id);\n if (existing === plugin) return;\n if (existing) {\n const bothReal = !isStandIn(existing) && !isStandIn(plugin);\n if (bothReal) {\n throw new Error(\n `createSdk: duplicate plugin id \"${plugin.id}\". Two different ` +\n `plugins registered under the same id.`,\n );\n }\n // A real plugin replaces a stand-in; otherwise keep what we have.\n if (isStandIn(existing) && !isStandIn(plugin)) {\n byId.set(plugin.id, plugin);\n for (const edge of edgesOf(plugin)) visit(edge);\n }\n return;\n }\n byId.set(plugin.id, plugin);\n for (const edge of edgesOf(plugin)) visit(edge);\n };\n visit(root);\n\n for (const [id, plugin] of byId) {\n if (isStandIn(plugin)) {\n throw new Error(\n `createSdk: missing dependency \"${id}\". A plugin depends on it ` +\n `(via a stand-in) but no implementation was registered.`,\n );\n }\n }\n return byId;\n}\n\n/**\n * Bind an entry's value onto a target under a key: a method's callable or a\n * static property value as a plain property, a live `get` property as a getter\n * (so reading it re-derives per access on the surface and in `imports`).\n */\nfunction bindValue(\n target: Record<string, unknown>,\n key: string,\n entry: PluginEntry,\n): void {\n if (entry.pluginType === \"property\" && entry.getValue) {\n Object.defineProperty(target, key, {\n get: entry.getValue,\n enumerable: true,\n configurable: true,\n });\n } else {\n Object.defineProperty(target, key, {\n value: (entry as MethodEntry | PropertyEntry).value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n}\n\n/**\n * Assemble an SDK surface from one or more resolved export maps plus the context\n * keys. Copies own-property descriptors (a spread would invoke and snapshot live\n * `get` getters, freezing them); later maps win on a binding collision.\n */\nfunction buildSurface(\n context: SdkContext,\n ...maps: Record<string, unknown>[]\n): Record<string, unknown> {\n const sdk: Record<string, unknown> = {};\n for (const map of maps) {\n Object.defineProperties(sdk, Object.getOwnPropertyDescriptors(map));\n }\n sdk.context = context;\n (sdk as { [CONTEXT]: SdkContext })[CONTEXT] = context;\n return sdk;\n}\n\n/**\n * What importing a dependency yields: a method's callable or a property's value\n * (a live `get` property reads through its getter each access). Works for any\n * plugin carrying `importBindings` (a leaf body's imports, or a wrap's imports).\n */\nfunction buildImports(\n plugins: Record<string, PluginEntry>,\n importBindings: readonly ImportBinding[],\n): Record<string, unknown> {\n const imports: Record<string, unknown> = {};\n for (const { binding, id } of importBindings) {\n bindValue(imports, binding, plugins[id]);\n }\n return imports;\n}\n\n/**\n * Project a legacy contribution's root keys into the live graph: one\n * `context.plugins` entry per key (a method entry for a callable, a property\n * entry otherwise), splitting each key's `PluginMeta` onto the entry so a\n * surface-driven reader reports it. Returns the keys as a plain value map for\n * callers that also need the bare exports. Shared by the pass-0 legacy bridge\n * and the legacy branch of `addPlugin`; the caller records the surface, which\n * differs between the two.\n */\nfunction mirrorLegacyRootKeys(\n context: SdkContext,\n rootKeys: Record<string, unknown>,\n meta: Record<string, PluginMeta>,\n): Record<string, unknown> {\n const exports: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(rootKeys)) {\n context.plugins[name] = legacyGraphEntry(name, value, meta[name]);\n exports[name] = value;\n }\n return exports;\n}\n\n/** Record an aggregate's export bindings on the surface (binding -> leaf id),\n * so the registry reports what the consumer calls. */\nfunction recordExportSurface(\n context: SdkContext,\n exports: Record<string, AnyLeafPlugin>,\n): void {\n for (const [binding, child] of Object.entries(exports)) {\n context.surface[binding] = child.id;\n }\n}\n\n/**\n * Materialize the reachable graph into `context.plugins` (keyed by id): a live\n * entry per plugin. Method entries' `value` computes `imports` from the shared\n * record at call time (order-independent), keyed by each dependency's bare\n * name but resolved by its id; aggregate entries resolve their export bindings\n * to child callables.\n *\n * The passes run in a fixed order because the order is load-bearing: method\n * wrappers must exist before a dependent's `setup` calls them, and aggregates\n * must resolve before middleware folds onto their targets. Each pass is a step\n * of this one operation, not an independent unit; `states` threads the eager\n * `setup` results from pass 2 to the method wrappers built in pass 1.\n */\nfunction materialize(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): Record<string, PluginEntry> {\n const states = new Map<string, unknown>();\n runLegacyPass(descriptors, context);\n buildMethodEntries(descriptors, context, states);\n buildEagerArtifacts(descriptors, context, states);\n bindAttachments(descriptors, context);\n resolveAggregates(descriptors, context);\n assembleMiddleware(descriptors, context);\n return context.plugins;\n}\n\n/**\n * Bind a resolver descriptor against the materialized graph: capture its\n * narrowed imports bag (so `fetch` / `tryResolveWithoutPrompt` are called with\n * input only, no sdk), recurse into child resolvers. `prompt` needs no imports\n * and passes through. Runs after every method and property exists, so a resolver\n * that reaches a method gets that method's stable callable, which reads its own\n * imports live per call, so order between resolver and target does not matter.\n */\nfunction bindResolver(\n resolver: Resolver,\n plugins: Record<string, PluginEntry>,\n): BoundResolver {\n switch (resolver.type) {\n case \"static\":\n return {\n type: \"static\",\n requireParameters: resolver.requireParameters,\n inputType: resolver.inputType,\n placeholder: resolver.placeholder,\n };\n case \"constant\":\n return {\n type: \"constant\",\n value: resolver.value,\n requireParameters: resolver.requireParameters,\n };\n case \"info\":\n return { type: \"info\", text: resolver.text };\n case \"object\": {\n const imports = buildImports(plugins, resolver.importBindings);\n const bound: BoundResolver = {\n type: \"object\",\n requireParameters: resolver.requireParameters,\n };\n if (resolver.properties)\n bound.properties = bindFields(resolver.properties, plugins);\n if (resolver.definitions)\n bound.definitions = bindDefinitions(resolver.definitions, plugins);\n const { getProperties } = resolver;\n if (getProperties)\n bound.getProperties = ({ input }) => getProperties({ imports, input });\n return bound;\n }\n case \"array\": {\n const bound: BoundResolver = {\n type: \"array\",\n requireParameters: resolver.requireParameters,\n minItems: resolver.minItems,\n maxItems: resolver.maxItems,\n itemValueType: resolver.itemValueType,\n items: isResolverRef(resolver.items)\n ? resolver.items\n : bindResolver(resolver.items, plugins),\n };\n if (resolver.definitions)\n bound.definitions = bindDefinitions(resolver.definitions, plugins);\n return bound;\n }\n default: {\n const imports = buildImports(plugins, resolver.importBindings);\n const bound: BoundResolver = {\n type: \"dynamic\",\n requireParameters: resolver.requireParameters,\n inputType: resolver.inputType,\n placeholder: resolver.placeholder,\n prompt: resolver.prompt,\n };\n const {\n getContext,\n listItems,\n tryResolveWithoutPrompt,\n tryResolveFromSearch,\n } = resolver;\n if (getContext)\n bound.getContext = ({ input }) => getContext({ imports, input });\n if (listItems)\n bound.listItems = ({ input, context, search, cursor }) =>\n listItems({ imports, input, context, search, cursor });\n if (tryResolveWithoutPrompt) {\n bound.tryResolveWithoutPrompt = ({ input }) =>\n tryResolveWithoutPrompt({ imports, input });\n }\n if (tryResolveFromSearch) {\n bound.tryResolveFromSearch = ({ input, search }) =>\n tryResolveFromSearch({ imports, input, search });\n }\n return bound;\n }\n }\n}\n\n/** Bind an object resolver's literal `properties`: each field's inline resolver\n * is bound; a `{ ref }` passes through for the CLI to resolve against\n * `definitions` at runtime. */\nfunction bindFields(\n fields: Record<string, Field>,\n plugins: Record<string, PluginEntry>,\n): Record<string, BoundField> {\n const out: Record<string, BoundField> = {};\n for (const [key, field] of Object.entries(fields)) {\n out[key] = {\n ...field,\n resolver: isResolverRef(field.resolver)\n ? field.resolver\n : bindResolver(field.resolver, plugins),\n };\n }\n return out;\n}\n\n/** Bind each reusable resolver in a `definitions` block. */\nfunction bindDefinitions(\n definitions: Record<string, Resolver>,\n plugins: Record<string, PluginEntry>,\n): Record<string, BoundResolver> {\n const out: Record<string, BoundResolver> = {};\n for (const [key, def] of Object.entries(definitions)) {\n out[key] = bindResolver(def, plugins);\n }\n return out;\n}\n\n/** Bind a formatter descriptor: capture its imports into `getContext` (called\n * once per rendered page, context threaded); `format` is pure and passes\n * through. */\nfunction bindFormatter(\n formatter: Formatter,\n plugins: Record<string, PluginEntry>,\n): BoundFormatter {\n const imports = buildImports(plugins, formatter.importBindings);\n const bound: BoundFormatter = { format: formatter.format };\n const { getContext } = formatter;\n if (getContext)\n bound.getContext = ({ items, input, context }) =>\n getContext({ imports, items, input, context });\n return bound;\n}\n\n/**\n * Late pass: bind each method's attachments (input resolvers, output formatter)\n * onto its materialized entry. The bound forms capture their imports, so\n * downstream consumers (CLI / MCP) call them with input only, never an sdk.\n * Attachments contribute no surface; they live only on the method entry.\n */\nfunction bindAttachments(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n const plugins = context.plugins;\n for (const [id, descriptor] of descriptors) {\n if (descriptor.pluginType !== \"method\") continue;\n const entry = plugins[id];\n if (!entry || entry.pluginType !== \"method\") continue;\n if (descriptor.resolvers) {\n const bound: Record<string, BoundResolver> = {};\n for (const [param, resolver] of Object.entries(descriptor.resolvers)) {\n bound[param] = bindResolver(resolver, plugins);\n }\n entry.resolvers = bound;\n }\n if (descriptor.formatter) {\n entry.formatter = bindFormatter(descriptor.formatter, plugins);\n }\n }\n}\n\n/**\n * Pass 0: legacy bridge plugins. Run each function plugin\n * against a live compat view, merge its context contributions into the shared\n * SdkContext (meta keyed by method name, hooks composed, arbitrary fields\n * assigned), and synthesize a context.plugins entry per root key. The compat\n * view resolves root reads to materialized entry values and `context` to the\n * live SdkContext, so the legacy methods read context live at call time.\n * Topological order so a legacy plugin that depends on another runs after it.\n */\nfunction runLegacyPass(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n const plugins = context.plugins;\n const compatView = new Proxy(\n {},\n {\n get: (_target, prop) => {\n if (prop === \"context\") return context;\n const entry = plugins[prop as string] as\n | MethodEntry\n | PropertyEntry\n | undefined;\n return entry?.value;\n },\n },\n );\n for (const id of topoOrder(descriptors)) {\n const descriptor = descriptors.get(id);\n if (!descriptor || descriptor.pluginType !== \"legacy\") continue;\n const { rootKeys, meta, hooks, contextRest } = splitPluginContribution(\n descriptor.run(compatView as never),\n );\n Object.assign(context.meta, meta);\n Object.assign(context, contextRest);\n context.hooks = buildHooks(context.hooks, hooks);\n const exports = mirrorLegacyRootKeys(context, rootKeys, meta);\n // The legacy SDK always surfaced getRegistry (added by the stack's\n // buildSdk, not a plugin). Synthesize the same RegistryResult-shaped\n // accessor over the live surface + context.meta, so the bridged SDK keeps\n // the contract CLI/MCP/docs consume.\n if (!(\"getRegistry\" in exports)) {\n // `this` is the live SDK surface (getRegistry is called as\n // `sdk.getRegistry()`), so the registry reflects post-seal `addPlugin`\n // additions; `context.meta` is mutated in place, so it is live too.\n function getRegistry(\n this: Record<string, unknown>,\n options?: { package?: string },\n ): RegistryResult {\n // Fold in module-model entries by surface binding, not by walking the\n // raw graph keyed on each leaf's own name: the graph holds non-exported\n // imports, and two leaves that share a name would clobber each other.\n // Legacy plugins are then layered on from context.meta, which is their\n // registry of record (and carries dynamic/templated members like\n // `apps.{appKey}` that have no static binding); it wins on collision.\n const sdk = this ?? exports;\n const meta: Record<string, PluginMeta> = {};\n const formatters: Record<string, BoundFormatter> = {};\n const boundResolvers: Record<\n string,\n Record<string, BoundResolver>\n > = {};\n for (const [binding, id] of Object.entries(context.surface)) {\n const entry = context.plugins[id];\n if (!entry || entry.pluginType === \"aggregate\") continue;\n const m = pluginEntryMeta(entry);\n if (m) meta[binding] = m;\n const f = normalizeFormatter(entry, sdk);\n if (f) formatters[binding] = f;\n const r = normalizeBoundResolvers(entry);\n if (r) boundResolvers[binding] = r;\n }\n Object.assign(meta, context.meta);\n return buildRegistry({\n sdk,\n meta,\n formatters,\n boundResolvers,\n packageFilter: options?.package,\n });\n }\n exports.getRegistry = getRegistry;\n plugins.getRegistry = {\n pluginType: \"method\",\n name: \"getRegistry\",\n value: getRegistry as (input: unknown) => unknown,\n chain: [],\n };\n }\n plugins[id] = { pluginType: \"aggregate\", name: descriptor.name, exports };\n }\n}\n\n/**\n * Pass 1: method entries. `value` is a STABLE wrapper (identity never\n * changes, so a handle captured in `setup` stays valid). The `output` mode\n * shapes the surface (see Output): raw is a passthrough that validates and\n * folds the middleware chain itself; item/list route through the shared\n * framework wrappers (createFunction / createPaginatedFunction) for the\n * boundary (hooks, error normalization, scope, validation) and the envelope\n * / iterator. In every mode the fold reads `entry.chain` live per call, so a\n * post-seal `addPlugin` wrap still applies. The eager `setup` state is read\n * lazily from `states` at call time, so pass 2 can fill it after this pass.\n */\nfunction buildMethodEntries(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\n): void {\n const plugins = context.plugins;\n for (const [id, descriptor] of descriptors) {\n if (descriptor.pluginType !== \"method\") continue;\n const out = normalizeOutput(descriptor.output);\n const entry: MethodEntry = {\n pluginType: \"method\",\n name: descriptor.name,\n chain: [],\n inputSchema: descriptor.inputSchema,\n // Derive the presentation type from the output mode when the author did\n // not set one; an explicit meta.type (e.g. \"create\") still wins.\n meta:\n out.type === \"raw\" || descriptor.meta?.type\n ? descriptor.meta\n : { ...descriptor.meta, type: out.type },\n output: out,\n // Replaced below; never called.\n value: () => undefined,\n };\n const callRun = (input: unknown): unknown =>\n descriptor.run({\n imports: buildImports(plugins, descriptor.importBindings),\n state: states.get(id),\n input,\n });\n // Fold the middleware chain around a core, reading `entry.chain` live.\n const fold =\n (coreFn: (input: unknown) => unknown) =>\n (input: unknown): unknown => {\n let next = coreFn;\n for (const wrap of entry.chain) {\n const inner = next;\n next = (i: unknown) =>\n wrap.run({\n imports: buildImports(plugins, wrap.owner.importBindings),\n next: inner,\n input: i,\n });\n }\n return next(input);\n };\n const sdk = { context };\n\n if (out.type === \"list\") {\n // Middleware wraps the page fetcher here; wrapping the public\n // PaginatedSdkResult contract instead is a follow-up (no list method has\n // middleware yet). The boundary's hook payload gets the method name from\n // the explicit `name` option, not the (anonymous) folded core.\n entry.value = createPaginatedFunction(\n fold(callRun) as (o?: unknown) => Promise<unknown>,\n {\n sdk,\n schema: descriptor.inputSchema,\n name: descriptor.name,\n defaultPageSize: out.defaultPageSize,\n adaptPage: out.adaptPage,\n },\n ) as MethodEntry[\"value\"];\n } else if (out.type === \"item\") {\n // Wrap inside the fold so a dependent's middleware sees the public\n // `{ data }` envelope as `next`'s result. The `name` option gives the\n // boundary's hook payload the method name (the folded core is anonymous).\n const itemCore = async (input: unknown): Promise<{ data: unknown }> => ({\n data: await callRun(input),\n });\n entry.value = createFunction(\n fold(itemCore) as (o?: unknown) => Promise<unknown>,\n { sdk, schema: descriptor.inputSchema, name: descriptor.name },\n ) as MethodEntry[\"value\"];\n } else {\n // raw: validate (if a schema is set), fold, passthrough. No boundary, so\n // a raw method stays synchronous when its `run` is.\n entry.value = (rawInput: unknown) => {\n const input = descriptor.inputSchema\n ? descriptor.inputSchema.parse(rawInput)\n : rawInput;\n return fold(callRun)(input);\n };\n }\n // Positional projection (see Output): the surface and imports take ordered\n // args; pack them into the canonical `{ input }` before the mode value runs,\n // so validation, middleware, and `run` stay canonical. Set only provided\n // args so trailing optionals (e.g. `fetch(url)`) stay absent.\n if (descriptor.positional) {\n const names = descriptor.positional;\n const canonicalValue = entry.value;\n entry.value = (...args: unknown[]) => {\n const packed: Record<string, unknown> = {};\n names.forEach((name, i) => {\n if (i < args.length) packed[name] = args[i];\n });\n return canonicalValue(packed);\n };\n entry.positional = names;\n }\n plugins[id] = entry;\n }\n}\n\n/**\n * Pass 2: build each leaf's eager artifact at materialization, dependencies\n * first (like a module's imports are constructed before the module): a\n * method's `setup` state, a property's value (`get` or static). Side effects\n * therefore run at createSdk, not on first call. Demand-driven recursion\n * gives the dependency order and detects cycles.\n */\nfunction buildEagerArtifacts(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\n): void {\n const plugins = context.plugins;\n const built = new Set<string>();\n const building = new Set<string>();\n const ensureBuilt = (id: string): void => {\n if (built.has(id)) return;\n const descriptor = descriptors.get(id);\n // Aggregates have no eager artifact; legacy plugins build in pass 0.\n if (\n !descriptor ||\n descriptor.pluginType === \"aggregate\" ||\n descriptor.pluginType === \"legacy\"\n ) {\n built.add(id);\n return;\n }\n if (building.has(id)) {\n throw new Error(`createSdk: dependency cycle at \"${id}\".`);\n }\n building.add(id);\n // Build the leaves that actually provide this leaf's imports first; through\n // an aggregate dependency, importBindings already resolves to child ids.\n for (const { id: depId } of descriptor.importBindings) ensureBuilt(depId);\n if (descriptor.pluginType === \"method\") {\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports(plugins, descriptor.importBindings),\n })\n : undefined,\n );\n } else {\n // A property's `setup` runs once here (eager, dependencies first), like a\n // method's; its result is the state `get` reads.\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports(plugins, descriptor.importBindings),\n })\n : undefined,\n );\n if (descriptor.privileged) {\n // A built-in receives the live context as its (static) value.\n plugins[id] = {\n pluginType: \"property\",\n name: descriptor.name,\n value: context,\n meta: descriptor.meta,\n };\n } else if (descriptor.get) {\n // A live getter: re-derive from imports + state on each read.\n const get = descriptor.get;\n const importBindings = descriptor.importBindings;\n plugins[id] = {\n pluginType: \"property\",\n name: descriptor.name,\n getValue: () =>\n get({\n imports: buildImports(plugins, importBindings),\n state: states.get(id),\n }),\n meta: descriptor.meta,\n };\n } else {\n plugins[id] = {\n pluginType: \"property\",\n name: descriptor.name,\n value: descriptor.value,\n meta: descriptor.meta,\n };\n }\n }\n building.delete(id);\n built.add(id);\n };\n for (const id of descriptors.keys()) ensureBuilt(id);\n}\n\n/**\n * Pass 3: aggregate entries resolve their export bindings to child values\n * (a method's callable or a property's value).\n */\nfunction resolveAggregates(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n const plugins = context.plugins;\n for (const [id, descriptor] of descriptors) {\n if (descriptor.pluginType !== \"aggregate\") continue;\n const exports: Record<string, unknown> = {};\n for (const [binding, child] of Object.entries(descriptor.exports)) {\n bindValue(exports, binding, plugins[child.id]);\n }\n plugins[id] = { pluginType: \"aggregate\", name: descriptor.name, exports };\n }\n}\n\n/**\n * Pass 4: assemble middleware chains. Walk aggregates in\n * topological order (dependencies first), so a middleware plugin that depends\n * on another sorts after it. Appending in this order leaves each target's\n * chain innermost-first, which the pass-1 fold turns into dependents-outermost\n * at call time (retry depends on auth, so retry(auth(core))). A target must be\n * a direct dependency that resolves to a method.\n */\nfunction assembleMiddleware(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n const plugins = context.plugins;\n for (const id of topoOrder(descriptors)) {\n const descriptor = descriptors.get(id);\n if (\n !descriptor ||\n descriptor.pluginType !== \"aggregate\" ||\n !descriptor.middleware\n ) {\n continue;\n }\n for (const [targetBinding, fn] of Object.entries(descriptor.middleware)) {\n const edge = descriptor.importBindings.find(\n (b) => b.binding === targetBinding,\n );\n if (!edge) {\n throw new Error(\n `createSdk: middleware target \"${targetBinding}\" in plugin \"${id}\" ` +\n `is not a direct dependency. A middleware target must be a ` +\n `declared dependency of the wrapping plugin.`,\n );\n }\n const target = plugins[edge.id];\n if (!target || target.pluginType !== \"method\") {\n throw new Error(\n `createSdk: middleware target \"${targetBinding}\" in plugin \"${id}\" ` +\n `does not resolve to a method.`,\n );\n }\n // A list method's middleware would wrap the page fetcher, not the public\n // PaginatedSdkResult, so the wrap would see raw pages instead of the\n // iterator (see Pass 1). Reject until that contract is settled, rather\n // than silently giving surprising semantics.\n if (target.output?.type === \"list\") {\n throw new Error(\n `createSdk: middleware target \"${targetBinding}\" in plugin \"${id}\" ` +\n `resolves to a list-output method, which does not support ` +\n `middleware yet.`,\n );\n }\n target.chain.push({ run: fn, owner: descriptor });\n }\n }\n}\n\n/**\n * Materialize one plugin into an SDK whose surface is that plugin's exports.\n * A method root surfaces its callable under its bare name; a property root its\n * value; an aggregate root its export bindings.\n */\n// The module-model roots take `root: P & CompletenessOf<P>`: a complete graph\n// infers `P` unchanged, an unsatisfied declaration fails to assign (see\n// CompletenessOf). The surface type is recovered from `P` via `*SdkOf`.\nexport function createSdk<P extends AnyMethodPlugin>(\n root: P & CompletenessOf<P>,\n): MethodSdkOf<P>;\nexport function createSdk<P extends AnyPropertyPlugin>(\n root: P & CompletenessOf<P>,\n): PropertySdkOf<P>;\nexport function createSdk<P extends AnyAggregatePlugin>(\n root: P & CompletenessOf<P>,\n): AggregateSdkOf<P>;\nexport function createSdk<TSurface>(\n root: LegacyPlugin<TSurface>,\n): TSurface & SdkInternals;\nexport function createSdk<\n TProvides extends PluginProvides,\n TPlugin extends AnyPlugin,\n>(\n root: LegacyMergePlugin<TProvides, TPlugin>,\n): TProvides & {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n} & AddedSurface<TPlugin> &\n SdkInternals;\nexport function createSdk(\n root: AnyPlugin | LegacyMergePlugin,\n): Record<string, unknown> {\n const context: SdkContext = { plugins: {}, meta: {}, hooks: {}, surface: {} };\n // Transitional merge root: lift + run the legacy stack and materialize the\n // migrated module-model plugin, then surface the union (see Migration order).\n if (root.pluginType === \"legacy-merge\") {\n const { legacy, plugin } = root;\n const collectRoot: AnyAggregatePlugin = {\n pluginType: \"aggregate\",\n name: root.name,\n id: `${root.id}:merge`,\n imports: [legacy, plugin],\n importBindings: [],\n exports: {},\n };\n const plugins = materialize(collectPlugins(collectRoot), context);\n const legacyExports = (plugins[legacy.id] as AggregateEntry).exports;\n let pluginSurface: Record<string, unknown>;\n if (plugin.pluginType === \"aggregate\") {\n pluginSurface = (plugins[plugin.id] as AggregateEntry).exports;\n } else {\n pluginSurface = {};\n bindValue(pluginSurface, plugin.name, plugins[plugin.id]);\n }\n // Surface map for the registry: legacy methods (keyed by their own name)\n // plus the module plugin's bindings.\n for (const key of Object.keys(legacyExports)) context.surface[key] = key;\n if (plugin.pluginType === \"aggregate\") {\n recordExportSurface(context, plugin.exports);\n } else {\n context.surface[plugin.name] = plugin.id;\n }\n // Module exports win on a binding collision (a plugin migrated off the\n // legacy stack replaces the legacy method of the same name).\n return buildSurface(context, legacyExports, pluginSurface);\n }\n const plugins = materialize(collectPlugins(root), context);\n // Record the surface (binding -> leaf id) so the registry reports what the\n // consumer calls, by binding, not the raw plugin graph by id. `context` stays\n // a string key during migration (back-compat); `[CONTEXT]` is the off-surface\n // escape hatch the string surface eventually narrows to.\n if (root.pluginType === \"method\" || root.pluginType === \"property\") {\n context.surface[root.name] = root.id;\n const sdk = buildSurface(context);\n bindValue(sdk, root.name, plugins[root.id]);\n return sdk;\n }\n // A plugin root surfaces its export bindings; a bare legacy root surfaces the\n // exports pass 0 synthesized and records no surface map (it has no static\n // bindings to record), matching its method/property/aggregate siblings.\n if (root.pluginType === \"aggregate\")\n recordExportSurface(context, root.exports);\n return buildSurface(context, (plugins[root.id] as AggregateEntry).exports);\n}\n\n/**\n * Materialize a module-model plugin into a built SDK in place:\n * collect only the not-yet-materialized part of its graph (existing entries\n * satisfy its stand-ins), materialize that delta into the live `context.plugins`\n * (dependencies first, without re-running existing `setup`; new middleware\n * appends to existing chains), and surface the plugin's exports on the SDK root.\n */\nfunction addModelPlugin(\n sdk: Record<string, unknown>,\n plugin: AnyPlugin,\n options: { override?: boolean } = {},\n): void {\n const override = options.override === true;\n const context = getContext(sdk);\n\n // The root keys this plugin surfaces: an aggregate's export bindings, or a\n // leaf's bare name.\n const surfaceKeys =\n plugin.pluginType === \"aggregate\"\n ? Object.keys((plugin as AggregatePlugin).exports)\n : [plugin.name];\n\n // Preflight before materializing anything, so the operation is atomic\n // (validate, then write) and agrees with the legacy `applyPluginToSdk`\n // semantics: a reserved root key always throws; an existing key throws\n // unless `{ override: true }`.\n checkRootKeyCollisions(sdk, surfaceKeys, override, \"addPlugin\");\n\n const materialized = new Set(Object.keys(context.plugins));\n // A materialized id is a boundary to `collectPlugins`: it returns an empty\n // delta and we re-surface the existing entry. That's correct for surfacing a\n // dependency that was already materialized, but an `{ override: true }`\n // against such an id would silently keep the old implementation rather than\n // replace it. Replacing in-place would have to re-run dependents' setup and\n // rebuild middleware chains, which the incremental path does not support, so\n // refuse loudly instead of no-op'ing. Replace via `createSdk` with the new\n // implementation in the graph.\n if (override && materialized.has(plugin.id)) {\n throw new Error(\n `addPlugin: cannot override already-materialized plugin \"${plugin.id}\" ` +\n `on the incremental path. Rebuild the SDK with the replacement via createSdk.`,\n );\n }\n\n materialize(collectPlugins(plugin, materialized), context);\n const entry = context.plugins[plugin.id];\n if (entry.pluginType === \"aggregate\") {\n // Copy descriptors (not a spread/assign) so live-property getters stay live.\n Object.defineProperties(\n sdk,\n Object.getOwnPropertyDescriptors(entry.exports),\n );\n for (const [binding, child] of Object.entries(\n (plugin as AggregatePlugin).exports,\n )) {\n context.surface[binding] = child.id;\n }\n } else {\n bindValue(sdk, plugin.name, entry);\n context.surface[plugin.name] = plugin.id;\n }\n}\n\n/**\n * Extend an already-built SDK in place with one more plugin (the post-seal\n * extension path). Dispatches on shape: a module-model plugin (`defineMethod` /\n * `defineProperty` / `definePlugin`) is materialized incrementally into the live\n * graph; a legacy function plugin runs through the legacy merge. Either way the\n * caller's `sdk` binding is narrowed to include the addition.\n */\nexport function addPlugin<TSdk extends object, P>(\n sdk: TSdk,\n plugin: P,\n options?: { override?: boolean },\n): asserts sdk is TSdk & AddedSurface<P> {\n if (typeof plugin === \"function\") {\n const record = sdk as unknown as Record<string, unknown>;\n const contribution = applyPluginToSdk(\n record,\n plugin as Plugin<unknown, PluginProvides>,\n options ?? {},\n );\n // Mirror addModelPlugin: keep context.plugins/context.surface authoritative\n // for the legacy path too. applyPluginToSdk only writes sdk + context.meta,\n // so without this a surface-driven reader (getRegistryPlugin) would miss a\n // legacy method added after build. The contribution's keys are already\n // collision-checked against the sdk by mergeContribution. A pure-legacy\n // stack-built SDK (createPluginStack().toSdk()) has no [CONTEXT] graph, so\n // there's nothing to mirror.\n const context = (record as { [CONTEXT]?: SdkContext })[CONTEXT];\n if (context) {\n mirrorLegacyRootKeys(context, contribution.rootKeys, contribution.meta);\n // A legacy method surfaces under its own name (binding === id).\n for (const name of Object.keys(contribution.rootKeys)) {\n context.surface[name] = name;\n }\n }\n return;\n }\n addModelPlugin(\n sdk as unknown as Record<string, unknown>,\n plugin as AnyPlugin,\n options ?? {},\n );\n}\n","import { z } from \"zod\";\nimport type {\n FunctionRegistryEntry,\n RegistryResult,\n} from \"../../types/registry\";\nimport { CoreCancelledSignal } from \"../../types/signals\";\nimport { planParameters } from \"./plan\";\nimport {\n start as engineStart,\n step as engineStep,\n firstPage,\n toChoice,\n type EngineContext,\n} from \"./engine\";\nimport type {\n ControllerChoice,\n ControllerParameterDescription,\n ControllerMethodDescription,\n ControllerMethodSummary,\n Controller,\n} from \"./types\";\n\n/** The slice of a built SDK the driver needs: its registry accessor. */\nexport interface ControllerSdk {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n}\n\n/** Convert a zod schema to JSON Schema at the wall, swallowing the conversion\n * throwing on an unrepresentable schema (a missing `schema` is a softer failure\n * than a crashed projection). zod stays behind the wall; this is its plain\n * projection. */\nfunction toJsonSchema(\n schema: z.ZodType | undefined,\n): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n try {\n return z.toJSONSchema(schema) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** Project a registry entry to its lightweight summary (the list face). */\nfunction projectSummary(entry: FunctionRegistryEntry): ControllerMethodSummary {\n return {\n name: entry.name,\n ...(entry.description ? { description: entry.description } : {}),\n ...(entry.categories?.length ? { categories: entry.categories } : {}),\n };\n}\n\n/** Project a registry entry to its full serialized contract (the item face):\n * resolution facts from the parameter plan, per-field types from the input\n * schema (converted once), positional + output lifted off the entry. */\nfunction projectMethod(\n entry: FunctionRegistryEntry,\n): ControllerMethodDescription {\n const inputProperties = toJsonSchema(entry.inputSchema)?.properties as\n | Record<string, Record<string, unknown>>\n | undefined;\n const parameters: Record<string, ControllerParameterDescription> = {};\n for (const spec of planParameters(entry).parameters) {\n parameters[spec.name] = {\n required: spec.required,\n dynamic: Boolean(spec.resolver?.listItems),\n ...(spec.resolver?.inputType === \"search\" ? { searchable: true } : {}),\n ...(inputProperties?.[spec.name]\n ? { schema: inputProperties[spec.name] }\n : {}),\n ...(spec.staticChoices ? { choices: spec.staticChoices } : {}),\n ...(spec.requires.length ? { requireParameters: spec.requires } : {}),\n };\n }\n const output = toJsonSchema(entry.outputSchema);\n return {\n name: entry.name,\n ...(entry.description ? { description: entry.description } : {}),\n ...(entry.categories?.length ? { categories: entry.categories } : {}),\n parameters,\n ...(entry.positional?.length ? { positional: entry.positional } : {}),\n ...(output ? { output } : {}),\n };\n}\n\n/**\n * Build a {@link Controller} over a built SDK. Reads `sdk.getRegistry()`\n * at call time (so post-build `addPlugin` additions are visible) to find each\n * method's canonical input schema and bound resolvers, then drives the engine.\n * The SDK surface itself is untouched; this is a sibling layer.\n */\nexport function createController(sdk: ControllerSdk): Controller {\n function entryFor(method: string): FunctionRegistryEntry {\n const entry = sdk.getRegistry().functions.find((f) => f.name === method);\n if (!entry) throw new Error(`unknown method \"${method}\"`);\n return entry;\n }\n\n function contextFor(method: string): EngineContext {\n const entry = entryFor(method);\n return {\n method,\n schema: entry.inputSchema,\n parameters: planParameters(entry).parameters,\n };\n }\n\n const start: Controller[\"start\"] = ({ method, input, interactive }) =>\n engineStart(contextFor(method), input, interactive);\n\n const step: Controller[\"step\"] = ({ state, action }) =>\n engineStep(contextFor(state.method), state, action);\n\n const resolve: Controller[\"resolve\"] = async ({\n method,\n input,\n answer,\n interactive,\n }) => {\n // One resolution targets one method, and nothing mutates the SDK mid-loop,\n // so build the context (registry read + parameter plan) ONCE and reuse it\n // across every step, rather than rebuilding the whole registry per step via\n // the public start/step. Liveness is unaffected: each resolve() re-reads.\n const ctx = contextFor(method);\n let { state, result } = await engineStart(ctx, input, interactive);\n // Drive both question-bearing results: `ask`, and `failed` (a lookup threw;\n // its question offers retry/cancel). Without looping on `failed`, a\n // transient `listItems` failure would abort instead of offering a retry.\n while (result.status === \"ask\" || result.status === \"failed\") {\n const action = await answer({ state, result });\n // `cancel` flows through `step` like any other action (it returns a\n // `cancelled` result), so the loop exits and we raise the signal below.\n ({ state, result } = await engineStep(ctx, state, action));\n }\n if (result.status === \"done\") return result.value;\n if (result.status === \"cancelled\") {\n throw new CoreCancelledSignal(`resolution cancelled for \"${method}\"`);\n }\n const detail = result.issues\n .map((i) => (i.parameter ? `${i.parameter}: ${i.message}` : i.message))\n .join(\"; \");\n throw new Error(`invalid input for \"${method}\": ${detail}`);\n };\n\n const listMethods: Controller[\"listMethods\"] = () => ({\n data: sdk.getRegistry().functions.map(projectSummary),\n });\n\n const getMethod: Controller[\"getMethod\"] = ({ method }) => ({\n data: projectMethod(entryFor(method)),\n });\n\n const listChoices: Controller[\"listChoices\"] = async ({\n method,\n parameter,\n input = {},\n search,\n cursor,\n }) => {\n const spec = contextFor(method).parameters.find(\n (p) => p.name === parameter,\n );\n if (!spec?.resolver?.listItems) return { data: [] };\n // Compute pre-fetch context once and thread it into both listItems and\n // prompt, exactly as the interactive `buildQuestion` path does — otherwise a\n // resolver that gates options or labels via getContext misbehaves here.\n const context = await spec.resolver.getContext?.({ input });\n const page = await firstPage(\n spec.resolver.listItems({ input, context, search, cursor }),\n );\n const config = spec.resolver.prompt?.({ items: page.data, input, context });\n const data: ControllerChoice[] = (config?.choices ?? []).map(toChoice);\n return { data, nextCursor: page.nextCursor };\n };\n\n return { resolve, start, step, listMethods, getMethod, listChoices };\n}\n","/**\n * Core signal machinery.\n *\n * Signals are intentional control-flow throws — not failures. They're the\n * sibling of {@link CoreError}: where an error means \"something went wrong,\" a\n * signal means \"stop and do this on purpose.\" The first (and currently only)\n * one is {@link CoreCancelledSignal}, thrown by `Controller.resolve` when the\n * host cancels resolution (its answer callback returned `{ type: \"cancel\" }`).\n *\n * Like errors, every signal is brand-stamped with {@link CORE_SIGNAL_SYMBOL} so\n * a consumer can recognize one via {@link isCoreSignal} without sharing class\n * identity — important across the bundled-vs-standalone kitcore boundary.\n */\n\n/**\n * Cross-package brand for kitcore signals. `Symbol.for(key)` reads the\n * engine-global registry, so the same value resolves across realms and across\n * multiple copies of kitcore. Use {@link isCoreSignal} for cross-package checks.\n */\nexport const CORE_SIGNAL_SYMBOL = Symbol.for(\"kitcore.signal\");\n\n/**\n * Base class for kitcore signals. A signal is intentional control flow, not an\n * error, so it does NOT extend any error hierarchy that failure-handling code\n * sweeps up via `instanceof CoreError`. Subclasses declare a stable `name` and\n * `code`. (Mirrors the head convention, e.g. zapier-sdk's `ZapierSignal`.)\n */\nexport abstract class CoreSignal extends Error {\n abstract readonly name: string;\n abstract readonly code: string;\n\n constructor(message?: string) {\n super(message);\n // Keep `instanceof` working across the transpiled prototype chain.\n Object.setPrototypeOf(this, new.target.prototype);\n // Non-enumerable brand so it doesn't leak into JSON.\n Object.defineProperty(this, CORE_SIGNAL_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n }\n}\n\n/**\n * Cross-package-safe check that `value` is a kitcore signal (an intentional\n * control-flow throw), as opposed to a real error. Survives the\n * bundled/standalone kitcore split, where `instanceof CoreSignal` may not.\n */\nexport function isCoreSignal(value: unknown): boolean {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as { [k: symbol]: unknown })[CORE_SIGNAL_SYMBOL] === true,\n );\n}\n\n/**\n * Thrown by `Controller.resolve` when the host cancels resolution (the answer\n * callback returned `{ type: \"cancel\" }`). The lower-level `start`/`step`\n * protocol instead returns a `{ status: \"cancelled\" }` result, so a host\n * driving it directly never sees this throw; `resolve` raises it because its\n * contract is \"the resolved input, or nothing.\"\n */\nexport class CoreCancelledSignal extends CoreSignal {\n readonly name = \"CoreCancelledSignal\";\n readonly code = \"CANCELLED\" as const;\n\n constructor(message = \"resolution cancelled\") {\n super(message);\n }\n}\n","import { z } from \"zod\";\nimport type { FunctionRegistryEntry } from \"../../types/registry\";\nimport type { BoundResolver } from \"../types\";\nimport type { ControllerChoice } from \"./types\";\n\n/**\n * A resolvable position the engine walks: a top-level parameter, a nested object\n * field, or an array item. Carries its bound resolver (refs already resolved),\n * required-ness, the sibling parameters that must resolve first, a coarse value\n * type and any static enum choices (schema-derived for top-level params), and\n * any `input` a `{ ref, input }` contributes (`extraInput`, nested only).\n */\nexport interface Leaf {\n name: string;\n required: boolean;\n valueType?: string;\n staticChoices?: ControllerChoice[];\n resolver?: BoundResolver;\n requires: readonly string[];\n /** Extra input a `{ ref, input }` merges into the resolver's input. */\n extraInput?: Record<string, unknown>;\n}\n\n/** The ordered top-level parameters for a method, ready for the engine to walk:\n * topologically sorted so a parameter's `requires` all precede it. */\nexport interface ParameterPlan {\n parameters: Leaf[];\n}\n\n/** Strip optional/default/nullable wrappers to the inner schema, tracking\n * whether the wrappers made the field non-required. */\nfunction unwrap(schema: z.ZodType): { inner: z.ZodType; required: boolean } {\n let inner = schema;\n let required = true;\n for (;;) {\n if (inner instanceof z.ZodOptional) {\n required = false;\n inner = inner._zod.def.innerType as z.ZodType;\n } else if (inner instanceof z.ZodDefault) {\n required = false;\n inner = inner._zod.def.innerType as z.ZodType;\n } else if (inner instanceof z.ZodNullable) {\n inner = inner._zod.def.innerType as z.ZodType;\n } else {\n break;\n }\n }\n return { inner, required };\n}\n\n/** A coarse value-type label for reflection / input hints. */\nfunction valueTypeOf(inner: z.ZodType): string | undefined {\n if (inner instanceof z.ZodString) return \"string\";\n if (inner instanceof z.ZodNumber) return \"number\";\n if (inner instanceof z.ZodBoolean) return \"boolean\";\n if (inner instanceof z.ZodEnum) return \"string\";\n if (inner instanceof z.ZodArray) return \"array\";\n if (inner instanceof z.ZodObject) return \"object\";\n return undefined;\n}\n\n/** Static choices when the field is a fixed enum; otherwise undefined. */\nfunction staticChoicesOf(inner: z.ZodType): ControllerChoice[] | undefined {\n if (inner instanceof z.ZodEnum) {\n const values = inner.options as readonly string[];\n return values.map((value) => ({ label: value, value }));\n }\n return undefined;\n}\n\n/** The object shape of a (canonical) input schema, or undefined when the schema\n * is absent or not a plain object. */\nfunction objectShape(\n schema: z.ZodSchema | undefined,\n): Record<string, z.ZodType> | undefined {\n const { inner } = schema ? unwrap(schema) : { inner: undefined };\n if (inner instanceof z.ZodObject) {\n return inner.shape as Record<string, z.ZodType>;\n }\n return undefined;\n}\n\n/** Order specs so each parameter's `requires` precede it (Kahn's algorithm),\n * preserving the original order among independent parameters. Falls back to the\n * input order if a dependency cycle is present (it shouldn't be). */\nfunction topoOrder(specs: Leaf[]): Leaf[] {\n const byName = new Map(specs.map((s) => [s.name, s]));\n const ordered: Leaf[] = [];\n const placed = new Set<string>();\n let progressed = true;\n while (ordered.length < specs.length && progressed) {\n progressed = false;\n for (const spec of specs) {\n if (placed.has(spec.name)) continue;\n const ready = spec.requires.every((r) => !byName.has(r) || placed.has(r));\n if (ready) {\n ordered.push(spec);\n placed.add(spec.name);\n progressed = true;\n }\n }\n }\n // Cycle (or unsatisfiable edge): append the rest in original order.\n for (const spec of specs) if (!placed.has(spec.name)) ordered.push(spec);\n return ordered;\n}\n\n/**\n * Build the ordered resolution plan for a registry entry from its (canonical)\n * input schema and bound resolvers. Parameters come from the schema's object\n * shape; each is matched to its bound resolver (if any) and its `requires`\n * (`resolver.requireParameters`) for ordering. A method with no object schema\n * falls back to the bound-resolver keys.\n */\nexport function planParameters(entry: FunctionRegistryEntry): ParameterPlan {\n const shape = objectShape(entry.inputSchema);\n const resolvers = entry.boundResolvers ?? {};\n const names = shape ? Object.keys(shape) : Object.keys(resolvers);\n\n const specs: Leaf[] = names.map((name) => {\n const field = shape?.[name];\n const { inner, required } = field\n ? unwrap(field)\n : { inner: undefined as z.ZodType | undefined, required: false };\n const resolver = resolvers[name];\n return {\n name,\n required,\n valueType: inner ? valueTypeOf(inner) : undefined,\n staticChoices: inner ? staticChoicesOf(inner) : undefined,\n resolver,\n requires: resolver?.requireParameters ?? [],\n };\n });\n\n return { parameters: topoOrder(specs) };\n}\n","import type { z } from \"zod\";\nimport type {\n PromptConfig,\n PromptConfigChoice,\n DeprecatedPromptConfigChoice,\n} from \"../../utils/schema-utils\";\nimport type { SdkPage } from \"../../types/pagination\";\nimport type { BoundField, BoundResolver, Field, ResolverRef } from \"../types\";\nimport type { Leaf } from \"./plan\";\nimport type {\n ControllerAffordance,\n ControllerChoice,\n ControllerAction,\n ControllerError,\n ControllerIssue,\n ControllerListing,\n ControllerQuestion,\n ControllerResult,\n ControllerState,\n ControllerPath,\n} from \"./types\";\n\n/**\n * The static inputs the engine needs for one method: its ordered top-level\n * parameter plan and the canonical input schema (final whole-input validation).\n * `start`/`step` are otherwise pure over it plus the serializable state.\n *\n * Supported: seeds + constants + `tryResolveWithoutPrompt` auto-resolution\n * (a skip-check run before prompting in both modes), dynamic `select`\n * (paginated `listItems`), static / plain\n * `input`, static enum `select`, search (`tryResolveFromSearch` exact-match plus\n * re-listing by term), load-more pagination, retry of a failed fetch, and\n * `object` resolvers (static `properties`, dynamic `getProperties`, `{ ref }`\n * into `definitions`, nesting), and `array` resolvers (min/max, the add/done\n * `collection` decision, items of any kind).\n */\nexport interface EngineContext {\n method: string;\n schema?: z.ZodType;\n parameters: Leaf[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tree helpers (the partial result is a nested object/array value tree). */\n/* -------------------------------------------------------------------------- */\n\nfunction getAtPath(\n root: Record<string, unknown>,\n path: ControllerPath,\n): unknown {\n let node: unknown = root;\n for (const seg of path) {\n if (node == null || typeof node !== \"object\") return undefined;\n node = (node as Record<string, unknown>)[seg as string];\n }\n return node;\n}\n\nfunction setAtPath(\n root: Record<string, unknown>,\n path: ControllerPath,\n value: unknown,\n): void {\n let node = root;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i] as string;\n if (node[seg] == null || typeof node[seg] !== \"object\") node[seg] = {};\n node = node[seg] as Record<string, unknown>;\n }\n node[path[path.length - 1] as string] = value;\n}\n\n/** A path's dotted key for the `settled` set. */\nconst key = (path: ControllerPath): string => path.join(\".\");\n\n/** Whether the engine is done with the position at `path`. */\nfunction isSettled(state: ControllerState, path: ControllerPath): boolean {\n return state.settled.includes(key(path));\n}\n\n/** Mark the position at `path` done (idempotent). */\nfunction settle(state: ControllerState, path: ControllerPath): void {\n const k = key(path);\n if (!state.settled.includes(k)) state.settled.push(k);\n}\n\n/** Clone state so neither `start` nor `step` mutates the caller's object — the\n * snapshot/undo pattern depends on prior states staying intact. State is\n * serializable by contract, so a JSON round-trip is a faithful deep clone. */\nfunction clone(state: ControllerState): ControllerState {\n return JSON.parse(JSON.stringify(state)) as ControllerState;\n}\n\n/** Coerce a raw string answer toward the parameter's value type so final\n * validation sees the right primitive (full validation still runs on the whole\n * input). */\nfunction coerce(leaf: Leaf, raw: unknown): unknown {\n if (typeof raw !== \"string\") return raw;\n if (leaf.valueType === \"number\") {\n const n = Number(raw);\n return raw.trim() !== \"\" && !Number.isNaN(n) ? n : raw;\n }\n if (leaf.valueType === \"boolean\") {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n }\n return raw;\n}\n\n/** Run the resolver's `PromptConfig.validate` against a chosen/typed value.\n * Returns an error message when invalid (a string verdict, or a generic message\n * for a `false` verdict), or null when valid / no validator. Recomputes\n * `getContext` so `prompt` sees the same `context` it does when rendering. */\nasync function validationError(\n leaf: Leaf,\n value: unknown,\n state: ControllerState,\n): Promise<string | null> {\n const context = await resolveContext(leaf, state.resolved);\n const config = leaf.resolver?.prompt?.({\n items: state.listing?.items ?? [],\n input: mergeInput(state.resolved, leaf.extraInput),\n context,\n });\n if (!config?.validate) return null;\n const verdict = config.validate(value);\n if (verdict === true) return null;\n return typeof verdict === \"string\" ? verdict : `${leaf.name}: invalid value`;\n}\n\nexport function toChoice(\n c: PromptConfigChoice | DeprecatedPromptConfigChoice,\n): ControllerChoice {\n const label = \"label\" in c ? c.label : c.name;\n const hint = Array.isArray(c.hint) ? c.hint.join(\", \") : c.hint;\n return { label, value: String(c.value), hint };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Navigation: resolve the children/leaf at a path against the registry. */\n/* -------------------------------------------------------------------------- */\n\nfunction isRef(r: unknown): r is ResolverRef {\n return typeof r === \"object\" && r !== null && \"ref\" in r;\n}\n\n/** Turn an object's field (static `BoundField` or `getProperties`-built `Field`)\n * into a {@link Leaf}, resolving a `{ ref }` against the object's `definitions`\n * and threading the ref's `input`. */\nfunction toLeaf(\n name: string,\n field: BoundField | Field,\n definitions: Record<string, BoundResolver> | undefined,\n): Leaf {\n let resolver: BoundResolver | undefined;\n let extraInput: Record<string, unknown> | undefined;\n if (isRef(field.resolver)) {\n resolver = definitions?.[field.resolver.ref];\n extraInput = field.resolver.input;\n } else {\n // Inline: a `BoundField` carries a `BoundResolver`; a `getProperties`-built\n // field carries an unbound `Resolver`, which the design constrains to\n // closure-free static/constant (same runtime shape), so treat it as bound.\n resolver = field.resolver as unknown as BoundResolver;\n }\n return {\n name,\n required: field.required ?? false,\n resolver,\n extraInput,\n // Carry the field's value type so nested answers coerce (number/boolean)\n // the same way top-level params do. Without this a nested `z.number()`\n // field's typed answer stays a string and fails final validation.\n valueType: field.valueType,\n requires: resolver?.requireParameters ?? [],\n };\n}\n\n/** The ordered child leaves of an object resolver: its static `properties`\n * (bound at materialization), or the dynamic field set from\n * `getProperties({ input })`. */\nasync function objectChildren(\n resolver: BoundResolver,\n input: Record<string, unknown>,\n): Promise<Leaf[]> {\n if (resolver.properties) {\n return Object.entries(resolver.properties).map(([name, field]) =>\n toLeaf(name, field, resolver.definitions),\n );\n }\n if (!resolver.getProperties) return [];\n const fields = await resolver.getProperties({ input });\n return Object.entries(fields).map(([name, field]) => {\n // `getProperties` returns unbound fields: an inline import-bearing resolver\n // never had its imports captured, so its `listItems`/`getContext` would run\n // with an empty bag. Require a `{ ref }` into the object's `definitions`\n // (refs bind at materialization) for anything with imports — fail loud\n // rather than silently drop the dependency.\n if (\n !isRef(field.resolver) &&\n ((field.resolver as { imports?: readonly unknown[] }).imports?.length ??\n 0) > 0\n ) {\n throw new Error(\n `dynamic object field \"${name}\" inlines an import-bearing resolver; ` +\n `use { ref } into the object's definitions so its imports bind`,\n );\n }\n return toLeaf(name, field, resolver.definitions);\n });\n}\n\n/** The Leaf an array's items resolve through (its `items`, a `{ ref }` resolved\n * against the array's `definitions`). `name` is filled by the caller. */\nfunction arrayItem(resolver: BoundResolver): Leaf {\n const items = resolver.items;\n // Carry the array's element value type onto the item leaf so a free-text item\n // answer coerces (number/boolean) like a top-level or object field, rather\n // than staying a string and failing final validation.\n const valueType = resolver.itemValueType;\n if (isRef(items)) {\n return {\n name: \"\",\n required: true,\n resolver: resolver.definitions?.[items.ref],\n extraInput: items.input,\n valueType,\n requires: [],\n };\n }\n return {\n name: \"\",\n required: true,\n resolver: items as BoundResolver,\n valueType,\n requires: [],\n };\n}\n\n/** Merge a leaf's ref-supplied `input` over the running input. */\nfunction mergeInput(\n input: Record<string, unknown>,\n extra: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n return extra ? { ...input, ...extra } : input;\n}\n\n/** The ordered children of the object at `path` (top-level params for the root). */\nasync function childrenAt(\n ctx: EngineContext,\n path: ControllerPath,\n resolved: Record<string, unknown>,\n): Promise<Leaf[]> {\n if (path.length === 0) return ctx.parameters;\n const leaf = await leafAt(ctx, path, resolved);\n if (!leaf?.resolver || leaf.resolver.type !== \"object\") return [];\n return objectChildren(leaf.resolver, mergeInput(resolved, leaf.extraInput));\n}\n\n/** The leaf at `path`, walking object fields (string segments) and array items\n * (numeric segments → the array's item resolver). */\nasync function leafAt(\n ctx: EngineContext,\n path: ControllerPath,\n resolved: Record<string, unknown>,\n): Promise<Leaf | undefined> {\n let children = ctx.parameters;\n let leaf: Leaf | undefined;\n for (let i = 0; i < path.length; i++) {\n const seg = path[i];\n if (typeof seg === \"number\") {\n if (leaf?.resolver?.type !== \"array\") return undefined;\n leaf = arrayItem(leaf.resolver);\n } else {\n leaf = children.find((c) => c.name === seg);\n if (!leaf) return undefined;\n }\n // Prepare children for the next string (object-field) segment.\n if (i < path.length - 1 && typeof path[i + 1] === \"string\") {\n if (leaf?.resolver?.type !== \"object\") return undefined;\n children = await objectChildren(\n leaf.resolver,\n mergeInput(resolved, leaf.extraInput),\n );\n }\n }\n return leaf;\n}\n\n/** The array at `path`: its bounds and the item leaf (named after the array). */\nasync function arrayInfoAt(\n ctx: EngineContext,\n path: ControllerPath,\n resolved: Record<string, unknown>,\n): Promise<{ min: number; max: number; item: Leaf }> {\n const leaf = await leafAt(ctx, path, resolved);\n const resolver = leaf?.resolver;\n // Only ever reached on a confirmed array path (the walk surfaces an array\n // decision before this is asked). Fail loud rather than fabricate a hollow\n // item that would silently resolve as a value-less leaf downstream.\n if (resolver?.type !== \"array\") {\n throw new Error(`expected an array resolver at \"${key(path)}\"`);\n }\n return {\n min: resolver.minItems ?? 0,\n max: resolver.maxItems ?? Infinity,\n item: { ...arrayItem(resolver), name: String(path[path.length - 1]) },\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Question building (the leaf machinery). */\n/* -------------------------------------------------------------------------- */\n\nconst AFFORDANCE: Record<string, ControllerAffordance> = {\n choose: { action: \"choose\", description: \"Pick one of the listed options\" },\n custom: {\n action: \"custom\",\n description: \"Provide a value directly\",\n supply: \"value\",\n },\n search: {\n action: \"search\",\n description: \"Filter the options by a search term\",\n supply: \"term\",\n },\n more: { action: \"more\", description: \"Load more options\" },\n skip: { action: \"skip\", description: \"Omit this optional parameter\" },\n add: { action: \"add\", description: \"Add another item\" },\n done: { action: \"done\", description: \"Finish the list\" },\n retry: { action: \"retry\", description: \"Retry loading the options\" },\n cancel: { action: \"cancel\", description: \"Cancel resolution\" },\n};\n\n/** Await any `listItems` result shape (page, promise of page, or paginated\n * result) down to a single page. */\nexport async function firstPage(result: unknown): Promise<SdkPage<unknown>> {\n const page = (await result) as SdkPage<unknown> | undefined;\n return {\n data: Array.isArray(page?.data) ? page.data : [],\n nextCursor: page?.nextCursor,\n };\n}\n\n/** Run a resolver's pre-fetch `getContext` (if any) once, shaping the fetch and\n * available to the prompt. May re-run across re-asks, so resolvers keep it\n * cheap. */\nasync function resolveContext(\n leaf: Leaf,\n input: Record<string, unknown>,\n): Promise<unknown> {\n return leaf.resolver?.getContext?.({\n input: mergeInput(input, leaf.extraInput),\n });\n}\n\n/** Fetch one page for a dynamic resolver, folding it into the prior items. */\nasync function fetchListing(\n leaf: Leaf,\n input: Record<string, unknown>,\n opts: {\n search?: string;\n cursor?: string;\n priorItems?: unknown[];\n context?: unknown;\n } = {},\n): Promise<ControllerListing> {\n const page = await firstPage(\n leaf.resolver?.listItems?.({\n input: mergeInput(input, leaf.extraInput),\n context: opts.context,\n search: opts.search,\n cursor: opts.cursor,\n }),\n );\n return {\n items: [...(opts.priorItems ?? []), ...page.data],\n cursor: page.nextCursor,\n search: opts.search,\n exhausted: page.nextCursor == null,\n };\n}\n\nfunction selectActions(\n leaf: Leaf,\n listing: ControllerListing,\n multiple: boolean,\n): ControllerAffordance[] {\n // Multi-select picks from the offered set, so no free-text `custom`.\n const actions: ControllerAffordance[] = multiple\n ? [AFFORDANCE.choose]\n : [AFFORDANCE.choose, AFFORDANCE.custom];\n if (leaf.resolver?.inputType === \"search\") actions.push(AFFORDANCE.search);\n if (listing.cursor) actions.push(AFFORDANCE.more);\n if (!leaf.required) actions.push(AFFORDANCE.skip);\n return actions;\n}\n\n/** Render a dynamic select question from the accumulated listing (choices via\n * the resolver's `prompt`, run over all loaded items). */\nfunction selectQuestion(\n leaf: Leaf,\n input: Record<string, unknown>,\n listing: ControllerListing,\n context?: unknown,\n): ControllerQuestion {\n const config: PromptConfig | undefined = leaf.resolver?.prompt?.({\n items: listing.items,\n input: mergeInput(input, leaf.extraInput),\n context,\n });\n const multiple = config?.type === \"checkbox\";\n return {\n type: \"select\",\n message: config?.message ?? `Select ${leaf.name}:`,\n choices: (config?.choices ?? []).map(toChoice),\n ...(multiple ? { multiple: true } : {}),\n ...(config?.notes?.length ? { notes: config.notes } : {}),\n actions: selectActions(leaf, listing, multiple),\n };\n}\n\n/** Normalize an arbitrary throwable to the serializable {@link ControllerError}\n * DTO. The controller is the serialization wall, and a raw `Error` loses its\n * message under `JSON.stringify`, so a `failed` result carries plain data a\n * remote host can render. */\nfunction toControllerError(error: unknown): ControllerError {\n if (error instanceof Error) {\n const code = (error as { code?: unknown }).code;\n return {\n name: error.name,\n message: error.message,\n ...(typeof code === \"string\" ? { code } : {}),\n };\n }\n return { name: \"Error\", message: String(error) };\n}\n\n/** A `failed` result for the current leaf, offering retry/cancel. The attempt's\n * `search`/`cursor` are kept in `state.listing` so `retry` replays it. */\nfunction failedResult(\n state: ControllerState,\n name: string,\n error: unknown,\n): { state: ControllerState; result: ControllerResult } {\n return {\n state,\n result: {\n status: \"failed\",\n error: toControllerError(error),\n question: {\n type: \"select\",\n message: `Could not load options for ${name}.`,\n choices: [],\n actions: [AFFORDANCE.retry, AFFORDANCE.cancel],\n },\n },\n };\n}\n\n/** Build the question to ask for the leaf at `path`, fetching candidates for a\n * dynamic resolver. Returns the question plus any listing to carry forward. */\nasync function buildQuestion(\n leaf: Leaf,\n input: Record<string, unknown>,\n): Promise<{ question: ControllerQuestion; listing?: ControllerListing }> {\n const optional = !leaf.required;\n const resolver = leaf.resolver;\n\n // Dynamic resolver: compute pre-fetch context once, fetch the first page,\n // render a select from `prompt`. Context shapes the fetch and reaches prompt.\n if (resolver?.listItems) {\n const context = await resolveContext(leaf, input);\n const listing = await fetchListing(leaf, input, { context });\n return {\n question: selectQuestion(leaf, input, listing, context),\n listing,\n };\n }\n\n // Static enum (no resolver): select from the known values.\n if (leaf.staticChoices) {\n const actions: ControllerAffordance[] = [AFFORDANCE.choose];\n if (optional) actions.push(AFFORDANCE.skip);\n return {\n question: {\n type: \"select\",\n message: `Select ${leaf.name}:`,\n choices: leaf.staticChoices,\n actions,\n },\n };\n }\n\n // Free-text input (a static resolver or a plain parameter). `search` is an\n // affordance, not a text-input subtype, so it maps to plain text here.\n const inputType =\n resolver?.inputType && resolver.inputType !== \"search\"\n ? resolver.inputType\n : \"text\";\n const actions: ControllerAffordance[] = [AFFORDANCE.custom];\n if (optional) actions.push(AFFORDANCE.skip);\n return {\n question: {\n type: \"input\",\n message: `Enter ${leaf.name}:`,\n inputType,\n placeholder: resolver?.placeholder,\n actions,\n },\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* The walk. */\n/* -------------------------------------------------------------------------- */\n\nfunction finalize(\n ctx: EngineContext,\n resolved: Record<string, unknown>,\n): ControllerResult {\n // `resolved` is already a clean value tree (skips leave no value), so no\n // post-processing — just validate.\n if (!ctx.schema) return { status: \"done\", value: resolved };\n const parsed = ctx.schema.safeParse(resolved);\n if (parsed.success) {\n return { status: \"done\", value: parsed.data as Record<string, unknown> };\n }\n const issues: ControllerIssue[] = parsed.error.issues.map((i) => ({\n parameter: i.path.map(String).join(\".\") || undefined,\n message: i.message,\n }));\n return { status: \"invalid\", issues };\n}\n\n/** The next thing the walk wants: a leaf to value, or an array's add/done\n * decision. */\ntype Target =\n | { kind: \"leaf\"; path: ControllerPath; leaf: Leaf }\n | {\n kind: \"array\";\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n };\n\n/** The array's add/done question. `done` is offered once the count is within\n * range (the decision is only reached at `min ≤ count < max`). */\nfunction collectionQuestion(t: {\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n}): ControllerQuestion {\n const actions: ControllerAffordance[] = [AFFORDANCE.add];\n if (t.count >= t.min) actions.push(AFFORDANCE.done);\n return {\n type: \"collection\",\n message: `Add another ${t.path[t.path.length - 1]}? (${t.count} so far)`,\n count: t.count,\n min: t.min,\n // An unbounded array's max is Infinity, which JSON.stringify turns to null;\n // omit it so the question round-trips across the wall as plain data.\n ...(Number.isFinite(t.max) ? { max: t.max } : {}),\n actions,\n };\n}\n\n/** Walk the array at `path`: finish the last (composite) item if incomplete,\n * force items below `min`, offer add/done in range, auto-finish at `max`. A\n * non-interactive caller takes the provided array as-is. */\nasync function findInArray(\n ctx: EngineContext,\n state: ControllerState,\n path: ControllerPath,\n): Promise<Target | null> {\n if (isSettled(state, path)) return null; // finished\n if (getAtPath(state.resolved, path) == null)\n setAtPath(state.resolved, path, []);\n if (!state.interactive) {\n settle(state, path); // take the submitted array as-is (validation checks bounds)\n return null;\n }\n const { min, max, item } = await arrayInfoAt(ctx, path, state.resolved);\n const items = getAtPath(state.resolved, path) as unknown[];\n const len = items.length;\n const itemType = item.resolver?.type;\n // Finish the in-progress last item (only composites can be mid-build).\n if (len > 0 && (itemType === \"object\" || itemType === \"array\")) {\n const inner = await findNext(ctx, state, [...path, len - 1]);\n if (inner) return inner;\n }\n if (len < min) return descendItem(ctx, state, path, len, item);\n if (len < max) return { kind: \"array\", path, count: len, min, max };\n settle(state, path); // at max\n return null;\n}\n\n/** Seed a new array item's slot at `itemPath` and report its kind, so callers\n * can branch on how to proceed: an object/array item gets an empty container the\n * walk descends into; a leaf item has no slot and is asked directly. */\nfunction seedItemSlot(\n state: ControllerState,\n itemPath: ControllerPath,\n item: Leaf,\n): \"object\" | \"array\" | \"leaf\" {\n const type = item.resolver?.type;\n if (type === \"object\") {\n setAtPath(state.resolved, itemPath, {});\n return \"object\";\n }\n if (type === \"array\") {\n setAtPath(state.resolved, itemPath, []);\n return \"array\";\n }\n return \"leaf\";\n}\n\n/** Start a new item at `index`: create its slot (object/array) and find its\n * first hole, or return the leaf target directly. */\nasync function descendItem(\n ctx: EngineContext,\n state: ControllerState,\n arrayPath: ControllerPath,\n index: number,\n item: Leaf,\n): Promise<Target | null> {\n const itemPath = [...arrayPath, index];\n const kind = seedItemSlot(state, itemPath, item);\n if (kind === \"object\") return findNext(ctx, state, itemPath);\n if (kind === \"array\") return findInArray(ctx, state, itemPath);\n return { kind: \"leaf\", path: itemPath, leaf: item };\n}\n\n/** Depth-first search for the next thing to resolve: walk the object at `path`\n * in order, descending into nested objects and arrays, returning the first leaf\n * that isn't done, or an array decision. Objects are always walked into (their\n * doneness derives from their children). */\nasync function findNext(\n ctx: EngineContext,\n state: ControllerState,\n path: ControllerPath = [],\n): Promise<Target | null> {\n const container = (getAtPath(state.resolved, path) ?? {}) as Record<\n string,\n unknown\n >;\n for (const leaf of await childrenAt(ctx, path, state.resolved)) {\n const childPath = [...path, leaf.name];\n // Defer any child — leaf OR composite — until the siblings it requires have\n // real values (a skipped, value-less sibling doesn't satisfy a requirement);\n // a later pass revisits once the dependency resolves. Top-level params are\n // already topo-ordered (planParameters), but nested object/array fields are\n // walked in declaration order, so the gate must run before descending into\n // them too, not just on the leaf branch.\n if (!leaf.requires.every((r) => container[r] !== undefined)) continue;\n if (leaf.resolver?.type === \"object\") {\n if (getAtPath(state.resolved, childPath) == null)\n setAtPath(state.resolved, childPath, {});\n const inner = await findNext(ctx, state, childPath);\n if (inner) return inner;\n continue; // object fully resolved → next field\n }\n if (leaf.resolver?.type === \"array\") {\n const inner = await findInArray(ctx, state, childPath);\n if (inner) return inner;\n continue; // array finished → next field\n }\n // Done if it has a real value (resolved or seeded) or was skipped (settled).\n if (container[leaf.name] !== undefined || isSettled(state, childPath))\n continue;\n return { kind: \"leaf\", path: childPath, leaf };\n }\n return null;\n}\n\n/** Build and return the question for a leaf (or a `failed` result if its fetch\n * throws), setting it as the current outstanding question. */\nasync function askLeaf(\n state: ControllerState,\n path: ControllerPath,\n leaf: Leaf,\n opts: { error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n state.current = path;\n try {\n const { question, listing } = await buildQuestion(leaf, state.resolved);\n state.listing = listing;\n return {\n state,\n result: {\n status: \"ask\",\n question,\n ...(opts.error ? { error: opts.error } : {}),\n },\n };\n } catch (error) {\n state.listing = { items: [], exhausted: false };\n return failedResult(state, leaf.name, error);\n }\n}\n\n/** Find the next target and either auto-resolve / omit a leaf (per mode), ask\n * it, or surface an array's add/done decision. When nothing remains, validate. */\nasync function advance(\n ctx: EngineContext,\n state: ControllerState,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n for (;;) {\n const target = await findNext(ctx, state);\n if (!target) {\n delete state.current;\n delete state.listing;\n return { state, result: finalize(ctx, state.resolved) };\n }\n if (target.kind === \"array\") {\n state.current = target.path;\n delete state.listing;\n return {\n state,\n result: { status: \"ask\", question: collectionQuestion(target) },\n };\n }\n const { path, leaf } = target;\n\n // Skip-check (both modes): a resolver may settle a leaf without asking, e.g.\n // a configured default, or \"no connection needed\" for a no-auth app. Run\n // before prompting, matching the legacy resolver, so interactive runs don't\n // prompt for something the resolver can already answer.\n const auto = await leaf.resolver?.tryResolveWithoutPrompt?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n });\n if (auto) {\n // A real value marks the leaf done by presence; `resolvedValue: undefined`\n // (\"nothing to resolve here\") needs an explicit settle so the walk\n // doesn't re-ask it. `PromptConfig.validate` is intentionally NOT run\n // here: the resolver produced this value itself (e.g. via its own API\n // check), so it isn't a user answer to re-validate.\n if (auto.resolvedValue !== undefined)\n setAtPath(state.resolved, path, auto.resolvedValue);\n settle(state, path);\n continue;\n }\n\n if (!state.interactive) {\n // Headless / form-submit: omit optionals, ask only for required gaps.\n if (!leaf.required) {\n settle(state, path); // omit (no value)\n continue;\n }\n } else if (!leaf.required && !leaf.resolver) {\n // Interactive: a bare optional with no resolver has nothing to ask.\n settle(state, path); // omit (no value)\n continue;\n }\n\n return askLeaf(state, path, leaf);\n }\n}\n\n/** Seed from the caller's input plus any constant resolvers (input wins), then\n * advance to the first interaction (or completion). */\nexport async function start(\n ctx: EngineContext,\n input: Record<string, unknown> = {},\n interactive = true,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const resolved: Record<string, unknown> = {};\n for (const spec of ctx.parameters) {\n if (spec.resolver?.type === \"constant\")\n resolved[spec.name] = spec.resolver.value;\n }\n Object.assign(resolved, input);\n return advance(ctx, {\n method: ctx.method,\n resolved,\n settled: [],\n interactive,\n });\n}\n\n/** Apply the host's action to the leaf currently being asked, then advance. */\nexport async function step(\n ctx: EngineContext,\n prior: ControllerState,\n action: ControllerAction,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const state = clone(prior);\n\n // Cancel is leaf-independent and terminal: the host chose to stop. Return a\n // `cancelled` result like any other terminal (done/invalid); `resolve`\n // turns it into a thrown signal.\n if (action.type === \"cancel\") {\n delete state.current;\n delete state.listing;\n return { state, result: { status: \"cancelled\" } };\n }\n\n const path = state.current;\n if (!path) throw new Error(\"step called with no outstanding question\");\n const leaf = await leafAt(ctx, path, state.resolved);\n\n // Stay-on-parameter actions: refine the listing and re-ask.\n if (\n leaf &&\n (action.type === \"search\" ||\n action.type === \"more\" ||\n action.type === \"retry\")\n ) {\n return refine(ctx, state, leaf, path, action);\n }\n\n // Array decision actions: `current` is the array path.\n if (action.type === \"add\" || action.type === \"done\") {\n delete state.current;\n delete state.listing;\n if (action.type === \"done\") {\n settle(state, path); // finish the array (validation checks min)\n return advance(ctx, state);\n }\n const items = (getAtPath(state.resolved, path) ?? []) as unknown[];\n const { item } = await arrayInfoAt(ctx, path, state.resolved);\n const itemPath = [...path, items.length];\n // Leaf item: ask it directly. Composite item: seed its slot and let the\n // walk (advance → findNext) descend into it.\n if (seedItemSlot(state, itemPath, item) === \"leaf\")\n return askLeaf(state, itemPath, item);\n return advance(ctx, state);\n }\n\n switch (action.type) {\n case \"choose\":\n case \"custom\": {\n // The resolver may reject the value; re-ask the same leaf with the\n // message instead of advancing (closures stay engine-side, so a remote\n // host gets the message over the wire).\n if (leaf) {\n const error = await validationError(leaf, action.value, state);\n if (error) return askLeaf(state, path, leaf, { error });\n }\n setAtPath(\n state.resolved,\n path,\n leaf ? coerce(leaf, action.value) : action.value,\n ); // done by presence\n break;\n }\n case \"skip\":\n settle(state, path); // omit (no value; validation catches if required)\n break;\n default:\n throw new Error(`action \"${action.type}\" is not supported here`);\n }\n\n delete state.current;\n delete state.listing;\n return advance(ctx, state);\n}\n\n/** Handle the actions that stay on the current leaf: `search` (exact-match\n * short-circuit, else re-list by term), `more` (next page, appended), and\n * `retry` (replay the last attempt). */\nasync function refine(\n ctx: EngineContext,\n state: ControllerState,\n leaf: Leaf,\n path: ControllerPath,\n action:\n | { type: \"search\"; term: string }\n | { type: \"more\" }\n | { type: \"retry\" },\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const attempt =\n action.type === \"search\"\n ? { search: action.term, cursor: undefined, priorItems: [] as unknown[] }\n : {\n search: state.listing?.search,\n cursor: state.listing?.cursor,\n priorItems: state.listing?.items ?? [],\n };\n try {\n if (action.type === \"search\") {\n const exact = await leaf.resolver?.tryResolveFromSearch?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n search: action.term,\n });\n if (exact) {\n // `PromptConfig.validate` is intentionally NOT run here: the resolver\n // produced this value itself (it confirmed the typed term names a valid\n // value), so it isn't a user pick to re-validate.\n setAtPath(state.resolved, path, coerce(leaf, exact.resolvedValue)); // done by presence\n delete state.current;\n delete state.listing;\n return advance(ctx, state);\n }\n }\n const context = await resolveContext(leaf, state.resolved);\n state.listing = await fetchListing(leaf, state.resolved, {\n ...attempt,\n context,\n });\n return {\n state,\n result: {\n status: \"ask\",\n question: selectQuestion(leaf, state.resolved, state.listing, context),\n },\n };\n } catch (error) {\n state.listing = {\n items: attempt.priorItems,\n search: attempt.search,\n cursor: attempt.cursor,\n exhausted: false,\n };\n return failedResult(state, leaf.name, error);\n }\n}\n","/**\n * ------------------------------\n * Core configuration plugin\n * ------------------------------\n *\n * `createCorePlugin` is how a head supplies kitcore-level behavior knobs\n * (`adaptError` for branded errors, future entries similarly). The plugin\n * writes to `context.core`; kitcore reads from that path at every method\n * invocation. Consumers configure through this factory's typed `CoreOptions`,\n * never by touching the context path.\n *\n * createPluginStack()\n * .use(createCorePlugin({ adaptError: myAdaptError }))\n * .use(listAppsPlugin);\n *\n * Installing this plugin is optional. Kitcore reads `context.core.*`\n * with optional chaining, so an SDK without `createCorePlugin`\n * installed just falls back to kitcore's built-in behavior.\n *\n * Note: pagination shaping is NOT configured here. Each paginated method\n * declares its own `adaptPage` on `createPaginatedPluginMethod`, so the\n * adapter travels with the plugin (and stays type-checked) rather than\n * relying on an ambient SDK-wide default.\n */\n\nimport type { Plugin } from \"../types/plugin\";\nimport type { AdaptError } from \"../types/errors\";\n\n/**\n * Head-supplied configuration for kitcore-managed behavior. All fields are\n * optional; absent fields fall back to kitcore's built-in behavior.\n */\nexport interface CoreOptions {\n /**\n * Construct the head's branded error class for kitcore-thrown errors\n * (validation failures, non-Error normalization). Receives the\n * abstract `CoreErrorCode`, message, optional cause, and\n * type-specific details; returns the head's `Error` subclass. The\n * returned instance is automatically brand-stamped via\n * `createCoreError` so `isCoreError(err)` still recognizes\n * it across package boundaries. If absent, kitcore throws a plain\n * `CoreError`.\n */\n adaptError?: AdaptError;\n}\n\n/**\n * Register kitcore-level configuration. Writes the options to\n * `context.core` internally; consumers never reference the path.\n *\n * Reads of `context.core.adaptError` are\n * live: kitcore's method wrappers consult them at every invocation,\n * not at registration time. A `createCorePlugin` registered after a\n * method plugin still applies to that method's subsequent calls.\n */\nexport function createCorePlugin(\n options: CoreOptions,\n): Plugin<object, { context: { core: CoreOptions } }> {\n return () => ({\n context: {\n core: options,\n },\n });\n}\n","import { z } from \"zod\";\n\n// ============================================================================\n// SDK type parameter\n// ============================================================================\n//\n// `OutputFormatter` and the resolver types take the composed SDK shape as\n// their first type parameter (`TSdk`). Callers pass their concrete SDK\n// type at the declaration site; the types here stay free of any specific\n// SDK reference.\n\n// ============================================================================\n// Format Metadata Types\n// ============================================================================\n\nexport interface FormattedItem {\n title: string;\n /**\n * Secondary identifying context shown dimmed after the title (ids, keys,\n * slugs, ...). A dumb visual string a renderer shows verbatim, never\n * structured data it has to interpret; the same role as a prompt choice's\n * `hint`. An array is joined with \", \". Structured fields live on the\n * response / `outputSchema`, not here, so the renderer stays dumb.\n */\n hint?: string | string[];\n /** @deprecated Use `hint` (the renderer no longer interprets ids). */\n id?: string;\n /** @deprecated Use `hint`. */\n key?: string;\n /** @deprecated Use `hint`. */\n keys?: string[];\n description?: string;\n /** If provided, the renderer shows this raw (verbatim) instead of `details`. */\n raw?: unknown;\n details: Array<{\n label?: string;\n text: string;\n style: \"normal\" | \"dim\" | \"accent\" | \"warning\" | \"success\";\n }>;\n}\n\nexport interface OutputFormatter<\n TSdk,\n TItem = unknown,\n TParams = Record<string, unknown>,\n TContext = unknown,\n> {\n fetch?: (\n sdk: TSdk,\n params: TParams,\n item: TItem,\n context: TContext | undefined,\n ) => Promise<TContext>;\n format: (item: TItem, context?: TContext) => FormattedItem;\n}\n\n// Helper function to get output schema from an input schema\nexport function getOutputSchema(inputSchema: z.ZodType): z.ZodType | undefined {\n return (inputSchema._zod.def as { outputSchema?: z.ZodType }).outputSchema;\n}\n\n// Helper function to link input schemas to output schemas\nexport function withOutputSchema<T extends z.ZodType>(\n inputSchema: T,\n outputSchema: z.ZodType,\n): T & {\n _def: T[\"_def\"] & { outputSchema: z.ZodType };\n} {\n // Store output schema reference on the input schema\n Object.assign(inputSchema._zod.def, {\n outputSchema,\n });\n return inputSchema as T & {\n _def: T[\"_def\"] & { outputSchema: z.ZodType };\n };\n}\n\n// ============================================================================\n// Resolution Metadata Types\n// ============================================================================\n\n/** A selectable option in a prompt. `label` is the display text; `value` is\n * what the resolver returns when picked. */\nexport interface PromptConfigChoice {\n label: string;\n value: unknown;\n /**\n * Optional secondary info shown after the label. The CLI wraps it in\n * dimmed parens; an array is joined with \", \". Use for keys, ids, or\n * other context that's useful but shouldn't compete visually with\n * the primary label.\n */\n hint?: string | string[];\n}\n\n/**\n * The pre-rename choice shape, kept so existing resolvers keep compiling while\n * they migrate to {@link PromptConfigChoice}.\n * @deprecated Use {@link PromptConfigChoice} with `label` instead of `name`.\n */\nexport interface DeprecatedPromptConfigChoice {\n /** @deprecated Use `label` instead. */\n name: string;\n value: unknown;\n hint?: string | string[];\n}\n\nexport interface PromptConfig {\n type: \"list\" | \"checkbox\" | \"confirm\";\n /**\n * The answer key. The framework supplies it from the resolver's attachment\n * (the param the resolver resolves), so authors should omit it; a provided\n * value is overwritten.\n * @deprecated Omit; the framework supplies the param key.\n */\n name?: string;\n message: string;\n choices?: Array<PromptConfigChoice | DeprecatedPromptConfigChoice>;\n default?: unknown;\n /** Informational, non-selectable lines shown with the prompt (e.g. \"enable X\n * to see more\"). A host renders them dimmed, after the choices. The framework\n * stays agnostic about their content; the resolver composes the text. */\n notes?: string[];\n filter?: (value: unknown) => unknown;\n /**\n * Return `true` for valid; a string for a custom invalid message; or\n * `false` for invalid with a generic fallback message (\"X: invalid\n * value.\"). Prefer returning a string so users see something specific.\n */\n validate?: (value: unknown) => boolean | string;\n}\n\n/** A PromptConfig narrowed to single-select list mode. */\nexport type ListPromptConfig = PromptConfig & { type: \"list\" };\n\n/**\n * The prompt config the NEW-model resolvers (`defineResolver`) return. It omits\n * three fields the resolution controller does not honor, so authors can't\n * supply a silent no-op:\n * - `name` — the framework supplies the answer key (always was overwritten).\n * - `default`— no resolver uses it; the controller has no preselect concept.\n * - `filter` — no resolver uses it; transform values in `listItems` instead.\n * (The legacy `SchemaParameterResolver` still honors `default`/`filter`, so the\n * full `PromptConfig` stays for that path.)\n */\nexport type ResolverPromptConfig = Omit<\n PromptConfig,\n \"name\" | \"default\" | \"filter\"\n>;\n\nexport interface Resolver {\n type: string;\n depends?: readonly string[] | string[]; // Parameters this resolver depends on\n}\n\nexport interface StaticResolver extends Resolver {\n type: \"static\";\n inputType?: \"text\" | \"password\" | \"email\";\n placeholder?: string;\n}\n\n/**\n * A resolver that always resolves to a fixed value, never prompts. Use to\n * pin an implicit parameter that downstream resolvers or SDK calls require\n * but the user shouldn't have to provide. Triggers, for example, are always\n * `actionType: \"read\"` from the SDK's perspective; createTriggerInbox\n * declares `actionType: { type: \"constant\", value: \"read\" }` so the\n * standard `actionKeyResolver` and `inputsResolver` (which depend on\n * `actionType`) work without any pinned variants.\n *\n * Constants attached to keys that aren't in the schema are seeded into\n * `resolvedParams` upfront, so dependent resolvers find them in context\n * without the key appearing in the user-facing surface (TS option type,\n * CLI flags, generated docs).\n */\nexport interface ConstantResolver extends Resolver {\n type: \"constant\";\n value: unknown;\n}\n\n/**\n * Fields shared by both variants of {@link DynamicResolver}.\n */\ninterface DynamicResolverBase<TSdk, TItem, TParams> extends Resolver {\n type: \"dynamic\";\n prompt: (items: TItem[], params: TParams) => PromptConfig;\n /** Capabilities that expand results. The parameter resolver shows a hint for any that aren't enabled. */\n requireCapabilities?: string[];\n /**\n * Optional hook called before fetch/prompt. If it returns a non-null object,\n * resolvedValue is used directly and fetch/prompt are skipped entirely. Return\n * null to fall through to the normal resolution flow. Implementations should\n * catch their own errors and return null on failure rather than throwing, so\n * that a transient API error does not block the CLI entirely.\n */\n tryResolveWithoutPrompt?: (\n sdk: TSdk,\n params: TParams,\n ) => Promise<{ resolvedValue: unknown } | null>;\n}\n\n/**\n * The classic dynamic-resolver variant: `fetch` returns a list of items\n * that the CLI renders as a search-filterable dropdown. The user picks one.\n */\nexport interface DynamicListResolver<TSdk, TItem, TParams>\n extends DynamicResolverBase<TSdk, TItem, TParams> {\n /** Explicitly absent on the list variant; set `inputType: \"search\"` to opt into the search variant. */\n inputType?: never;\n /** Only meaningful for the search variant; set to `never` here so TS catches misuse. */\n placeholder?: never;\n fetch: (\n sdk: TSdk,\n resolvedParams: TParams,\n ) => PromiseLike<\n | TItem[]\n | { data: TItem[]; nextCursor?: string }\n | AsyncIterable<{ data: TItem[]; nextCursor?: string }>\n >;\n}\n\n/**\n * The search-input variant: the CLI prompts the user for free-form text\n * first, then calls `fetch` with `{ ...resolvedParams, search }`.\n *\n * `fetch` can short-circuit by returning a primitive (`string | number`),\n * which the CLI treats as an exact match — no dropdown is rendered. Any\n * other return (array, page, async iterable) is rendered as the normal\n * search-filterable dropdown.\n *\n * The `search` key is injected by the CLI at call time; it isn't part of\n * `TParams` because callers that invoke `fetch` directly (outside the CLI)\n * are responsible for passing it themselves. Search-mode resolvers should\n * type `TParams` as `{ search?: string; ...otherDeps }` to make this\n * explicit.\n */\nexport interface DynamicSearchResolver<TSdk, TItem, TParams>\n extends Omit<DynamicResolverBase<TSdk, TItem, TParams>, \"prompt\"> {\n inputType: \"search\";\n /**\n * Hint text appended to the search prompt's message. NOT used as\n * inquirer's `default` value, because inquirer prefills `default` as\n * editable text that the user has to delete before typing.\n */\n placeholder?: string;\n /**\n * Search-mode always renders a single-select @inquirer/search dropdown,\n * so `prompt` must return a list-typed PromptConfig. Checkbox/confirm\n * configs would be silently ignored at runtime; the type narrows so\n * misuse fails at compile time.\n *\n * Note: a primitive return from `fetch` (string | number) is treated\n * as an exact match and short-circuits without running this prompt or\n * the resolver's validate/filter. Canonicalize inside `fetch` if the\n * exact-match path needs normalization.\n */\n prompt: (items: TItem[], params: TParams) => ListPromptConfig;\n fetch: (\n sdk: TSdk,\n resolvedParams: TParams,\n ) => PromiseLike<\n | string\n | number\n | TItem[]\n | { data: TItem[]; nextCursor?: string }\n | AsyncIterable<{ data: TItem[]; nextCursor?: string }>\n >;\n}\n\n/**\n * A dynamic resolver: either a classic list (`inputType` absent) or a\n * search-input variant (`inputType: \"search\"`). The discriminator is the\n * `inputType` field; TS narrows to the right variant when you check it.\n */\nexport type DynamicResolver<\n TSdk,\n TItem = unknown,\n TParams = Record<string, unknown>,\n> =\n | DynamicListResolver<TSdk, TItem, TParams>\n | DynamicSearchResolver<TSdk, TItem, TParams>;\n\n// Minimal field descriptor for resolver prompts. Full InputFieldItem is accepted too.\nexport interface ResolverFieldItem {\n type: string;\n key: string;\n title?: string;\n is_required?: boolean;\n value_type?: string;\n choices?: Array<{ label: string; value: string }>;\n fields?: ResolverFieldItem[];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolver?: ResolverMetadata<any, any, any>;\n}\n\nexport interface FieldsResolver<\n TSdk,\n TParams = Record<string, unknown>,\n TResult = Record<string, unknown>,\n> extends Resolver {\n type: \"fields\";\n fetch: (sdk: TSdk, resolvedParams: TParams) => Promise<ResolverFieldItem[]>;\n transform?: (value: Record<string, unknown>) => TResult;\n}\n\nexport interface ArrayResolver<TSdk, TParams = Record<string, unknown>>\n extends Resolver {\n type: \"array\";\n fetch: (\n sdk: TSdk,\n resolvedParams: TParams,\n ) => Promise<ResolverMetadata<TSdk, unknown, TParams>>; // Returns a resolver for each item\n minItems?: number; // Default 0\n maxItems?: number; // Default Infinity\n}\n\nexport type ResolverMetadata<\n TSdk,\n TItem = unknown,\n TParams = Record<string, unknown>,\n> =\n | StaticResolver\n | ConstantResolver\n | DynamicResolver<TSdk, TItem, TParams>\n | FieldsResolver<TSdk, TParams>\n | ArrayResolver<TSdk, TParams>;\n\n/**\n * Extract the SDK shape a resolver requires by inferring it from the resolver's\n * `fetch` callback. Static and Constant resolvers have no fetch and produce\n * `unknown`, meaning they impose no requirement on the plugin's SDK.\n */\nexport type RequiredSdkOf<R> = R extends {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fetch: (sdk: infer S, ...args: any[]) => any;\n}\n ? S\n : unknown;\n\n/**\n * Per-entry resolver-slot validator. For each key, if the plugin's `TSdk`\n * satisfies the resolver's required SDK, the entry passes through unchanged;\n * otherwise the slot widens to `ResolverMetadata<TSdk, any, any>`, so TS\n * surfaces the mismatch at the specific offending key rather than at the\n * whole `resolvers` object.\n *\n * Pair with `NoInfer<TSdk>` at the call site to prevent TS from inferring\n * `TSdk` from a resolver entry (which would silently accommodate the\n * mismatch). With `NoInfer`, the only inference site for `TSdk` is the\n * `sdk` argument, and each resolver is then checked against it.\n */\nexport type ValidResolvers<TSdk, R> = {\n [K in keyof R]: TSdk extends RequiredSdkOf<R[K]>\n ? R[K]\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ResolverMetadata<TSdk, any, any>;\n};\n\n// Wrapper interface for resolver metadata to allow future extensibility\nexport interface ResolverConfig<\n TSdk,\n TItem = unknown,\n TParams = Record<string, unknown>,\n> {\n resolver: ResolverMetadata<TSdk, TItem, TParams>;\n // Future metadata types can be added here:\n // validation?: ValidationMetadata;\n // display?: DisplayMetadata;\n}\n\n// Helper function to add resolver metadata to schemas\nexport function withResolver<\n T extends z.ZodType,\n TSdk,\n TItem = unknown,\n TParams = Record<string, unknown>,\n>(schema: T, config: ResolverConfig<TSdk, TItem, TParams>): T {\n // Store resolver metadata on the schema definition\n (\n schema._zod.def as { resolverMeta?: ResolverConfig<TSdk, TItem, TParams> }\n ).resolverMeta = config;\n return schema;\n}\n\n// ============================================================================\n// Schema Description Utilities\n// ============================================================================\n\nexport function getSchemaDescription(schema: z.ZodSchema): string | undefined {\n return schema.description;\n}\n\nexport function getFieldDescriptions(\n schema: z.ZodObject<z.ZodRawShape>,\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n const shape = schema.shape;\n\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (fieldSchema instanceof z.ZodType && fieldSchema.description) {\n descriptions[key] = fieldSchema.description;\n }\n }\n\n return descriptions;\n}\n\n// ============================================================================\n// Positional Parameter Metadata\n// ============================================================================\n\nexport interface PositionalMetadata {\n positionalMeta: {\n positional: true;\n };\n}\n\n// Helper function to mark a parameter as positional for CLI\nexport function withPositional<T extends z.ZodType>(\n schema: T,\n): T & {\n _def: T[\"_def\"] & PositionalMetadata;\n} {\n // Store positional metadata on the schema definition\n Object.assign(schema._zod.def, {\n positionalMeta: { positional: true },\n } satisfies PositionalMetadata);\n return schema as T & {\n _def: T[\"_def\"] & PositionalMetadata;\n };\n}\n\nfunction schemaHasPositionalMeta<T extends z.ZodType>(\n schema: T,\n): schema is T & {\n _def: T[\"_def\"] & PositionalMetadata;\n} {\n return \"positionalMeta\" in schema._zod.def;\n}\n\n// Helper function to check if a parameter should be positional\nexport function isPositional(schema: z.ZodType): boolean {\n // Check the current schema first\n if (\n schemaHasPositionalMeta(schema) &&\n (schema._zod.def as { positionalMeta?: { positional: boolean } })\n .positionalMeta?.positional\n ) {\n return true;\n }\n\n // If this is a ZodOptional, check the inner type\n if (schema instanceof z.ZodOptional) {\n return isPositional(schema._zod.def.innerType as z.ZodType);\n }\n\n // If this is a ZodDefault, check the inner type\n if (schema instanceof z.ZodDefault) {\n return isPositional(schema._zod.def.innerType as z.ZodType);\n }\n\n return false;\n}\n\n// ============================================================================\n// Open Enum\n// ============================================================================\n\n// Builds a string-valued schema whose known values are listed for docs\n// and downstream AST consumers, with a `z.string()` fallback so a new\n// server-side value doesn't crash `.parse()` on the response. Use this\n// for any lifecycle status field the backend may extend.\nexport function openEnum<const T extends readonly [string, ...string[]]>(\n values: T,\n description: string,\n) {\n return z.union([z.enum(values), z.string()]).describe(description);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;;;ACWX,SAAS,YAAY,OAAuB;AACjD,SACE,MAEG,QAAQ,sBAAsB,OAAO,EAErC,QAAQ,WAAW,GAAG,EACtB,QAAQ,QAAQ,GAAG,EACnB,KAAK,EAEL,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,EACxE,KAAK,GAAG;AAEf;AAUO,SAAS,YAAY,OAAuB;AACjD,MAAI,SAAS,MAEV,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,CAAC;AACD,SAAO;AAGT;AAySO,SAAS,aAKd,QAAW,QAAiD;AAE5D,EACE,OAAO,KAAK,IACZ,eAAe;AACjB,SAAO;AACT;AAMO,SAAS,qBAAqB,QAAyC;AAC5E,SAAO,OAAO;AAChB;AAEO,SAAS,qBACd,QACwB;AACxB,QAAM,eAAuC,CAAC;AAC9C,QAAM,QAAQ,OAAO;AAErB,aAAW,CAACC,MAAK,WAAW,KAAK,OAAO,QAAQ,KAAK,GAAG;AACtD,QAAI,uBAAuB,cAAE,WAAW,YAAY,aAAa;AAC/D,mBAAaA,IAAG,IAAI,YAAY;AAAA,IAClC;AAAA,EACF;AAEA,SAAO;AACT;AAaO,SAAS,eACd,QAGA;AAEA,SAAO,OAAO,OAAO,KAAK,KAAK;AAAA,IAC7B,gBAAgB,EAAE,YAAY,KAAK;AAAA,EACrC,CAA8B;AAC9B,SAAO;AAGT;AAEA,SAAS,wBACP,QAGA;AACA,SAAO,oBAAoB,OAAO,KAAK;AACzC;AAGO,SAAS,aAAa,QAA4B;AAEvD,MACE,wBAAwB,MAAM,KAC7B,OAAO,KAAK,IACV,gBAAgB,YACnB;AACA,WAAO;AAAA,EACT;AAGA,MAAI,kBAAkB,cAAE,aAAa;AACnC,WAAO,aAAa,OAAO,KAAK,IAAI,SAAsB;AAAA,EAC5D;AAGA,MAAI,kBAAkB,cAAE,YAAY;AAClC,WAAO,aAAa,OAAO,KAAK,IAAI,SAAsB;AAAA,EAC5D;AAEA,SAAO;AACT;AAUO,SAAS,SACd,QACA,aACA;AACA,SAAO,cAAE,MAAM,CAAC,cAAE,KAAK,MAAM,GAAG,cAAE,OAAO,CAAC,CAAC,EAAE,SAAS,WAAW;AACnE;","names":["key","start","key","key","exports","import_zod","key","exports","getContext","getRegistry","meta","id","plugins","import_zod","import_zod","topoOrder","actions","start","step","import_zod","key"]}