@zapier/kitcore 0.17.1 → 0.17.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/utils/string-utils.ts","../src/utils/schema-utils.ts","../src/utils/stability.ts","../src/registry.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/call-options.ts","../src/utils/async-context.ts","../src/utils/method-scope.ts","../src/utils/call-context.ts","../src/utils/core-options.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/utils/output-policy.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/model/resolution/questions.ts","../src/model/resolution/walk.ts","../src/utils/core-plugin.ts","../src/transport/attempt-http-request.ts","../src/transport/authorize-http-request.ts","../src/transport/dispatch-http-request.ts","../src/transport/prepare-http-request.ts","../src/transport/receive-http-response.ts","../src/transport/initialize-http-request.ts","../src/transport/retry-http-request.ts","../src/transport/send-http-request.ts","../src/transport/fetch.ts","../src/transport/redact.ts","../src/connections/default-connection-scheme.ts","../src/connections/normalize-connection.ts","../src/connections/resolve-connection.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 disposeSdk,\n resolvePlugin,\n CoreDisposeError,\n fromFunctionPlugin,\n defineLegacyMerge,\n dangerousContextPlugin,\n getRegistryPlugin,\n coreOptionsPluginRef,\n getContext,\n getRegistry,\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 defineOverride,\n /** @deprecated Use `defineOverride`. */\n defineMethodOverride,\n defineResolver,\n defineFormatter,\n defineHook,\n defineProperty,\n declareMethod,\n declareProperty,\n declareOptionalProperty,\n declareOptionalMethod,\n declareDefault,\n selectExports,\n omitExports,\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 CreateSdkOptions,\n DisposeFn,\n SdkContext,\n SdkContextCarrier,\n LeafMeta,\n OverridableMetaFields,\n MethodPlugin,\n MethodAnnotator,\n MethodOverridePlugin,\n HookPlugin,\n HookAnnotator,\n DynamicMember,\n PropertyPlugin,\n AggregatePlugin,\n PluginSurface,\n MethodAttachment,\n Formatter,\n // The model resolver descriptor (the `defineResolver` result). It can't take\n // the bare name `Resolver` during the transition: `export *` from schema-utils\n // already publishes a legacy `Resolver`, and two public `Resolver`s would\n // collide. A head still needs to name it to annotate a `defineResolver`\n // result (the same reason `Formatter` is exported), so it ships as\n // `ModelResolver`; once the legacy `Resolver` is deleted this is renamed to\n // `Resolver`.\n Resolver as ModelResolver,\n ResolverRequirement,\n BoundResolver,\n BoundFormatter,\n ResolverType,\n ListItemsResult,\n PluginSummary,\n StandInId,\n LeafSummary,\n // Resolution controller surface.\n Controller,\n ControllerSdk,\n ControllerState,\n ControllerResult,\n ControllerError,\n ControllerIssue,\n ControllerQuestion,\n ControllerAction,\n ControllerPagination,\n ControllerListingPage,\n ControllerListingPosition,\n ControllerSelectPage,\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 { CORE_OPTIONS_ID, defaultLogDeprecation } from \"./utils/core-options\";\nexport type {\n CoreOptions,\n DeprecationWarning,\n StabilityNotice,\n} from \"./utils/core-options\";\n\nexport type {\n MethodHooks,\n ComposedAnnotator,\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\n// Types only: heads name `CallContext` (the run bag / annotate helper) and\n// `Annotations` (the annotator return). The minting/brand functions stay\n// internal — a head reads/writes `.annotations` on a context it is handed; it\n// never mints or brand-checks one.\nexport type {\n CallContext,\n Annotations,\n CallOrigin,\n} from \"./utils/call-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 {\n createDeprecationLogger,\n createStabilityNoticeLogger,\n} from \"./utils/logging\";\nexport type { StabilityNoticeLogger } 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 ResponseMeta,\n OutputDataValidationReport,\n} from \"./types/output-validation\";\n\nexport type {\n CategoryDefinition,\n FunctionRegistryEntry,\n FunctionDeprecation,\n RegistryResult,\n} from \"./types/registry\";\n\n// The stability ladder: the levels array (single source of truth for the\n// type, tier iteration order, and docs render order), the normalizer the\n// registry projection uses, and the one label renderer every\n// description-rendering consumer (CLI help, MCP tool descriptions) calls.\nexport {\n STABILITY_LEVELS,\n STABILITY_TITLES,\n normalizeStability,\n applyStabilityLabel,\n} from \"./utils/stability\";\nexport type { StabilityLevel } from \"./utils/stability\";\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 isCoreCancelledSignal,\n} from \"./types/signals\";\n\n// Transport: the swappable `sendHttpRequest` pipeline and its fetch-shaped\n// request type. Wrap focused behavior around the narrowest stage; see\n// docs/design/2026-08-03-kitcore-transport.md.\nexport {\n attemptHttpRequestPlugin,\n authorizeHttpRequestPlugin,\n dispatchHttpRequestPlugin,\n initializeHttpRequestPlugin,\n prepareHttpRequestPlugin,\n receiveHttpResponsePlugin,\n sendHttpRequestPlugin,\n fetchPlugin,\n retryHttpRequestPlugin,\n retryHttpRequestOptionsPluginRef,\n RETRY_HTTP_REQUEST_OPTIONS_ID,\n redactHeaders,\n redactHttpRequest,\n} from \"./transport\";\nexport type {\n AttemptHttpRequestInput,\n AuthorizeHttpRequestInput,\n DispatchHttpRequestInput,\n HttpAttemptContext,\n HttpFetchInit,\n HttpPipelineState,\n InitializeHttpRequestInput,\n HttpOperationContext,\n HttpOperationStart,\n PrepareHttpRequestInput,\n HttpRequest,\n HttpRequestInput,\n HttpResponse,\n ReceiveHttpResponseInput,\n RetryHttpRequestOptions,\n SendHttpRequest,\n} from \"./transport\";\n\n// Connections: generic opaque reference normalization. Heads may provide a\n// default scheme; kitcore does not assign one.\nexport {\n defaultConnectionSchemePlugin,\n normalizeConnectionPlugin,\n resolveConnectionPlugin,\n} from \"./connections\";\nexport type {\n DefaultConnectionSchemeInput,\n NormalizedConnection,\n NormalizeConnectionInput,\n ResolveConnectionInput,\n} from \"./connections\";\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","import { z } from \"zod\";\n\n/**\n * Plugins with a required-parameter rename declare two schemas: a canonical one\n * (new names only, carrying `.meta({ aliases })`) and a `z.union([canonical,\n * deprecated])` for runtime input parsing (so callers passing old names still\n * validate). The union has no object shape, so everything that reads parameter\n * shape/requiredness — the registry projection, generated docs, and the\n * resolution planner — must read the canonical variant, not the union.\n *\n * Convention: the FIRST union variant is the canonical schema. Every plugin\n * that uses unions follows this; it's explicit and needs no extra metadata.\n * Runtime validation still uses the full union; only shape reading canonicalizes.\n */\nexport function 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\n/** Strip optional/default/nullable wrappers to the inner schema, tracking\n * whether the wrappers made the field non-required. */\nexport function unwrapSchema(schema: z.ZodType): {\n inner: z.ZodType;\n required: boolean;\n} {\n let inner = schema;\n let required = true;\n for (;;) {\n // `unwrap()` is typed against zod's core base, so each result is cast back\n // to the classic `ZodType` this module and its callers speak.\n if (inner instanceof z.ZodOptional || inner instanceof z.ZodDefault) {\n required = false;\n inner = inner.unwrap() as z.ZodType;\n } else if (inner instanceof z.ZodNullable) {\n // Nullable alone still demands the key, so requiredness is unchanged.\n inner = inner.unwrap() as z.ZodType;\n } else {\n break;\n }\n }\n return { inner, required };\n}\n\n/**\n * The object shape of a method's input schema, or undefined when the schema is\n * absent or not a plain object. A required-rename union (`z.union([canonical,\n * deprecated])`) is canonicalized to its first variant first, and\n * optional/default/nullable wrappers are stripped, so a schema whose fields are\n * readable at all is read rather than treated as shapeless.\n */\nexport function objectShapeOf(\n schema: z.ZodSchema | undefined,\n): Record<string, z.ZodType> | undefined {\n const canonical = canonicalInputSchema(schema);\n if (!canonical) return undefined;\n const { inner } = unwrapSchema(canonical);\n if (inner instanceof z.ZodObject) {\n return inner.shape as Record<string, z.ZodType>;\n }\n return undefined;\n}\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 * four 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 * - `validate`— validation is the resolver's top-level `validate`, which\n * never routes through rendering (and gets `imports`).\n */\nexport type ResolverPromptConfig = Omit<\n PromptConfig,\n \"name\" | \"default\" | \"filter\" | \"validate\"\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// Negatable Parameter Metadata\n// ============================================================================\n\n/**\n * Marks an optional boolean schema for which omission is distinct from false:\n * omitting the value means \"use the server default\" or \"preserve the current\n * value\", so an explicit false needs its own affordance. A string supplies\n * the domain antonym — \"disabled\" for `enabled` — which each surface renders\n * in its own vocabulary (a CLI as a flag spelling, a tool description as\n * prose). `true` requests generic negation when the domain has no antonym.\n *\n * Declare it via `.meta({ negatable: \"disabled\" } satisfies NegatableMetadata)`.\n * The `satisfies` matters: zod's metadata type permits arbitrary keys, so it\n * is the only compile-time check against a misspelled key.\n */\nexport interface NegatableMetadata {\n negatable: true | string;\n}\n\n/**\n * Read a schema's `negatable` metadata: `true`, the domain antonym, or\n * undefined when the schema doesn't declare one. Unwraps optional/default\n * wrappers like `isPositional`, so the `.meta()` call may sit on any layer\n * of the chain.\n */\nexport function getNegatable(\n schema: z.ZodType,\n): NegatableMetadata[\"negatable\"] | undefined {\n const negatable = (\n schema as { meta?: () => { negatable?: unknown } | undefined }\n ).meta?.()?.negatable;\n if (negatable === true) return true;\n if (typeof negatable === \"string\" && negatable.length > 0) return negatable;\n\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) {\n return getNegatable(schema._zod.def.innerType as z.ZodType);\n }\n\n return undefined;\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.\n// The return type is annotated rather than inferred: left inferred, the\n// declaration rollup expands `z.enum`'s mapped type through an `infer` step and\n// emits a form TypeScript then rejects (TS2536), which surfaces to any consumer\n// typechecking with `skipLibCheck: false`.\nexport function openEnum<const T extends readonly [string, ...string[]]>(\n values: T,\n description: string,\n): z.ZodUnion<readonly [z.ZodEnum<{ [K in T[number]]: K }>, z.ZodString]> {\n return z.union([z.enum(values), z.string()]).describe(description);\n}\n","/**\n * API stability tiers.\n *\n * A plugin declares exactly one level via `PluginMeta.stability`; tier\n * membership (which subpath aggregate exports the plugin) is structural,\n * so nothing here compares levels ordinally. The array is the single\n * source of truth: it derives the {@link StabilityLevel} type, gives the\n * ladder tests their adjacent-tier iteration order, and gives docs a\n * render order.\n */\nexport const STABILITY_LEVELS = [\"stable\", \"beta\", \"experimental\"] as const;\n\nexport type StabilityLevel = (typeof STABILITY_LEVELS)[number];\n\n/**\n * Title-case display names for each level, for section-level badges in\n * generated docs (e.g. `Code Workflows (Beta)`). Inline description\n * labels go through {@link applyStabilityLabel} instead.\n */\nexport const STABILITY_TITLES = {\n stable: \"Stable\",\n beta: \"Beta\",\n experimental: \"Experimental\",\n} as const satisfies Record<StabilityLevel, string>;\n\n/**\n * Normalize authored meta to a concrete level: absent means `\"stable\"`,\n * and the deprecated `experimental: true` boolean means `\"experimental\"`.\n * The registry projection runs every entry through this, so\n * `FunctionRegistryEntry.stability` is always concrete and consumers\n * never branch on `undefined`.\n *\n * The declared value can cross a JSON boundary from a hand-written\n * plugin, so at runtime it may be any string. An unrecognized level\n * clamps to `\"experimental\"` — the author declared the method not\n * stable, and clamping keeps the raw string out of notices and labels.\n * It doesn't throw because this also runs in the `getStability` live\n * read on the call path, where a throw would break the observed call.\n */\nexport function normalizeStability(meta: {\n stability?: StabilityLevel;\n experimental?: boolean;\n}): StabilityLevel {\n if (meta.stability !== undefined) {\n return (STABILITY_LEVELS as readonly string[]).includes(meta.stability)\n ? meta.stability\n : \"experimental\";\n }\n return meta.experimental ? \"experimental\" : \"stable\";\n}\n\n/**\n * The shared label renderer: every consumer that renders a registry\n * entry's description (CLI help, MCP tool descriptions) labels it\n * through this function, so a new consumer cannot silently drop the\n * label. `stability` stays structured data on the registry entry — the\n * label is applied at render time, never baked into the stored\n * description (docs badge at the section level, so baking it in would\n * double-badge).\n *\n * The label follows the plugin's declared level, not the subpath that\n * surfaced it: a beta method surfaced through an experimental-tier\n * consumer still reads \"(beta)\".\n */\nexport function applyStabilityLabel({\n description,\n stability,\n placement = \"suffix\",\n}: {\n description: string;\n /** Absent means stable (the value may arrive from outside the\n * normalized registry projection, e.g. hand-built JSON). */\n stability: StabilityLevel | undefined;\n /**\n * `\"suffix\"` renders `<description> (beta)` (CLI help);\n * `\"prefix\"` renders `[Beta] <description>` (MCP tool descriptions,\n * where the front of the string is what an LLM reads first).\n */\n placement?: \"suffix\" | \"prefix\";\n}): string {\n if (stability === undefined || stability === \"stable\") return description;\n return placement === \"prefix\"\n ? `[${STABILITY_TITLES[stability]}] ${description}`\n : `${description} (${stability})`;\n}\n","import 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\";\nimport { canonicalInputSchema } from \"./utils/schema-utils\";\nimport { normalizeStability } from \"./utils/stability\";\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\nexport function buildRegistry({\n sdk,\n meta,\n formatters,\n resolvers,\n positional,\n skipInputValidation,\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, lifted off materialized method entries by the\n * caller (like `formatters`). A bound runtime thing, not descriptive meta, so\n * supplied separately rather than read off `PluginMeta`. */\n resolvers?: Record<string, Record<string, BoundResolver>>;\n /** Per-binding positional projections, lifted off materialized method entries\n * by the caller (like `resolvers`). A runtime projection, not meta. */\n positional?: Record<string, readonly string[]>;\n /** Per-binding `skipInputValidation` flags, lifted off materialized method\n * entries. A boundary fact (not meta) the controller reads to skip its final\n * validation for methods that own their input. */\n skipInputValidation?: Record<string, boolean>;\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 const stability = normalizeStability(m);\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 outputSchema: m.outputSchema,\n positional: positional?.[key],\n skipInputValidation: skipInputValidation?.[key],\n categories: (m.categories ?? []).map((c) =>\n typeof c === \"string\" ? c : c.key,\n ),\n resolvers: resolvers?.[key],\n formatter: formatters?.[key],\n stability,\n // Deprecated derived read, literal by name: only the experimental\n // tier reads true. Beta reads false — the \"not stable\" warning duty\n // lives in `stability` and the runtime notice, not this boolean.\n experimental: stability === \"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 * Method-call lifecycle hooks. Plugins contribute `onMethodStart` and/or\n * `onMethodEnd` observers, plus an optional pre-run `annotator` that returns\n * fields merged into the call's annotation bag; `buildHooks` composes each\n * across plugins so multiple contributors coexist. Composition is right-additive\n * (newer plugins fire — and `annotator` fields win — after earlier ones); only\n * opt-in methods built through `createPluginMethod` /\n * `createPaginatedPluginMethod` trigger the hooks.\n */\n\nimport type { Annotations, CallOrigin } from \"./call-context\";\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 /** The call's correlation id, copied from the per-call context; `null` where\n * id minting was unavailable. */\n callId: string | null;\n /**\n * Origin of the call's root, copied from the per-call context. `\"surface\"` =\n * surface-origin (an SDK-surface call or a runtime delegation — real user\n * work); `\"internal\"` = a framework-internal call minted by kitcore's own\n * machinery (resolver/formatter/dispose/observer twins, `resolvePlugin`).\n * Orthogonal to `depth` (an internal call is still `depth 0`); a head can drop\n * internal-origin calls from telemetry.\n */\n callOrigin: CallOrigin;\n /**\n * The call's annotation bag, carried live from the per-call context. At\n * `onMethodStart` it holds the early-knowable fields (boundary annotator +\n * a method's pre-run `annotator`); by `onMethodEnd` any mid-`run` writes\n * are visible too (same object reference throughout the call).\n */\n annotations: Annotations;\n}\n\nexport type OnMethodStart = (ctx: OnMethodStartContext) => void;\n\nexport interface OnMethodEndContext extends OnMethodStartContext {\n durationMs: number;\n error?: Error;\n}\n\nexport type OnMethodEnd = (ctx: OnMethodEndContext) => void;\n\n/**\n * A composed pre-run annotator: given a call's method name and (normalized,\n * pre-validation) input, it returns {@link Annotations} the boundary merges into\n * the call's bag before `onMethodStart`. Unlike the `void` lifecycle observers,\n * this one returns a value; composition merges the returned bags rather than\n * chaining side effects. A contributor with nothing to add returns an empty bag,\n * so absence is modelled by no annotator rather than an `undefined` return.\n */\nexport type ComposedAnnotator = (ctx: {\n methodName: string;\n input: unknown;\n}) => Annotations;\n\nexport interface MethodHooks {\n onMethodStart?: OnMethodStart;\n onMethodEnd?: OnMethodEnd;\n annotator?: ComposedAnnotator;\n}\n\n// Functions already isolated by `isolate` (leaf wrappers, and composites built\n// only from them). Membership lets `isolate` skip re-wrapping during the\n// incremental composition buildHooks performs, so each observer ends up behind\n// exactly one try/catch instead of one per pass. A WeakSet keys on identity and\n// releases entries when the functions are collected, so it holds no state of\n// its own.\nconst isolated = new WeakSet<object>();\n\n/**\n * Wrap one fire-and-forget observer so it runs in isolation, or pass through\n * `undefined`. A throwing observer must not break the observed method or its\n * sibling observers, so a throw is logged and swallowed rather than\n * propagated. Idempotent: an already-isolated function is returned unchanged,\n * so repeated composition never stacks redundant wrappers. A routed error\n * handler is deliberately not supported: this composes at build time and has\n * no access to the per-SDK configuration such a handler would live on.\n */\nfunction isolate<C>(\n observer: ((ctx: C) => void) | undefined,\n): ((ctx: C) => void) | undefined {\n if (!observer) return undefined;\n if (isolated.has(observer)) return observer;\n const wrapped = (ctx: C) => {\n try {\n observer(ctx);\n } catch (error) {\n console.error(\n \"[core] A method-lifecycle observer threw and was ignored. \" +\n \"Observers are fire-and-forget and must not throw.\",\n error,\n );\n }\n };\n isolated.add(wrapped);\n return wrapped;\n}\n\n/**\n * Compose two same-shaped observer hooks into one that runs `existing` then\n * `added`, each isolated so a throw reaches neither the method boundary nor\n * the sibling observer. Returns the lone (wrapped) side when only one is set,\n * or `undefined` when neither is. The composed function only calls isolated\n * parts, so it cannot throw either; marking it isolated lets a later pass fold\n * it in without re-wrapping. 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 const wrappedExisting = isolate(existing);\n const wrappedAdded = isolate(added);\n if (!wrappedExisting) return wrappedAdded;\n if (!wrappedAdded) return wrappedExisting;\n const composed = (ctx: C) => {\n wrappedExisting(ctx);\n wrappedAdded(ctx);\n };\n isolated.add(composed);\n return composed;\n}\n\n/**\n * Compose two annotators into one that merges both returned bags (`added` wins\n * on key collision, keeping composition right-additive like {@link composeVoid}).\n * Each contributor is guarded at registration (see `assembleHooks`), so neither\n * side throws here.\n */\nfunction composeAnnotators(\n existing: ComposedAnnotator | undefined,\n added: ComposedAnnotator | undefined,\n): ComposedAnnotator | undefined {\n if (!existing) return added;\n if (!added) return existing;\n return (ctx) => ({ ...existing(ctx), ...added(ctx) });\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. `annotator` is the one\n * non-`void` member: it returns `Annotations` the boundary merges before\n * `onMethodStart`, so it uses `composeAnnotators` rather than `composeVoid`.\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 const annotator = composeAnnotators(existing.annotator, added.annotator);\n if (annotator) result.annotator = annotator;\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\nexport interface StabilityNoticeLogger {\n logStabilityNotice(message: string): void;\n resetStabilityNotices(): void;\n}\n\n/**\n * Create a package-tagged stability-notice logger: the deprecation logger's\n * sibling for non-stable (beta / experimental) API warnings, with the same\n * once-per-process dedupe policy and its own independent message Set.\n */\nexport function createStabilityNoticeLogger(\n tag: string,\n): StabilityNoticeLogger {\n const loggedNotices = new Set<string>();\n\n return {\n logStabilityNotice(message: string): void {\n if (loggedNotices.has(message)) return;\n loggedNotices.add(message);\n\n console.warn(`[${tag}] ${message}`);\n },\n\n resetStabilityNotices(): void {\n loggedNotices.clear();\n },\n };\n}\n\nexport const { logStabilityNotice, resetStabilityNotices } =\n createStabilityNoticeLogger(\"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\nimport { logDeprecation } from \"./logging\";\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 CONCAT: \"concat\",\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 Lists\n// ============================================================================\n\ninterface PaginatedResult<TItem> {\n data: TItem[];\n nextCursor?: string;\n}\n\n/**\n * Supplies one list to `concatLists`: called with that list's own cursor,\n * resolves one page. An SDK paginated method fits directly\n * (`({ cursor }) => sdk.listThings({ cursor })`; awaiting a paginated\n * result yields the requested page).\n */\ntype ListSource<TItem> = (options: {\n cursor?: string;\n}) => PromiseLike<PaginatedResult<TItem>>;\n\ninterface ConcatCursorEnvelope {\n v: typeof CURSOR_VERSION;\n source: typeof CURSOR_SOURCE.CONCAT;\n index: number;\n cursor?: string;\n}\n\nfunction encodeConcatCursor(index: number, cursor: string | undefined): string {\n const envelope: ConcatCursorEnvelope = {\n v: CURSOR_VERSION,\n source: CURSOR_SOURCE.CONCAT,\n index,\n cursor,\n };\n return encodeBase64(JSON.stringify(envelope));\n}\n\nfunction decodeConcatCursor(incoming?: string): {\n index: number;\n cursor: string | undefined;\n} {\n if (!incoming) {\n return { index: 0, cursor: undefined };\n }\n try {\n const envelope = JSON.parse(decodeBase64(incoming)) as ConcatCursorEnvelope;\n if (\n envelope.v === CURSOR_VERSION &&\n envelope.source === CURSOR_SOURCE.CONCAT &&\n typeof envelope.index === \"number\"\n ) {\n return { index: envelope.index, cursor: envelope.cursor };\n }\n } catch {\n // Fall through to the plain-cursor fallback below.\n }\n // Not a concat envelope: treat it as the first list's own cursor.\n return { index: 0, cursor: incoming };\n}\n\n/**\n * List one page of several paginated lists joined end to end. Lists are\n * drained in order; pass a page's `nextCursor` back in to get the next page.\n *\n * Pagination is stateless: every outgoing cursor encodes which list to\n * resume plus that list's own cursor, so a fresh `concatLists` call\n * continues exactly where the previous page left off. A cursor stores its\n * position by list index, so it is only valid while `sources` keeps the\n * same lists in the same order. Lists must produce disjoint items\n * themselves; there is no cross-list dedupe (an in-memory seen-set could\n * not survive the cursor round-trip).\n *\n * Uses paginateBuffered internally to normalize page sizes across list\n * boundaries: if the first list only has 2 items, they'll be buffered with\n * items from the next list into a full page.\n */\nexport async function concatLists<TItem>({\n sources,\n pageSize = 100,\n cursor,\n}: {\n /** The lists to concatenate, each supplied as a page-fetching source. */\n sources: ListSource<TItem>[];\n pageSize?: number;\n /** Cursor from a previous `concatLists` page; resumes there. */\n cursor?: string;\n}): Promise<PaginatedResult<TItem>> {\n if (sources.length === 0) {\n return { data: [] };\n }\n\n const pageFunction = async (options: {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n }): Promise<PaginatedResult<TItem>> => {\n let { index, cursor: listCursor } = decodeConcatCursor(options.cursor);\n\n while (index < sources.length) {\n const page = await sources[index]({ cursor: listCursor });\n const hasMoreInList = page.nextCursor != null;\n\n if (page.data.length === 0 && !hasMoreInList) {\n index++;\n listCursor = undefined;\n continue;\n }\n\n return {\n data: page.data,\n nextCursor: hasMoreInList\n ? encodeConcatCursor(index, page.nextCursor)\n : index < sources.length - 1\n ? encodeConcatCursor(index + 1, undefined)\n : undefined,\n };\n }\n\n return { data: [] };\n };\n\n const result = await paginateBuffered(pageFunction, {\n pageSize,\n cursor,\n }).next();\n return result.done ? { data: [] } : result.value;\n}\n\n/**\n * @deprecated Use {@link concatLists}; awaiting either yields the same one\n * page. The page-iterable half of the old return shape is gone; to walk\n * pages, pass each page's `nextCursor` to a fresh call.\n */\nexport function concatPaginated<TItem>({\n sources,\n pageSize,\n cursor,\n}: {\n sources: ListSource<TItem>[];\n pageSize?: number;\n cursor?: string;\n}): Promise<PaginatedResult<TItem>> {\n logDeprecation(\"concatPaginated() is deprecated. Use concatLists() instead.\");\n return concatLists({ sources, pageSize, cursor });\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 *\n * @deprecated Call `.pages()` on the paginated result instead; it returns a\n * plain AsyncIterable over pages with no wrapper needed.\n */\nexport function toIterable<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n logDeprecation(\n \"toIterable() is deprecated. Call .pages() on the paginated result instead.\",\n );\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","import { z } from \"zod\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\n\n/**\n * The floor the framework holds its own call parameters to, and the only\n * statement of their shapes. Which of them a given boundary reads at all is\n * that boundary's {@link FrameworkOptionsPolicy}.\n *\n * MINIMAL on purpose. It rejects what the machinery cannot act on and nothing\n * else, leaving a plugin free to tighten it. `pageSize` is at least 1 because a\n * page loop asking upstream for zero items does not terminate. `maxItems` may\n * be 0, since \"return nothing\" is a coherent request the loop already handles.\n * `cursor` is any string: its meaning belongs to the head's API, including\n * whatever a reverse-paginating one encodes in it.\n *\n * A plugin that wants a tighter rule writes it in its own `inputSchema`, and\n * both run. See {@link parseCallOptions}.\n */\nexport const CallFrameworkOptionsSchema = z.object({\n /** Page to fetch. Opaque to kitcore: the head's API defines the format. */\n cursor: z.string().optional(),\n /** Items per page. */\n pageSize: z.number().int().min(1).optional(),\n /** Stop after this many items, across pages. */\n maxItems: z.number().int().min(0).optional(),\n /** Bypass output validation for this one call. */\n skipOutputDataValidation: z.boolean().optional(),\n});\n\nexport type CallFrameworkOptions = z.infer<typeof CallFrameworkOptionsSchema>;\nexport type CallFrameworkOptionKey = keyof CallFrameworkOptions;\n\n/**\n * What one boundary does with the framework's call parameters.\n *\n * There is no global answer, because the modes differ. A list call feeds a page\n * loop; an item call has no loop to feed; a legacy handler honors nothing the\n * framework added after it was written.\n *\n * This is a fact about the MODE, decided when the boundary is built. It says\n * nothing about the plugin's schema, which is the difference between this and\n * everything {@link parseCallOptions} used to infer.\n */\nexport interface FrameworkOptionsPolicy {\n /** The parameters this boundary reads. Each is also held to\n * {@link CallFrameworkOptionsSchema}, whatever the plugin's schema says. */\n claims: readonly CallFrameworkOptionKey[];\n /** The subset handed to `run` even when the plugin's schema dropped it,\n * because `run` cannot do its job without it. A list `run` is asked for one\n * page, so it gets that page. */\n injects: readonly CallFrameworkOptionKey[];\n}\n\n/** Item mode: no page loop, so the caller's output skip is all it reads. */\nexport const ITEM_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"skipOutputDataValidation\"],\n injects: [],\n};\n\n/** List mode: the page loop plus the caller's output skip. */\nexport const LIST_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"cursor\", \"pageSize\", \"maxItems\", \"skipOutputDataValidation\"],\n injects: [\"cursor\", \"pageSize\"],\n};\n\n/**\n * A legacy paginated handler: the page loop, and nothing else. Nothing in the\n * legacy path honors a caller's output skip, so that key there is whatever the\n * handler's own schema says it is.\n *\n * Everything it claims it also hands over, because the legacy path leaves a\n * handler's input alone. That is what keeps a handler written before any of\n * this working unchanged.\n */\nexport const PAGE_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"cursor\", \"pageSize\", \"maxItems\"],\n injects: [\"cursor\", \"pageSize\", \"maxItems\"],\n};\n\n/** Reads nothing: every key in the call object belongs to the plugin. */\nexport const NO_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [],\n injects: [],\n};\n\n/** A validated call, in the two halves the boundary hands on. */\nexport interface ParsedCallOptions {\n /** The framework's parameters, held to the floor above. */\n framework: CallFrameworkOptions;\n /** The plugin's parse output, or the raw call when it has no schema. */\n domain: unknown;\n /** Framework keys the plugin's schema refused, so the boundary supplies them\n * rather than the plugin's output. */\n supplied: ReadonlySet<string>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The framework keys a strict schema rejected outright, from the issues of a\n * failed parse. Only top-level rejections count: a nested `unrecognized_keys`\n * is a rule about the plugin's own nested object, not about our parameters. */\nfunction strictlyRefused(\n error: z.ZodError,\n claims: readonly string[],\n): string[] {\n const refused = new Set<string>();\n for (const issue of error.issues) {\n if (issue.code !== \"unrecognized_keys\" || issue.path.length > 0) continue;\n for (const key of issue.keys) {\n if (claims.includes(key)) refused.add(key);\n }\n }\n return [...refused];\n}\n\nfunction withoutKeys(\n options: Record<string, unknown>,\n keys: readonly string[],\n): Record<string, unknown> {\n const next: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if (!keys.includes(key)) next[key] = value;\n }\n return next;\n}\n\n/**\n * Validate a call against BOTH schemas, each on its own terms.\n *\n * The framework's parameters are held to {@link CallFrameworkOptionsSchema}\n * whatever the plugin says, so an invalid `pageSize` never reaches a page loop.\n * That runs even with no plugin schema at all, because the floor is the\n * framework's own rule and not something a plugin can opt out of by declaring\n * nothing.\n *\n * The plugin's schema then sees the WHOLE call. That is what keeps a declared\n * constraint alive: an author who writes `pageSize: z.number().max(100)` gets\n * their cap, on top of our floor. Zod strips keys an object schema does not\n * declare, so a plugin that never mentions `cursor` simply drops it and the\n * boundary puts it back.\n *\n * A `strict()` schema is the one shape that cannot ignore what it did not\n * declare. When it rejects our parameters by name, they are removed and the\n * parse runs again, so the plugin still sees exactly the input it meant to\n * describe. The retry is also what makes the ERROR honest: reported as-is, the\n * message would name `cursor` beside the caller's real typo, and a caller would\n * reasonably conclude they may not pass a `cursor` they may in fact pass.\n *\n * Detecting ownership from what the schema DID, rather than from reading its\n * structure, is the point. A wrapper (`.transform()`, `.refine()`) hides an\n * object's shape from any reader, but it cannot hide the parse result.\n */\nexport function parseCallOptions(\n options: unknown,\n {\n schema,\n policy = NO_FRAMEWORK_OPTIONS,\n adaptError,\n }: {\n schema?: z.ZodSchema;\n policy?: FrameworkOptionsPolicy;\n adaptError?: AdaptError;\n } = {},\n): ParsedCallOptions {\n const claims = policy.claims as readonly string[];\n const call = isRecord(options) ? options : undefined;\n\n // The floor, always. A plugin cannot opt out of it by having no schema.\n let framework: CallFrameworkOptions = {};\n if (call && claims.length > 0) {\n const present: Record<string, unknown> = {};\n for (const key of claims) {\n if (key in call) present[key] = call[key];\n }\n framework = parseOrThrow(CallFrameworkOptionsSchema, present, adaptError);\n }\n\n if (!schema) return { framework, domain: options, supplied: new Set() };\n\n const first = schema.safeParse(options);\n if (first.success) {\n // The plugin's schema accepted (or silently dropped) our parameters, so its\n // output is authoritative for everything it kept.\n return { framework, domain: first.data, supplied: new Set() };\n }\n\n const refused = call ? strictlyRefused(first.error, claims) : [];\n if (refused.length === 0) throw toCoreError(first.error, options, adaptError);\n\n const retry = schema.safeParse(withoutKeys(call!, refused));\n if (!retry.success) {\n throw toCoreError(retry.error, options, adaptError);\n }\n return { framework, domain: retry.data, supplied: new Set(refused) };\n}\n\n/**\n * Put the two halves back together for the boundary.\n *\n * The framework's validated value wins for every parameter it claims. A caller\n * who asks for `pageSize: 5` gets 5, whatever the plugin's schema produced for\n * that key, because the framework owns these and the caller's value already\n * passed both gates.\n *\n * Only the keys the caller actually passed are in `framework`, so a plugin's\n * `.default()` still applies to a key the caller omitted. A cap is unaffected\n * too: `z.number().max(100)` REJECTS 500 rather than rewriting it, so the throw\n * happens before this.\n *\n * What this does override is a plugin rewriting a claimed key mid-parse, a\n * transform emitting `pageSize: 999` over the caller's 5. That is the plugin\n * silently answering a question the caller already answered, and the framework\n * is the one that owns the question.\n *\n * Everything claimed comes back, not just what `run` will see. A page loop\n * needs `maxItems`, and an output policy needs the caller's skip, and both read\n * this object before `run` does. What `run` itself sees is decided later, at\n * the innermost core: see {@link withheldFromRun}.\n */\nexport function mergeCallOptions({\n framework,\n domain,\n}: ParsedCallOptions): unknown {\n const claimed = Object.entries(framework);\n if (!isRecord(domain) || claimed.length === 0) return domain;\n return { ...domain, ...Object.fromEntries(claimed) };\n}\n\n/**\n * The framework parameters that must not reach a plugin's `run`: everything\n * this boundary claims, minus what it injects.\n *\n * A fact about the mode alone, with no reading of the plugin's schema. What is\n * left is a value the framework consumes itself, `maxItems` for the page loop\n * and the caller's output skip, and a `run` can act on neither. Several `run`\n * bodies spread their whole input into a delegate or a request, so they would\n * ride along uninvited.\n */\nexport function withheldFromRun(\n policy: FrameworkOptionsPolicy,\n): ReadonlySet<string> {\n return new Set(policy.claims.filter((key) => !policy.injects.includes(key)));\n}\n\n/**\n * Drop those parameters. Runs at the innermost core, INSIDE the middleware\n * fold, so every `wrap` still sees the whole call object, and so does the\n * boundary's hook payload, which sits outside the fold entirely.\n */\nexport function stripFrameworkOnlyOptions(\n options: unknown,\n withheld: ReadonlySet<string>,\n): unknown {\n if (withheld.size === 0 || !isRecord(options)) return options;\n const entries = Object.entries(options);\n if (!entries.some(([key]) => withheld.has(key))) return options;\n return Object.fromEntries(entries.filter(([key]) => !withheld.has(key)));\n}\n\nfunction parseOrThrow<TSchema extends z.ZodSchema>(\n schema: TSchema,\n input: unknown,\n adaptError?: AdaptError,\n): z.infer<TSchema> {\n const result = schema.safeParse(input);\n if (result.success) return result.data;\n throw toCoreError(result.error, input, adaptError);\n}\n\nfunction toCoreError(\n error: z.ZodError,\n input: unknown,\n adaptError?: AdaptError,\n): Error {\n const messages = error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"input\";\n return `${path}: ${issue.message}`;\n });\n return createCoreError(\n {\n code: CoreErrorCode.Validation,\n message: `Validation failed:\\n ${messages.join(\"\\n \")}`,\n details: { zodErrors: error.issues, input },\n },\n adaptError,\n );\n}\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// This package's `browser` field maps it to `false`, so a browser bundler stubs\n// the module rather than failing to resolve it; instantiation then throws here\n// and the context falls back to inert-but-safe (every `run` just calls `fn`,\n// every `get` returns undefined). The catch is the backstop that makes that\n// stubbing survivable, and it 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; additional fields remain available\n * for plugin-specific scoped state.\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// Sync re-entrancy guard for lifecycle observers: while an observer runs, any\n// SDK method it calls must not fire hooks (else observing a call that itself\n// calls a method would recurse: hook -> observer -> method -> hook -> ...).\n// Observers are synchronous fire-and-forget, so a module-level counter is\n// race-free; a method invoked from an observer captures the suppression at\n// call entry, keeping its deferred end-hook paired with its suppressed start.\nlet observerReentrancy = 0;\n\n/** Run a lifecycle observer isolated: defensively (an observer error never\n * breaks the observed call) and with hook firing suppressed for any method\n * the observer itself calls (see the re-entrancy note above). */\nexport function runIsolatedObserver(fn: () => void): void {\n observerReentrancy++;\n try {\n fn();\n } catch {\n // Observers are isolated: a telemetry error must not break the call.\n } finally {\n observerReentrancy--;\n }\n}\n\n/** True while a lifecycle observer is executing (see runIsolatedObserver). */\nexport function isInsideObserver(): boolean {\n return observerReentrancy > 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 * Per-call context threaded explicitly through the method boundary in place of\n * ambient AsyncLocalStorage. It carries call identity, nesting depth, and a\n * per-invocation annotation bag. Because it travels as data, correlation and\n * nested-call dedup work without `async_hooks` — including in browsers, where\n * the old ALS store was inert and nested calls all looked top-level.\n *\n * Framework-neutral: heads surface `callId` under their own name (e.g. a\n * correlation id) and own their annotation field names.\n */\n\n/**\n * A private brand (a fresh `Symbol()`, never `Symbol.for`) makes a CallContext\n * unforgeable: no outside code can name the symbol to synthesize an id-bearing\n * context, and the brand never collides across bundled copies. This is the same\n * unforgeability the `INTERNAL_CALL` sentinel relies on.\n */\nconst CALL_CONTEXT_BRAND: unique symbol = Symbol(\"kitcore.callContext\");\n\n/**\n * The per-invocation annotation bag: an open string-keyed map a head fills with\n * telemetry-shaping fields (via the boundary annotator, a method's pre-run\n * `annotator`, or the run bag's mid-`run` `annotate`) and reads back on the\n * method-lifecycle hook context. Framework-neutral: kitcore does not know or\n * constrain the keys.\n */\nexport type Annotations = Record<string, unknown>;\n\n/**\n * Origin of a call's root. `\"surface\"` = entered through the SDK surface, or a\n * parent-less runtime delegation that still represents real user work;\n * `\"internal\"` = a framework-internal root minted by kitcore's own machinery,\n * which a head can suppress from telemetry.\n */\nexport type CallOrigin = \"surface\" | \"internal\";\n\nexport interface CallContext {\n /**\n * Minted once at the root call; copied verbatim to every nested (child) call.\n * `readonly`: method code owns only the `annotations` bag. A child copies this\n * off the live parent when the delegated call fires, so mutating it mid-run\n * would corrupt the child's correlation id.\n */\n readonly callId: string | null;\n /**\n * 0 at the outermost call; `parent.depth + 1` for a delegated call. `readonly`\n * for the same reason as `callId` — a mutated depth would mis-nest children\n * and, where ALS can't correct it (browsers), duplicate telemetry.\n */\n readonly depth: number;\n /**\n * Per-invocation scratch space. Never forwarded to callees — a child call\n * gets a fresh bag — so annotations describe one method's own invocation.\n * Method `run` code contributes through the run bag's `annotate` function\n * rather than writing here directly; the bag reference is fixed, only its\n * contents change.\n */\n readonly annotations: Annotations;\n /**\n * Origin of the call's root, copied verbatim to every child. `\"surface\"`\n * (the default) marks a surface-origin root — a call that entered through the\n * SDK surface, or a parent-less runtime delegation that still represents real\n * user work (e.g. a delegation proxy reaching another method). `\"internal\"`\n * marks a framework-internal root minted by kitcore's own build-time machinery\n * (resolver/formatter/dispose/observer twins, `resolvePlugin`), which a head\n * can suppress from telemetry. Orthogonal to `depth`: an internal root is\n * still `depth 0`. `readonly` so a child can't inherit a mutated origin.\n */\n readonly callOrigin: CallOrigin;\n readonly [CALL_CONTEXT_BRAND]: true;\n}\n\n/**\n * Strict brand check. A bare value in the boundary's second argument slot — the\n * array index from `items.map(sdk.method)`, say — fails this, so such a call is\n * treated as a root rather than an id-bearing child.\n */\nexport function isCallContext(value: unknown): value is CallContext {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { [CALL_CONTEXT_BRAND]?: unknown })[CALL_CONTEXT_BRAND] === true\n );\n}\n\n/**\n * Mint a call id: prefer `crypto.randomUUID()`, fall back to a v4 UUID built\n * from `crypto.getRandomValues`, and degrade to `null` rather than throwing\n * where neither is available (e.g. a non-secure browser context). The boundary\n * must never throw on id minting, so this is fully guarded.\n */\nfunction generateCallId(): string | null {\n try {\n const webCrypto = (\n globalThis as {\n crypto?: {\n randomUUID?: () => string;\n getRandomValues?: (array: Uint8Array) => Uint8Array;\n };\n }\n ).crypto;\n if (webCrypto?.randomUUID) {\n return webCrypto.randomUUID();\n }\n if (webCrypto?.getRandomValues) {\n const bytes = webCrypto.getRandomValues(new Uint8Array(16));\n const hex = Array.from(bytes, (byte, i) => {\n // Stamp the version (4) and variant (10xx) nibbles per RFC 4122.\n const value =\n i === 6\n ? (byte & 0x0f) | 0x40\n : i === 8\n ? (byte & 0x3f) | 0x80\n : byte;\n return value.toString(16).padStart(2, \"0\");\n });\n return [\n hex.slice(0, 4).join(\"\"),\n hex.slice(4, 6).join(\"\"),\n hex.slice(6, 8).join(\"\"),\n hex.slice(8, 10).join(\"\"),\n hex.slice(10, 16).join(\"\"),\n ].join(\"-\");\n }\n } catch {\n // Fall through to null.\n }\n return null;\n}\n\n/**\n * A fresh root context: a new `callId`, depth 0, and an empty annotation bag.\n * Surface-origin (`callOrigin: \"surface\"`) unless a caller opts into a\n * framework-internal root — only kitcore's own build-time machinery does.\n */\nexport function rootCallContext({\n callOrigin = \"surface\",\n}: { callOrigin?: CallOrigin } = {}): CallContext {\n return {\n callId: generateCallId(),\n depth: 0,\n annotations: {},\n callOrigin,\n [CALL_CONTEXT_BRAND]: true,\n };\n}\n\n/**\n * A child of `parent`: same `callId`, `depth + 1`, and a fresh annotation bag\n * (annotations are per-invocation and never inherited). Origin is inherited, so\n * a delegated subtree carries its root's `callOrigin`.\n */\nexport function childCallContext(parent: CallContext): CallContext {\n return {\n callId: parent.callId,\n depth: parent.depth + 1,\n annotations: {},\n callOrigin: parent.callOrigin,\n [CALL_CONTEXT_BRAND]: true,\n };\n}\n","/**\n * Framework options (`CoreOptions`) and their well-known configuration id.\n * Heads inject the bag under `CORE_OPTIONS_ID` via `createSdk`'s\n * `configuration`; the method boundary resolves it by id at every invocation\n * (`resolveCoreOptions`), and `coreOptionsPluginRef` (model/builtins) is the\n * importable stand-in for plugins that need the same options.\n */\n\nimport type { AdaptError } from \"../types/errors\";\nimport type { FunctionDeprecation } from \"../types/registry\";\nimport type { StabilityLevel } from \"./stability\";\nimport { logDeprecation, logStabilityNotice } from \"./logging\";\n\n/**\n * What the boundary reports when a deprecated method is called: the method\n * plus its declared `deprecation` meta, whole, so future declaration fields\n * ride along without a signature change. `type` makes the record\n * self-describing (the shape a future unified event channel would carry;\n * see docs/design/2026-06-04-unified-event-bus.md).\n */\nexport interface DeprecationWarning {\n type: \"deprecation\";\n methodName: string;\n deprecation: FunctionDeprecation;\n}\n\n/**\n * The default `logDeprecation` handler: format the one-line warning and pass\n * it through kitcore's deduping logger, so the built-in policy is\n * once-per-process per message.\n */\nexport function defaultLogDeprecation({\n methodName,\n deprecation,\n}: DeprecationWarning): void {\n logDeprecation(`${methodName}() is deprecated. ${deprecation.message}`);\n}\n\n/**\n * What the boundary reports when a non-stable (beta / experimental) method\n * is called: the method plus its declared level. `DeprecationWarning`'s\n * sibling — same self-describing shape, same handler-not-observer contract.\n */\nexport interface StabilityNotice {\n type: \"stability\";\n methodName: string;\n stability: StabilityLevel;\n}\n\n// What each non-stable tier's warning must convey. Stable never signals,\n// so it has no entry.\nconst STABILITY_NOTICE_DETAILS: Record<\n Exclude<StabilityLevel, \"stable\">,\n string\n> = {\n beta: \"Its API shape is settled, but it is not yet covered by stable-tier guarantees.\",\n experimental: \"It may change shape or disappear without notice.\",\n};\n\n/**\n * The default `logStabilityNotice` handler: format the one-line warning and\n * pass it through kitcore's deduping logger (once-per-process per message),\n * exactly like {@link defaultLogDeprecation}.\n */\nexport function defaultLogStabilityNotice({\n methodName,\n stability,\n}: StabilityNotice): void {\n if (stability === \"stable\") return;\n logStabilityNotice(\n `${methodName}() is a ${stability} API. ${STABILITY_NOTICE_DETAILS[stability]}`,\n );\n}\n\n/**\n * The well-known id for framework options: heads inject a `CoreOptions` bag\n * under it via `createSdk`'s `configuration` (or register a property plugin),\n * and the method boundary resolves it by id at every invocation, falling back\n * to the legacy `context.core` write while the deprecated `createCorePlugin`\n * path still exists.\n */\nexport const CORE_OPTIONS_ID = \"kitcore/coreOptions\";\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 * The deprecation HANDLER (adaptError's sibling, not an observer): the\n * framework signals every call of a method declaring `deprecation` meta,\n * and this gate decides what happens — policy (how often to tell; the\n * deduping deprecation loggers make once-per-process one line) and\n * presentation. Exactly one: absent falls back to\n * {@link defaultLogDeprecation}, supplied replaces it. Runs isolated, so a\n * throwing handler never breaks the observed call. Additive observation\n * (many subscribers, e.g. telemetry counting hits) is a different concept\n * reserved for an `on*`-named observer when the unified event bus lands.\n */\n logDeprecation?: (warning: DeprecationWarning) => void;\n /**\n * `logDeprecation`'s sibling for API stability: the framework signals\n * every surface call of a method declaring a non-stable `stability`\n * level (beta / experimental), and this gate decides what happens.\n * Exactly one: absent falls back to {@link defaultLogStabilityNotice}\n * (once-per-process per message), supplied replaces it. Runs isolated,\n * so a throwing handler never breaks the observed call. Internal\n * delegation never signals, matching the deprecation contract.\n */\n logStabilityNotice?: (notice: StabilityNotice) => void;\n /**\n * Report what output validation stripped, on the response's\n * `meta.outputDataValidation.droppedPaths`. Off by\n * default: the report is a debugging aid for reconciling a schema against the\n * wire, and a sidecar every caller has to ignore is worse than one a head\n * turns on while it audits its schemas. Off also skips the recursive\n * raw-vs-parsed diff, so the strip costs a parse and nothing more.\n */\n includeOutputValidationDroppedPaths?: boolean;\n}\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 { validateOptions } from \"./validation\";\nimport {\n mergeCallOptions,\n parseCallOptions,\n type FrameworkOptionsPolicy,\n} from \"./call-options\";\nimport {\n getCurrentDepth,\n isInsideObserver,\n runInMethodScope,\n runIsolatedObserver,\n} from \"./method-scope\";\nimport {\n isCallContext,\n rootCallContext,\n type Annotations,\n type CallContext,\n} from \"./call-context\";\nimport type { ComposedAnnotator, MethodHooks } from \"./build-hooks\";\nimport {\n CORE_OPTIONS_ID,\n defaultLogDeprecation,\n defaultLogStabilityNotice,\n type CoreOptions,\n type DeprecationWarning,\n type StabilityNotice,\n} from \"./core-options\";\nimport type { FunctionDeprecation } from \"../types/registry\";\nimport type { StabilityLevel } from \"./stability\";\n\n/**\n * Minimal SDK shape the function wrappers accept. The wrappers only\n * touch `context.hooks` and the resolved core options, but we keep\n * `context` 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 };\ntype PluginsContext = {\n plugins?: Record<\n string,\n { value?: unknown; getValue?: () => unknown } | undefined\n >;\n};\n\n/**\n * Resolve the framework options at invocation time: the module-model value\n * registered (or injected) under `kitcore/coreOptions` wins; the legacy\n * `context.core` write is the fallback while both paths exist. Read live per\n * call, preserving the late-binding contract for framework state.\n */\nexport function resolveCoreOptions(context: unknown): CoreOptions | undefined {\n const entry = (context as PluginsContext).plugins?.[CORE_OPTIONS_ID];\n if (entry) {\n return (entry.getValue ? entry.getValue() : entry.value) as\n | CoreOptions\n | undefined;\n }\n return (context as CoreContext).core;\n}\n\n/**\n * Marks a call as internal delegation (one plugin calling another through its\n * `imports` bag or `resolvePlugin`): materialization's import-facing bindings\n * pass this sentinel in the boundary's second argument slot, and the boundary\n * reads it via `arguments[1]` so its declared signature and arity stay\n * single-parameter. Surface-only concerns (the deprecation signal) fire only\n * when the sentinel is absent — the consumer chose the deprecated surface;\n * a delegating sibling did not. Identity-checked because surface callables\n * leak into arg-forwarding call sites (`items.map(sdk.method)` passes an\n * index here). A private `Symbol()` on purpose: the writer (internal binding)\n * and reader (boundary) are always created together by the same kitcore copy,\n * so it never crosses bundled-copy lines (contrast `CONTEXT`, which other\n * copies read by design and so lives in the global registry) — and\n * `Symbol.for` would make \"internal\" forgeable by any code.\n */\nexport const INTERNAL_CALL: unique symbol = Symbol(\"kitcore.internalCall\");\n\n/**\n * Resolve the per-call context from the boundary's second argument slot. A\n * caller's internal twin passes a child {@link CallContext} there (nested call,\n * inherits the root's `callId`); anything else — the `INTERNAL_CALL` sentinel, a\n * stray `items.map(sdk.method)` index, or nothing — is an outermost call and\n * mints a fresh root. Depth and correlation ride this value instead of ambient\n * ALS, so nesting is tracked correctly even where `async_hooks` is unavailable.\n */\nfunction resolveCallContext(secondArg: unknown): CallContext {\n return isCallContext(secondArg) ? secondArg : rootCallContext();\n}\n\n// A hook annotator may close over an SDK and invoke another method despite not\n// receiving imports. Suppress hook annotation for that nested invocation so it\n// cannot recurse; the nested method's own annotator and lifecycle still run.\nlet hookAnnotatorReentrancy = 0;\n\ninterface ApplyAnnotationsOptions {\n context: CallContext;\n methodName: string;\n input: unknown;\n hookAnnotator?: ComposedAnnotator;\n methodAnnotator?: (input: unknown) => Annotations;\n}\n\n/**\n * Populate the call's annotation bag before `onMethodStart`: composed hook\n * annotators first, then the method's own annotator. Both annotation sources are\n * best-effort and receive raw, pre-validation input. Hook annotators run only\n * for the outermost surface-origin invocation and are suppressed inside\n * observers and during hook-annotator re-entry. The method annotator runs for\n * every invocation so method behavior does not depend on its entry path.\n */\nfunction applyAnnotations({\n context,\n methodName,\n input,\n hookAnnotator,\n methodAnnotator,\n}: ApplyAnnotationsOptions): void {\n if (\n hookAnnotator &&\n !isInsideObserver() &&\n context.depth === 0 &&\n context.callOrigin !== \"internal\" &&\n hookAnnotatorReentrancy === 0\n ) {\n hookAnnotatorReentrancy++;\n try {\n Object.assign(context.annotations, hookAnnotator({ methodName, input }));\n } catch {\n // Annotation inference must never break the call.\n } finally {\n hookAnnotatorReentrancy--;\n }\n }\n try {\n Object.assign(context.annotations, methodAnnotator?.(input));\n } catch {\n // Annotation inference must never break the call.\n }\n}\n\n/**\n * A declared deprecation IS the runtime signal: the boundary reports every\n * SURFACE call of a deprecated method to the head's `logDeprecation` handler\n * (policy + presentation live there; the default dedupes once-per-process\n * through kitcore's logger). Internal delegation (see {@link INTERNAL_CALL})\n * never signals: a user running `curl` must not be warned that `fetch` is\n * deprecated because curl delegates to it. `getDeprecation` is a live read of\n * the method entry's meta, so a deprecation merged after build\n * (`defineMethodOverride`, an `addPlugin`-applied override) still fires. Runs\n * isolated, so a throwing handler never breaks the call and a deprecated\n * method the handler itself calls doesn't recurse.\n */\nfunction signalDeprecation(\n context: unknown,\n methodName: string,\n getDeprecation?: () => FunctionDeprecation | undefined,\n): void {\n if (isInsideObserver()) return;\n const deprecation = getDeprecation?.();\n if (!deprecation?.message) return;\n const warning: DeprecationWarning = {\n type: \"deprecation\",\n methodName,\n deprecation,\n };\n const handler =\n resolveCoreOptions(context)?.logDeprecation ?? defaultLogDeprecation;\n runIsolatedObserver(() => handler(warning));\n}\n\n/**\n * `signalDeprecation`'s sibling for API stability: the boundary reports\n * every SURFACE call of a beta / experimental method to the head's\n * `logStabilityNotice` handler (the default dedupes once-per-process), so a\n * consumer of a bundled build gets told at runtime what the editor and docs\n * badges say at authoring time. Same contract throughout: internal\n * delegation never signals, `getStability` is a live read of the method\n * entry's meta, and the handler runs isolated so a throw never breaks the\n * observed call.\n */\nfunction signalStability(\n context: unknown,\n methodName: string,\n getStability?: () => StabilityLevel | undefined,\n): void {\n if (isInsideObserver()) return;\n const stability = getStability?.();\n if (!stability || stability === \"stable\") return;\n const notice: StabilityNotice = {\n type: \"stability\",\n methodName,\n stability,\n };\n const handler =\n resolveCoreOptions(context)?.logStabilityNotice ??\n defaultLogStabilityNotice;\n runIsolatedObserver(() => handler(notice));\n}\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, context?: CallContext) => Promise<TResult>,\n options: {\n sdk: FunctionSdk;\n schema?: z.ZodSchema<TSchemaOptions>;\n name?: string;\n /** Pre-run per-method annotator (see applyAnnotations): invoked before\n * onMethodStart with the normalized input, its result merged into the\n * call's annotation bag. */\n annotator?: (input: unknown) => Annotations;\n /** Which framework call parameters this callable reads; see\n * `FrameworkOptionsPolicy`. Omitted means none, which is what a legacy\n * handler wants: nothing there honors a framework parameter, so every key\n * in the call object is the handler's own. */\n frameworkOptions?: FrameworkOptionsPolicy;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n) {\n const {\n sdk,\n schema,\n name,\n annotator,\n frameworkOptions,\n getDeprecation,\n getStability,\n } = 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 const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, functionName, getDeprecation);\n signalStability(sdk.context, functionName, getStability);\n }\n return runInMethodScope(async () => {\n const startTime = Date.now();\n const normalizedOptions = (callOptions ?? {}) as TOptions;\n const args: unknown[] = [normalizedOptions];\n // Dedup depth comes from the explicit context — the signal that\n // survives where `async_hooks` is unavailable (browsers). ALS still\n // contributes while it lives, so nested paths that don't yet thread a\n // context stay deduped; that term drops once ALS is retired.\n const depth = Math.max(context.depth, getCurrentDepth());\n // Read live: a plugin contributing hooks or adaptError after\n // this method was constructed should still apply.\n const insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n\n applyAnnotations({\n context,\n methodName: functionName,\n input: normalizedOptions,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n\n // callId and the annotations bag ride every payload for this call; the\n // bag is one shared reference, so mid-`run` writes are visible by\n // onMethodEnd.\n const hookBase = {\n methodName: functionName,\n args,\n isPaginated: false,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n\n hooks?.onMethodStart?.({ ...hookBase });\n\n try {\n // Both schemas run, each on its own terms, and the framework's\n // half wins for anything the plugin's schema refused. See\n // `parseCallOptions`.\n const parsed = parseCallOptions(normalizedOptions, {\n schema,\n policy: frameworkOptions,\n adaptError,\n });\n const result: TResult = await coreFn(\n mergeCallOptions(parsed) as TOptions,\n context,\n );\n\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n });\n\n return result;\n } catch (error) {\n const normalizedError = normalizeError(error, adaptError);\n\n hooks?.onMethodEnd?.({\n ...hookBase,\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 * Wrap a raw method's core with the boundary lifecycle: method scope, live\n * `context.hooks` firing (start/end with `error` on failure), and\n * error-branded input validation via the resolved core options. Unlike\n * `createFunction` there is no envelope and no error normalization on the\n * rethrow path: the ORIGINAL error propagates (raw callers keep error\n * identity, e.g. an `AbortError`), with only the hook payload's `error`\n * coerced for observers. A synchronous core stays synchronous: hooks fire\n * around the call without forcing a promise.\n *\n * `positional` projects the canonical input back onto the caller's argument\n * list for the hook payload, so observers see the call as it was made\n * (`fetch(url, init)`, not one packed object).\n */\nexport function createRawFunction(\n coreFn: (input: unknown, context?: CallContext) => unknown,\n options: {\n sdk: FunctionSdk;\n name: string;\n schema?: z.ZodSchema;\n positional?: readonly string[];\n /** Pre-run per-method annotator (see applyAnnotations). */\n annotator?: (input: unknown) => Annotations;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n): (input: unknown) => unknown {\n const {\n sdk,\n name,\n schema,\n positional,\n annotator,\n getDeprecation,\n getStability,\n } = options;\n // A function expression (not an arrow) so `arguments[1]` can carry the\n // internal-call sentinel (or a child call context) without widening the\n // declared signature.\n return function (rawInput: unknown): unknown {\n const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, name, getDeprecation);\n signalStability(sdk.context, name, getStability);\n }\n return runInMethodScope(() => {\n const startTime = Date.now();\n // Dedup depth comes from the explicit context (the signal that survives\n // where `async_hooks` is unavailable); ALS still contributes until it is\n // retired, so nested paths not yet threading a context stay deduped.\n const depth = Math.max(context.depth, getCurrentDepth());\n const insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n // Validation is the transforming path, so it normalizes a bare call to\n // `{}` before parsing (as `createFunction` always did; a method must\n // never require `fn({})`). The unvalidated path stays genuinely\n // untouched — `skipInputValidation` methods own their input, undefined\n // included.\n const input = schema ? (rawInput ?? {}) : rawInput;\n applyAnnotations({\n context,\n methodName: name,\n input,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n const record = input as Record<string, unknown> | undefined;\n const args: unknown[] = positional\n ? positional\n .filter((key) => record?.[key] !== undefined)\n .map((key) => record?.[key])\n : [input];\n const hookBase = {\n methodName: name,\n args,\n isPaginated: false,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n hooks?.onMethodStart?.({ ...hookBase });\n const fireEnd = (error?: Error): void => {\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n ...(error ? { error } : {}),\n });\n };\n try {\n const parsed = schema\n ? validateOptions(schema, input, { adaptError })\n : input;\n const result = coreFn(parsed, context);\n if (\n result !== null &&\n typeof result === \"object\" &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n return (result as Promise<unknown>).then(\n (value) => {\n fireEnd();\n return value;\n },\n (error: unknown) => {\n fireEnd(\n error instanceof Error ? error : new Error(String(error)),\n );\n throw error;\n },\n );\n }\n fireEnd();\n return result;\n } catch (error) {\n fireEnd(error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n });\n };\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 *\n * `meta` is deliberately NOT allowed even though `SdkPage` declares it: the\n * framework attaches it after this guard, so a page arriving here with `meta`\n * came from a handler or `adaptPage` overstepping the sidecar's owner.\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, context?: CallContext) => Promise<TResponse>,\n {\n sdk,\n adaptPage,\n finalizePage,\n }: {\n sdk: FunctionSdk;\n adaptPage?: (response: TResponse) => SdkPage<TItem>;\n /** Applied to the canonical page after the shape guard, e.g. to validate +\n * strip items and attach `meta.outputDataValidation`. Receives this call's\n * options too, since per-call controls (output validation) ride there and the\n * finalizer itself is built once. */\n finalizePage?: (\n page: SdkPage<TItem>,\n callOptions: unknown,\n ) => 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 callContext?: CallContext,\n ): Promise<SdkPage<TItem>> {\n try {\n const response = await coreFn(options, callContext);\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 finalizePage ? finalizePage(page, options) : page;\n } catch (error) {\n throw normalizeError(\n error,\n resolveCoreOptions(sdk.context)?.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 context?: CallContext,\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 /** Pre-run per-method annotator (see applyAnnotations). */\n annotator?: (input: unknown) => Annotations;\n /** Applied to each canonical page after the shape guard (output validation),\n * with this call's options so it can read per-call controls. */\n finalizePage?: (\n page: SdkPage<TItem>,\n callOptions: unknown,\n ) => SdkPage<TItem>;\n /** Which framework call parameters this callable reads; see\n * `FrameworkOptionsPolicy`. */\n frameworkOptions?: FrameworkOptionsPolicy;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n): (\n options?: TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n },\n) => PaginatedSdkResult<TItem> {\n const {\n sdk,\n schema,\n name,\n defaultPageSize,\n adaptPage,\n annotator,\n finalizePage,\n frameworkOptions,\n getDeprecation,\n getStability,\n } = options;\n const pageFunction = createPageFunction(coreFn, {\n sdk,\n adaptPage,\n finalizePage,\n });\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 const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, functionName, getDeprecation);\n signalStability(sdk.context, functionName, getStability);\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 // Dedup depth comes from the explicit context (the signal that survives\n // where `async_hooks` is unavailable); ALS still contributes until it\n // is retired, so nested paths not yet threading a context stay deduped.\n const depth = Math.max(context.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 insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n\n applyAnnotations({\n context,\n methodName: functionName,\n input: normalizedOptions,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n\n // Shared across onMethodStart and the deferred/sync onMethodEnd sites\n // below, so every payload for this call carries the same callId and the\n // one live annotations bag.\n const hookBase = {\n methodName: functionName,\n args,\n isPaginated: true,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n\n hooks?.onMethodStart?.({ ...hookBase });\n\n // Input validation and first-page kickoff run inside a try so a\n // synchronous throw (a schema-invalid call) still fires onMethodEnd and\n // normalizes the error, rather than escaping between onMethodStart and\n // the deferred end (which observers would see as a started-but-never-\n // ended call). On success the deferred end below is the only one that\n // fires; on a sync throw only this catch fires. The two are mutually\n // exclusive (a throw here means no firstPagePromise exists).\n try {\n // Both schemas run, each on its own terms. See `parseCallOptions`.\n // The page loop reads its controls off the merged object, so the\n // framework's half has to be on it whatever the plugin declared.\n const validatedOptions = mergeCallOptions(\n parseCallOptions(normalizedOptions, {\n schema,\n policy: frameworkOptions,\n adaptError,\n }),\n ) as TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n };\n\n const pageSize = validatedOptions.pageSize ?? defaultPageSize;\n const optimizedOptions = {\n ...validatedOptions,\n pageSize,\n };\n\n // Every page shares this one `context`, so a paginated call keeps a\n // single `callId`/depth across pages. The wrapper closes over it, so\n // pages pulled lazily by the consumer — after this synchronous body\n // (and its method scope) has returned — still carry the context that\n // ambient ALS could not reach.\n const iterator = paginate(\n (pageOptions: Parameters<typeof pageFunction>[0]) =>\n pageFunction(pageOptions, context),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n optimizedOptions as any,\n );\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 once the first page settles. The two-arg\n // `then(onFulfilled, onRejected)` (not `then().catch()`) keeps the\n // rejection handler one hop off `firstPagePromise`, beside the\n // success handler, rather than a hop behind it. Both are registered\n // before the caller awaits the same promise, so onMethodEnd fires\n // before the caller resumes on failure too, matching the\n // non-paginated path. It also makes the two handlers mutually\n // exclusive, so a throw in the success handler can't re-fire the end\n // through a trailing `.catch`.\n if (hooks?.onMethodEnd) {\n firstPagePromise.then(\n () => {\n hooks.onMethodEnd!({\n ...hookBase,\n durationMs: Date.now() - startTime,\n });\n },\n (error) => {\n hooks.onMethodEnd!({\n ...hookBase,\n durationMs: Date.now() - startTime,\n error:\n error instanceof Error ? error : new Error(String(error)),\n });\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 views over ONE page stream: it emits the\n // buffered first page, then the rest of the shared cursor. Bare\n // iteration and `.pages()` hand back this single stream; `.items()`\n // is a view that pulls the same stream and flattens each page.\n // Because the buffered page is emitted by exactly one stream,\n // consuming any view drains the others (the second sees nothing)\n // rather than replaying page 1 over an exhausted cursor (the\n // 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 // `.pages()` is a plain iterable (not a thenable), so unlike the\n // result itself it survives being returned from an async function.\n return Object.assign(firstPagePromise, {\n [Symbol.asyncIterator]() {\n return pageStream;\n },\n pages: function () {\n return {\n [Symbol.asyncIterator]() {\n return pageStream;\n },\n };\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 } catch (error) {\n const normalizedError = normalizeError(error, adaptError);\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n error: normalizedError,\n });\n throw normalizedError;\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 { PAGE_FRAMEWORK_OPTIONS } from \"./call-options\";\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n \"createPluginMethod() is deprecated. Author methods with defineMethod instead.\",\n );\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n 'createPaginatedPluginMethod() is deprecated. Author list methods with defineMethod output \"list\" instead.',\n );\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 // The page loop reads the page controls out of the call object, so a\n // handler's schema does not have to declare them. It reads nothing else:\n // no legacy handler honors the caller's output skip.\n frameworkOptions: PAGE_FRAMEWORK_OPTIONS,\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 */\n/**\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\n */\nexport function createPluginStack<TRequires = object>(): PluginStack<\n TRequires,\n {\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n };\n }\n> {\n logDeprecation(\n \"createPluginStack() is deprecated. Compose with definePlugin and build with createSdk instead.\",\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","/**\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 *\n * `Symbol.for`, not `Symbol()`: heads bundle kitcore (tsup `noExternal`), so\n * an sdk built by one bundle's copy must still be readable by another copy's\n * `getContext` / `resolvePlugin` (e.g. a CLI sdk inspected with helpers\n * imported from `@zapier/zapier-sdk`). The global symbol registry makes every\n * copy agree on the key.\n */\nexport const CONTEXT: unique symbol = Symbol.for(\"kitcore.context\");\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 { CONTEXT } from \"./shared\";\nimport type { Annotations, CallContext } from \"../utils/call-context\";\nimport type { PluginMeta, PluginProvides } from \"../types/plugin\";\nimport type {\n MethodHooks,\n OnMethodStartContext,\n OnMethodEndContext,\n} 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 { StabilityLevel } from \"../utils/stability\";\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 /** Behavioral opt-out that rides on this config for every `defineMethod`\n * overload (all merge `LeafMetaFields`), the partner of `outputSchema`: when\n * true, the materializer skips validating/stripping the output. It is\n * consumed at build time and stored as a first-class plugin field, NOT folded\n * into the projected meta (hence absent from `LEAF_META_KEYS`), so it stays\n * off the registry / CLI / MCP surface, exactly like `skipInputValidation`. */\n skipOutputValidation?: boolean;\n packages?: string[];\n stability?: StabilityLevel;\n /** @deprecated Use `stability: \"experimental\"` instead. */\n experimental?: boolean;\n confirm?: \"create-secret\" | \"delete\";\n deprecation?: FunctionDeprecation;\n aliases?: Record<string, string>;\n supportsJsonOutput?: boolean;\n}\n\n/**\n * The meta an override may patch onto an already-built method.\n *\n * An allow-list, so a field added to {@link LeafMetaFields} later is refused\n * until someone decides it is safe. Naming the dangerous fields instead would\n * hand every future field to overrides by default, and the default has to be\n * the safe one: an override changes how a surface PRESENTS a method, never what\n * runs, what input is accepted, or what safety gate fires. Nothing re-checks\n * the method's declared TypeScript type after `defineMethod` fixes it.\n *\n * What that rule rules out, and why each is dangerous rather than merely\n * unused:\n *\n * - `outputSchema` decides what output validation enforces. Patching it makes\n * a call fail against a contract its own return type says it satisfies.\n * - `confirm` gates a host's confirmation prompt. Patching it can drop the\n * prompt in front of a destructive call.\n * - `type` reaches `confirm` indirectly: the registry derives\n * `confirm: m.confirm ?? (m.type === \"delete\" ? \"delete\" : undefined)`, so\n * moving a method off `\"delete\"` removes the same prompt quietly.\n * - `aliases` maps a parameter to a CLI flag, so patching it changes which\n * input a caller can pass.\n * - `skipOutputValidation` is already unreachable, being absent from\n * `LEAF_META_KEYS` and never folded into the projected meta.\n */\nexport type OverridableMetaFields = Pick<\n LeafMetaFields,\n | \"description\"\n | \"categories\"\n | \"itemType\"\n | \"returnType\"\n | \"packages\"\n | \"experimental\"\n | \"deprecation\"\n | \"supportsJsonOutput\"\n>;\n\n/** One segment of a {@link DynamicMember} path: a literal binding/segment name,\n * or a `{ param }` placeholder for an open-ended key (rendered `{param}`). */\nexport type DynamicMemberSegment = string | { param: string };\n\n/**\n * A templated registry member: a dynamic sub-surface with no static binding\n * (e.g. `apps.{appKey}.{actionType}.{actionKey}`), backed at runtime by a proxy.\n * It is a bodyless declaration — the same descriptive fields an author sets on a\n * leaf, keyed by a `path` instead of a `name`. The framework derives the\n * registry name by joining the path (params rendered `{param}`) and folds these\n * fields into a `PluginMeta` for the registry / CLI / MCP / docs projection.\n * `path[0]` must be a literal that resolves to a real surfaced binding (the\n * owning member).\n */\nexport type DynamicMember = {\n path: readonly DynamicMemberSegment[];\n /** Projection-only input schema (no runtime; the proxy validates its own). */\n inputSchema?: z.ZodType;\n} & LeafMetaFields;\n\n/** A {@link DynamicMember} normalized at define time: the derived registry name,\n * the literal root segment (validated against the surface), and the folded meta. */\nexport interface NormalizedDynamicMember {\n name: string;\n rootBinding: string;\n meta: PluginMeta;\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 \"packages\",\n \"stability\",\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 /** True when the edge came from a `declareOptionalProperty` stand-in: if no real\n * plugin satisfies the id, the binding resolves to `undefined` instead of\n * failing the build as a missing dependency. */\n optional?: boolean;\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 * What `run` sees, given what a CALLER may pass.\n *\n * Subtracts exactly what the runtime strips on the way in, so the type and\n * `stripFrameworkOnlyOptions` cannot drift. The subtraction is unconditional,\n * matching the runtime: a method that DECLARES `maxItems` still does not\n * receive it, because a list `run` fetches one page and the cap spans pages.\n */\nexport type ItemRunInput<TInput> = Omit<TInput, \"skipOutputDataValidation\">;\n\n/** The list twin of {@link ItemRunInput}, plus the page `run` is asked for. */\nexport type ListRunInput<TInput> = Omit<\n TInput,\n \"skipOutputDataValidation\" | \"maxItems\"\n> &\n PageFetchInput;\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 — exactly the dependency's {@link PluginSurface}.\n */\nexport type BindingsOf<TDep extends AnyPlugin> = PluginSurface<TDep>;\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; `callContext` is the live per-call\n * context (call identity plus the annotation bag the boundary reads back on the\n * lifecycle hooks); `annotate` merges mid-run-derived telemetry fields into that\n * bag. Prefer `annotate` over writing `callContext.annotations` directly.\n */\nexport interface MethodRunBag<TImports, TInput, TState = unknown> {\n imports: TImports;\n state: TState;\n input: TInput;\n callContext: CallContext;\n /** Merge mid-run-derived telemetry fields into the call's annotation bag. The\n * declarative pre-run sibling is the method's `annotator` config; both add\n * to the same bag, one during `run`, one before it. */\n annotate: (metadata: Annotations) => void;\n}\n\n/**\n * A method's declarative pre-`run` annotator: given the method's raw,\n * pre-validation `input`, it returns {@link Annotations} the boundary merges\n * into the call's bag before `onMethodStart`. The input is `unknown` because\n * schema coercion/transformation has not run; an annotator must narrow it before\n * reading fields. A provider with nothing to add returns an empty bag, so absence\n * is modelled by no provider rather than an `undefined` return.\n */\nexport type MethodAnnotator = (bag: { input: unknown }) => Annotations;\n\n/**\n * A hook's declarative pre-`run` annotator: like {@link MethodAnnotator} but\n * cross-cutting, so it also receives the `methodName` and the hook's `state`.\n * Many hooks' annotators coexist; the boundary composes them.\n */\nexport type HookAnnotator<TState = unknown> = (bag: {\n methodName: string;\n input: unknown;\n state: TState;\n}) => Annotations;\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/**\n * One entry in `requireParameters`. A bare NAME is looked up in the resolver's\n * own container first, then at the root. That is convenient, and ambiguous when\n * both hold the name: the container wins, silently. An ARRAY is an absolute\n * path from the root (`[\"input\", \"owner\"]`), matching the engine's own path\n * representation, so it says exactly which value is meant, and it also reaches\n * a field inside another parameter that no bare name can name.\n *\n * An index in a path is LITERAL. `[\"filters\", 0, \"operator\"]` names the first\n * item and no other, so it cannot address the array item currently being\n * walked. A requirement inside an array item names its sibling with a bare\n * name, which resolves against the item.\n *\n * A dotted string is NOT a path: the engine looks the whole string up as one\n * key, so `\"input.owner\"` silently never matches. Use the array form.\n */\nexport type ResolverRequirement =\n | string\n // A NON-EMPTY tuple. An empty path names nothing, and the walk resolves a\n // path with `getAtPath`, which traverses zero segments and hands back the\n // resolved root. That object is not `undefined`, so the gate would read the\n // requirement as already satisfied and run the resolver early.\n | readonly [string | number, ...(string | number)[]];\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 /** Parameters that must resolve before this resolver runs (it reads their\n * values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. See {@link ResolverRequirement} for the\n * bare-name vs absolute-path forms. */\n requireParameters?: readonly ResolverRequirement[];\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 (the engine awaits the first page + `nextCursor`), never a\n * bare array. `cursor` is the stateless re-entry hook for \"load more\": the\n * engine awaits one page, carries `nextCursor`, and calls again with `cursor`.\n * Required: a dynamic resolver IS a candidate-lister; a free-text field (with\n * or without auto-resolution someday) is the `static` kind's job. */\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 /** The CURRENT page's items only — the engine windows the listing one\n * page at a time (an accumulating host may be showing more). Rendering\n * input only; validation is the top-level `validate`. */\n items: unknown[];\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n }) => ResolverPromptConfig;\n /** Check a chosen/typed value before the engine accepts it. Async with\n * `imports` so it can verify against the source (`tryResolveFromSearch`'s\n * sibling for picks) — never against a loaded page: pagination means the\n * pick can come from a page the engine no longer holds. Return true to\n * accept or a message to re-ask with. A throw is a lookup failure (the\n * host gets retry/cancel), not a rejection. */\n validate?: (bag: {\n imports: Record<string, unknown>;\n value: unknown;\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n }) => Promise<true | string> | true | string;\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 /** Open-ended entries whose keys aren't known up front (a `z.record`): the\n * walk collects entries in an add/done loop, asking each entry's key (via\n * `keys`, default a free-text string) then its value (via `values`), and\n * assembling them onto the object alongside any fixed `properties`. The\n * JSON-Schema `additionalProperties` analog. */\n additionalKeys?: AdditionalKeys;\n}\n\n/** The open-keyed-entry spec for an {@link ObjectResolver.additionalKeys}. */\nexport interface AdditionalKeys {\n /** Resolver for each entry's key; defaults to a free-text string prompt. A\n * `{ ref }` resolves against the object's `definitions`. */\n keys?: Resolver | ResolverRef;\n /** Resolver for each entry's value. A `{ ref }` resolves against the\n * object's `definitions`. */\n values: Resolver | ResolverRef;\n minEntries?: number;\n maxEntries?: number;\n /** Coarse value types so a free-text key/value answer coerces (usually\n * `\"string\"` for the key), the way `Field.valueType` does. */\n keyValueType?: string;\n valueValueType?: string;\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 * (the engine awaits the first page + `nextCursor`), or a plain page / promise\n * of one. No bare array and no scalar: it behaves like any other list method,\n * 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/** Fields shared by every bound resolver kind. */\ninterface BoundResolverBase {\n /** Parameters that must resolve before this resolver runs (it reads their\n * values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. See {@link ResolverRequirement}. */\n requireParameters?: readonly ResolverRequirement[];\n}\n\n/** Free-text input, no candidate list. */\nexport interface BoundStaticResolver extends BoundResolverBase {\n type: \"static\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n}\n\n/** A fixed value the author pinned; auto-settles, never asks. */\nexport interface BoundConstantResolver extends BoundResolverBase {\n type: \"constant\";\n value: unknown;\n}\n\n/** Display-only text; resolves no value, never asks. */\nexport interface BoundInfoResolver extends BoundResolverBase {\n type: \"info\";\n text: string;\n}\n\n/** List candidate items (`listItems`) and prompt to pick one; carries the\n * auto-resolution hooks (`tryResolveWithoutPrompt`, `tryResolveFromSearch`). */\nexport interface BoundDynamicResolver extends BoundResolverBase {\n type: \"dynamic\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: 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 prompt?: (bag: {\n items: unknown[];\n input: Record<string, unknown>;\n context?: unknown;\n }) => ResolverPromptConfig;\n validate?: (bag: {\n value: unknown;\n input: Record<string, unknown>;\n context?: unknown;\n }) => Promise<true | string> | true | string;\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/** Keyed members: static `properties` (bound) or a `getProperties`-built\n * (unbound) field map; `definitions` holds ref targets. `additionalKeys`\n * carries open-ended entries (a `z.record`). */\nexport interface BoundObjectResolver extends BoundResolverBase {\n type: \"object\";\n properties?: Record<string, BoundField>;\n definitions?: Record<string, BoundResolver>;\n getProperties?: (bag: {\n input: Record<string, unknown>;\n }) => PromiseLike<Record<string, Field>>;\n additionalKeys?: BoundAdditionalKeys;\n}\n\n/** The bound form of {@link AdditionalKeys}: `keys`/`values` are bound (or a\n * `{ ref }` into the object's `definitions`). */\nexport interface BoundAdditionalKeys {\n keys?: BoundResolver | ResolverRef;\n values: BoundResolver | ResolverRef;\n minEntries?: number;\n maxEntries?: number;\n keyValueType?: string;\n valueValueType?: string;\n}\n\n/** A homogeneous list resolved through `items` (bound, or a ref into\n * `definitions`). */\nexport interface BoundArrayResolver extends BoundResolverBase {\n type: \"array\";\n items: BoundResolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n /** The element's coarse value type, used to coerce a free-text item answer\n * before validation (see {@link ArrayResolver.itemValueType}). */\n itemValueType?: string;\n definitions?: Record<string, BoundResolver>;\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). A discriminated union mirroring\n * {@link Resolver}, so kind-specific field access compiles only behind a\n * `type` narrow (the binder's switch is the one exhaustiveness-checked\n * dispatch; the engine's if-chains get the field-access check).\n */\nexport type BoundResolver =\n | BoundStaticResolver\n | BoundConstantResolver\n | BoundInfoResolver\n | BoundDynamicResolver\n | BoundObjectResolver\n | BoundArrayResolver;\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 * What `run` receives, when that differs from what a CALLER may pass.\n *\n * They part company for item and list, whose call type mixes in\n * {@link CallOutputOptions} and {@link PaginatedCallInput}. Those are the\n * framework's, peeled off before `run`, so folding them into one parameter\n * told a consumer reading `Parameters<typeof plugin.run>[0]` that `run` gets\n * a flag the runtime always removes.\n *\n * Defaults to `TInput`, since raw's caller and `run` see the same object.\n */\n TRunInput = TInput,\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 /** True for a `declareOptionalMethod` stand-in: dependents bind `undefined` if\n * no real plugin satisfies it, and `PluginSurface` types the binding\n * `| undefined`. */\n optional?: boolean;\n /** Present on a `declareDefault` wrapper: this entry is the DEFAULT provider\n * for its id (preempted by any explicit provider). Its value is the wrapped\n * plugin, so two defaults for one id dedup (same source) or conflict\n * (different source). */\n defaultSource?: AnyLeafPlugin;\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 /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\n /** Validates `input` before `run` and drives the authoring `input` type. */\n inputSchema?: z.ZodType;\n /** When true, skip the runtime validation/parse of `input`: `run` receives the\n * raw input untouched — no coercion, stripping, or cloning — even if\n * `inputSchema` is set (the schema stays for registry / CLI / MCP projection).\n * For raw methods that own their own validation and must not have their input\n * transformed, e.g. `fetch` passing a `RequestInit` bag through unchanged. */\n skipInputValidation?: boolean;\n /** When true, the materializer skips validating/stripping `run`'s output\n * against `meta.outputSchema` (the schema stays for projection). The output\n * partner of {@link MethodPlugin.skipInputValidation}. */\n skipOutputValidation?: boolean;\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 /** Declarative pre-`run` annotator: the boundary invokes it before\n * `onMethodStart` with the (pre-validation) `input`, and merges its returned\n * `Annotations` into the call's bag. Runs synchronously and receives only\n * `input` — the per-method sibling of the run bag's mid-`run` `annotate`,\n * which is where fields needing imports or async work are written. For\n * telemetry fields knowable before the method's own work; never passed to\n * `run`. */\n annotator?: MethodAnnotator;\n /**\n * Phantom, never present at runtime. `TInput` types the CALL and `TRunInput`\n * types `run`, and once they differ `run` alone cannot tell a reader which is\n * which: an interface is structural, so a parameter that appears nowhere in\n * the body is not inferable. `ExportSurface` recovers the call type from\n * here. Optional and `undefined`-valued, so no implementation writes it.\n */\n readonly __callInput?: TInput;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: (bag: MethodRunBag<any, TRunInput, 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 * Phantom carrier for the CALL input.\n *\n * `TInput` and `TRunInput` differ for item and list, and `run` types the\n * latter. An interface is structural, so a parameter appearing nowhere in the\n * body is not inferable, and without this `ExportSurface` would recover the\n * run input and offer callers the wrong shape. Never present at runtime.\n * @internal\n */\n readonly [CALL_INPUT]?: TInput;\n}\n\n/** Phantom-only key (see `MethodPlugin`); never set at runtime. */\ndeclare const POSITIONAL_NAMES: unique symbol;\n\n/** Phantom-only key (see `MethodPlugin`); never set at runtime. */\ndeclare const CALL_INPUT: 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 * Output controls a method's public caller may pass, the sibling of\n * {@link PaginatedCallInput}: caller-side only, peeled before `run`, and never\n * part of a plugin's declared input, so `run` never sees it.\n *\n * Item and list only, and raw's absence is a decision rather than a gap: raw\n * reserves NOTHING in the caller's call object. That object is entirely the\n * author's, and raw is the mode most likely to forward it verbatim into a\n * request, so a framework key shadowing a domain one there is the worst version\n * of a collision the framework should not create. A `skipOutputDataValidation`\n * passed to a raw method is domain input that happens to share the name: not\n * read, not stripped, and it does not skip.\n *\n * Raw still validates. The author's `skipOutputValidation` field is the only\n * opt-out it honors, which is why that field keeps its name across every mode.\n */\nexport type CallOutputOptions = { skipOutputDataValidation?: boolean };\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/**\n * A response whose only own key is `data`. Gates the item overload of\n * `defineMethod` the way `StrictPage` gates list-standard: `run` returns the\n * `{ data }` envelope itself, and an envelope with extra keys is rejected (a\n * future variant may accept metadata alongside `data`).\n */\nexport type StrictItem<TResponse> = { data: unknown } & {\n [K in Exclude<keyof TResponse, \"data\">]?: never;\n};\n\n/** Data type sourced from an item envelope. */\nexport type DataOf<TResponse> = TResponse extends { data: infer TData }\n ? TData\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 skipInputValidation?: boolean;\n output?: OutputConfig;\n positional?: readonly string[];\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n annotator?: MethodAnnotator;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: any) => unknown;\n dispose?: DisposeFn;\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, state })` computes the value from imports and\n * `setup` state, re-running live on each read. An optional `setup` runs once\n * eagerly at createSdk (dependencies first, like a method's `setup`) to build\n * that state. An imported/surfaced property yields 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 /** True for a `declareOptionalProperty` stand-in: an optional reference. If no real\n * property satisfies it, dependents bind `undefined` rather than the build\n * failing on a missing dependency. */\n optional?: boolean;\n /** Present on a `declareDefault` wrapper: this entry is the DEFAULT provider\n * for its id (preempted by any explicit provider). Its value is the wrapped\n * plugin, so two defaults for one id dedup (same source) or conflict\n * (different source). */\n defaultSource?: AnyLeafPlugin;\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 /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\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: {\n imports: Record<string, unknown>;\n state: unknown;\n callContext?: CallContext;\n }) => TValue;\n /** Descriptive metadata for the registry / CLI / MCP / docs (carry-only). */\n meta?: LeafMeta;\n /** Templated registry members for this property's dynamic sub-surface (e.g. a\n * proxy). Carry-only: normalized at define time, folded into the registry. */\n dynamicMembers?: readonly NormalizedDynamicMember[];\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 state: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * The authoring type for a hook's `wrap`: a map whose keys are the method\n * bindings among the hook's `imports` (you can only wrap a method you import)\n * and whose values are contract-preserving wraps. `next` and `input` take the\n * target's input and the wrap must return the target's output, so a wrap that\n * changes the public signature, or that targets a non-imported / non-method\n * binding, does not compile. `state` is the hook's `setup` result (one bag\n * shape across run/observe/wrap; `next` is the only variant).\n */\nexport type MiddlewareMap<TImports, TState = unknown> = {\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 state: TState;\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 * wrap's `imports` is built from, and how a wrap target\n * binding resolves to a method id. */\n importBindings: readonly ImportBinding[];\n exports: TExports;\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>;\n\n/**\n * A patch over an already-defined method's descriptive fields. It carries no\n * `run`: it names an existing method by id (`target`) and, after that method\n * materializes, merges its `meta` (the same public {@link LeafMetaFields} an\n * author sets on `defineMethod`) onto the method's entry, so the surface\n * registry / CLI / MCP / docs project the patched values. For surface-specific\n * tweaks a base method should not carry (e.g. a CLI that deprecates `fetch`\n * while the SDK does not, or a host that hides a method via `packages`).\n *\n * Distinct from a *replacement* (`addPlugin(..., { override: true })`), which\n * swaps the whole implementation and forces re-declaring `run`. An override\n * inherits the target's implementation untouched and only patches meta.\n */\nexport interface MethodOverridePlugin {\n pluginType: \"method-override\";\n name: string;\n id: string;\n /** The id of the method whose meta is patched (its bare name if the method is\n * namespace-less). */\n target: string;\n imports: readonly AnyPlugin[];\n importBindings: readonly ImportBinding[];\n meta?: LeafMeta;\n}\n\n/**\n * A method-lifecycle hook leaf (`defineHook`). `observe` contributes\n * fire-and-forget observers (`onMethodStart` / `onMethodEnd`) that the method\n * boundary fires around every method; they run defensively (an observer error\n * never breaks the observed call). `setup` runs once and owns the hook's state\n * (e.g. a telemetry queue), delivered to the observers.\n * Each observer bag mirrors a method's: `{ imports, input, state }` — `input` is\n * the lifecycle context, and there is no `next` (observers don't participate in\n * the call). The module-model replacement for a legacy plugin that contributed\n * `context.hooks`.\n */\nexport interface HookPlugin<TName extends string = string> {\n pluginType: \"hook\";\n name: TName;\n namespace?: string;\n id: string;\n imports: readonly AnyPlugin[];\n importBindings: readonly ImportBinding[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: { imports: any }) => unknown;\n /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\n /** Contract-preserving wraps around imported methods (the middleware onion,\n * folded dependents-outermost in topological order). Keyed by the target's\n * binding among this hook's `imports`. */\n wrap?: Record<string, MiddlewareFn>;\n observe?: {\n onMethodStart?: (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n input: OnMethodStartContext;\n state: unknown;\n }) => void;\n onMethodEnd?: (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n input: OnMethodEndContext;\n state: unknown;\n }) => void;\n };\n /** Composable pre-run annotator: returns `Annotations` merged into the call's\n * bag before `onMethodStart`. Coexists with other hooks' annotators. */\n annotator?: HookAnnotator;\n}\n\nexport type AnyPlugin =\n | AnyLeafPlugin\n | AnyAggregatePlugin\n | AnyLegacyPlugin\n | HookPlugin\n | MethodOverridePlugin;\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 hook\n * (whose `imports` the wrap receives, built live at call time). */\nexport interface MiddlewareWrap {\n run: MiddlewareFn;\n owner: HookPlugin;\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 /** The import-facing twin of `value`: the same boundary, called with the\n * internal-call sentinel so surface-only concerns (the deprecation signal)\n * don't fire when a sibling plugin delegates. `buildImports` and\n * `resolvePlugin` bind this; the surface and registry bind `value`. Absent\n * on legacy graph entries (they bind `value`). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n internalValue?: (input: any) => any;\n /** Produce the import-facing twin for a given call context: with a context,\n * the twin mints a fresh child per invocation (callee inherits `callId`, its\n * origin, and sits one level deeper); without one it is parent-less — the\n * surface-origin `internalValue` by default, or a framework-internal root when\n * `frameworkOrigin` is set (kitcore's own build-time passes request it, so\n * their delegated calls can be dropped from telemetry). `buildImports` binds\n * this. Absent on legacy graph entries. */\n bindInternal?: (opts: {\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) => (...args: any[]) => any;\n chain: MiddlewareWrap[];\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n inputSchema?: z.ZodType;\n /** When true, the method owns its input validation and the boundary passes it\n * through unparsed; carried so the controller skips its final `safeParse` too\n * (it still uses `inputSchema` to plan/prompt parameters). */\n skipInputValidation?: boolean;\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 /** Re-derives the value per read. Receives the live per-call `CallContext`\n * when installed on a method's `imports` bag with a threaded context, and\n * nothing on a surface / build-time read. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getValue?: (callContext?: CallContext) => any;\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n meta?: LeafMeta;\n /** Carried from the descriptor: templated registry members for this\n * property's dynamic sub-surface (folded into the registry by getRegistry). */\n dynamicMembers?: readonly NormalizedDynamicMember[];\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 /** Teardown callbacks recorded at materialization, in build order\n * (dependencies first); `disposeSdk` walks them in reverse. */\n disposers?: SdkDisposer[];\n /** The first `disposeSdk` call's settled result; later calls return it\n * (idempotent, first input wins). */\n disposed?: Promise<void>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\n/** One leaf's recorded teardown: built at materialization (closing over the\n * leaf's imports + setup state), run by `disposeSdk`. */\nexport interface SdkDisposer {\n id: string;\n dispose: (input?: unknown) => void | Promise<void>;\n}\n\n/** The teardown callback a leaf declares beside `setup`, releasing what setup\n * acquired. `input` is whatever the caller passed to `disposeSdk` (untyped:\n * the framework does not bless a shape; each dispose narrows what it reads). */\nexport type DisposeFn = (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n state: unknown;\n input?: unknown;\n}) => void | Promise<void>;\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 SDK surface a plugin contributes, derived from its descriptor: a\n * method's callable or a property's value under its name, or an aggregate's\n * export bindings. No `SdkInternals` — this is the plugin's own slice, not a\n * whole SDK. The inference replacement for a hand-written\n * `<Name>PluginProvides` interface:\n *\n * export type ListAppsPluginProvides = PluginSurface<typeof listAppsPlugin>;\n *\n * \"Surface\", not \"Provides\": `PluginProvides` is the legacy function-plugin\n * bag and `ProvidesOf` is the completeness ledger's phantom ids — both\n * different concepts.\n */\nexport type PluginSurface<P extends AnyPlugin> =\n P extends MethodPlugin<\n infer TName,\n infer TInput,\n infer TOutput,\n infer TPositional\n >\n ? P extends { optional: true }\n ? { [K in TName]: SurfaceCall<TInput, TOutput, TPositional> | undefined }\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 : never;\n\n/**\n * The framework-owned access an SDK carries beyond its string surface.\n *\n * Both keys, because the value has both. `[CONTEXT]` is what materialization\n * writes and what `getContext` reads, so declaring it is the type telling the\n * truth. `context` is the legacy string key, kept for back-compat and narrowing\n * away later.\n *\n * The symbol used to be omitted so it would not reach a consumer's emitted\n * declarations. It is exported from the package root, so it is nameable there,\n * and hiding it cost more than it saved: `ControllerSdk` had to check the\n * legacy string key as a stand-in for the real one.\n */\nexport interface SdkContextCarrier {\n readonly [CONTEXT]: SdkContext;\n}\n\nexport type SdkInternals = {\n context: SdkContext;\n} & SdkContextCarrier;\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> = [P] extends [AnyPlugin]\n ? // A model plugin adds its PluginSurface; a kind with no typed surface\n // (hook, method-override, legacy descriptor) resolves to never there and\n // adds nothing. The tuple wrappers keep never from distributing.\n [PluginSurface<P>] extends [never]\n ? Record<never, never>\n : PluginSurface<P>\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/**\n * The id a stand-in declares, carried separately from the requires ledger.\n *\n * `declareProperty` requires its own id, so the ledger alone would do. A\n * `declareOptionalProperty` requires NOTHING, which is the point of it, so its\n * ledger is empty and the id has nowhere else to live. Reading the id off the\n * ledger meant an optional stand-in handed a by-reference provider `never`,\n * and a `never` in that position stopped `CompletenessOf` reporting anything\n * for the whole graph.\n *\n * A carrier of its own keeps the two facts apart: what a stand-in NEEDS, and\n * what it NAMES.\n */\nexport interface StandInId<TId extends string = never> {\n /** @internal */\n readonly [DECLARES]?: TId;\n}\n\n/** Phantom-only key (see `StandInId`); never set at runtime. */\ndeclare const DECLARES: unique symbol;\n\n/** The id a stand-in names (reads the phantom carrier). */\nexport type DeclaredIdOf<P> = P extends { readonly [DECLARES]?: infer R }\n ? Extract<R, string>\n : never;\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/**\n * The runtime-input channel for `createSdk`. `configuration` maps plugin ids to\n * immutable values; each entry materializes as a static value property under\n * that id, satisfying a `declareProperty` / `declareOptionalProperty` stand-in exactly\n * as a registered provider would (DI value injection). Strict at build time:\n * an id must resolve to a property stand-in reachable from the root, so\n * unknown ids, non-property targets, and collisions with a registered real\n * provider all throw. kitcore keeps the map untyped; a head's factory is the\n * typed wrapper (`createMySdk(options)` passes\n * `{ configuration: { \"my/config\": options } }`).\n */\nexport interface CreateSdkOptions {\n configuration?: Record<string, unknown>;\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 {\n OnMethodStartContext,\n OnMethodEndContext,\n} from \"../utils/build-hooks\";\nimport type { CallContext } from \"../utils/call-context\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport type { ResponseMeta } from \"../types/output-validation\";\nimport type {\n FormattedItem,\n PromptConfig,\n ResolverPromptConfig,\n} from \"../utils/schema-utils\";\nimport { logDeprecation } from \"../utils/logging\";\nimport { makeId, parseId } from \"./shared\";\nimport { LEAF_META_KEYS } from \"./types\";\nimport type {\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyMethodPlugin,\n AnyPlugin,\n AggregatePlugin,\n ArrayExports,\n DefineMethodConfig,\n Formatter,\n ImportsInput,\n ExportsInput,\n ImportBinding,\n ImportsOf,\n ItemOf,\n DynamicMember,\n LeafMeta,\n LeafMetaFields,\n OverridableMetaFields,\n MethodOverridePlugin,\n NormalizedDynamicMember,\n HookPlugin,\n HookAnnotator,\n MethodPlugin,\n MethodAnnotator,\n MethodRunBag,\n MiddlewareMap,\n PageFetchInput,\n PaginatedCallInput,\n ItemRunInput,\n ListRunInput,\n CallOutputOptions,\n PropertyPlugin,\n Resolver,\n ResolverRef,\n ResolverRequirement,\n ListItemsResult,\n ResolverType,\n Field,\n DisposeFn,\n DynamicResolver,\n StaticResolver,\n ConstantResolver,\n InfoResolver,\n ObjectResolver,\n AdditionalKeys,\n ArrayResolver,\n StrictItem,\n DataOf,\n StrictPage,\n PluginSummary,\n StandInId,\n StaticList,\n LiteralString,\n IdOf,\n LastSegment,\n LeafSummary,\n LeafRequires,\n LeafProvides,\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, optional?: boolean): 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(optional ? { binding, id, optional } : { 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 if (plugin.pluginType === \"hook\") {\n // A hook contributes behavior, not an importable value: it materializes\n // no `context.plugins` entry, so binding it would break `buildImports`.\n // Keep it in the plugin list only (reachability + topological ordering,\n // e.g. a hook importing another to wrap AROUND it).\n } else {\n // A `declareOptionalProperty` stand-in marks its binding optional so an\n // unsatisfied dependency resolves to `undefined` instead of throwing.\n add(plugin.name, plugin.id, (plugin as { optional?: boolean }).optional);\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/** Render a dynamic-member path to its registry name: literals as-is, params as\n * `{param}`, joined with `.` (e.g. `apps.{appKey}.{actionType}.{actionKey}`). */\nfunction formatDynamicMemberName(\n path: readonly (string | { param: string })[],\n): string {\n return path\n .map((seg) => (typeof seg === \"string\" ? seg : `{${seg.param}}`))\n .join(\".\");\n}\n\n/** Normalize authored dynamic members: derive each registry name, capture the\n * literal root segment (validated against the surface later), and fold the\n * hoisted fields into a `PluginMeta` (with the projection-only `inputSchema`). */\nfunction collectDynamicMembers(\n members: readonly DynamicMember[] | undefined,\n): readonly NormalizedDynamicMember[] | undefined {\n if (!members?.length) return undefined;\n return members.map((member) => {\n const root = member.path[0];\n if (typeof root !== \"string\") {\n throw new Error(\n \"defineProperty: a dynamicMember path must start with a literal \" +\n \"segment (the owning binding), not a { param }.\",\n );\n }\n const leaf = collectLeafMeta(member) ?? {};\n return {\n name: formatDynamicMemberName(member.path),\n rootBinding: root,\n meta: member.inputSchema\n ? { ...leaf, inputSchema: member.inputSchema }\n : leaf,\n };\n });\n}\n\n/**\n * Reject a LIST stand-in from the ref form, at the REF rather than at `run`.\n * Without this the mismatch surfaces as a run-return type error, which sends\n * the reader to the wrong file. The key is the message: a missing required\n * property names itself in the error.\n *\n * A `PaginatedSdkResult` is a decorated thenable the framework builds, so no\n * hand-written `run` returns one. That makes it a fact about the ref, not a\n * guess.\n *\n * ITEM is deliberately absent. An item surface is `Promise<{ data }>`, which is\n * also just an ordinary async method returning an object with a `data` field,\n * and rejecting the second to catch the first turned a valid raw provider into\n * a compile error with advice that did not apply. An item stand-in implemented\n * by reference now fails on the run return instead, which is a worse message\n * for a real mistake but does not refuse correct code.\n */\ntype RefFormRawOnly<TOutput> =\n TOutput extends PaginatedSdkResult<unknown>\n ? {\n \"defineMethod(ref, config) provides raw output only; define a list provider from scratch\": never;\n }\n : unknown;\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 `{ data: T }`, surfaced as `Promise<{ data: T }>`), or `list`\n * (`run` 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 /** Skip the runtime parse of `input`; `run` gets it untouched (the schema\n * stays for projection). For raw methods that validate their own input, like\n * `fetch`. See {@link MethodPlugin.skipInputValidation}. */\n skipInputValidation?: boolean;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n annotator?: MethodAnnotator;\n output?: \"raw\" | { type: \"raw\" };\n positional?: TPositional;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\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 a strict `{ data }` envelope, symmetric with list's\n// strict `SdkPage`; the framework passes it through.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TResponse extends StrictItem<TResponse>,\n TData = DataOf<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 annotator?: MethodAnnotator;\n output: \"item\" | { type: \"item\" };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & CallOutputOptions,\n Promise<{ data: TData; meta?: ResponseMeta }>,\n readonly [],\n ItemRunInput<TInput>\n> &\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 annotator?: MethodAnnotator;\n output:\n | \"list\"\n | { type: \"list\"; adaptPage?: undefined; defaultPageSize?: number };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & PaginatedCallInput & CallOutputOptions,\n PaginatedSdkResult<TItem>,\n readonly [],\n ListRunInput<TInput>\n> &\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 annotator?: MethodAnnotator;\n output: {\n type: \"list\";\n adaptPage: (response: TResponse) => SdkPage<TItem>;\n defaultPageSize?: number;\n };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & PaginatedCallInput & CallOutputOptions,\n PaginatedSdkResult<TItem>,\n readonly [],\n ListRunInput<TInput>\n> &\n LeafSummary<TNamespace, TName, TImports>;\n// ref form (raw output): provide a `declareMethod` stand-in BY REFERENCE. `run`\n// is typed against the declared `TInput` / `TOutput`, and id / name / namespace\n// come from the ref (no string respelled). Raw only, because an item or list\n// stand-in is\n// defined from scratch via the output-moded overloads above, since its `run`\n// return differs from the surfaced output. Mirrors `defineProperty(ref, { value })`.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TOutput,\n const TId extends string,\n const TImports extends ImportsInput = readonly [],\n TState = undefined,\n>(\n ref: MethodPlugin<TName, TInput, TOutput> &\n StandInId<TId> &\n RefFormRawOnly<TOutput>,\n config: {\n imports?: TImports & StaticList<TImports>;\n inputSchema?: z.ZodType<TInput>;\n skipInputValidation?: boolean;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n // NoInfer on both, so the REF states the input and output. Inferred from\n // here too, a provider's own `run` widened them, which let the raw-only\n // guard read a shape the ref never declared.\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, NoInfer<TInput>, TState>,\n ) => NoInfer<TOutput>;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput, TOutput> &\n PluginSummary<LeafRequires<TId, TImports>, LeafProvides<TId, TImports>>;\nexport function defineMethod(\n configOrRef: DefineMethodConfig | MethodPlugin,\n refConfig?: Omit<DefineMethodConfig, \"name\" | \"namespace\">,\n // Only the run slot moves off its default. The item and list overloads narrow\n // `run`'s input away from the call input, and a parameter position is\n // contravariant, so `never` is the one input every overload's `run` accepts.\n): MethodPlugin<string, unknown, unknown, readonly [], never> {\n // Ref form, `defineMethod(ref, { run, … })`: the ONLY difference is where\n // the identity comes from, so borrow it off the stand-in and fall through to\n // the one build below. A second literal here would be a copy to keep in step,\n // and the copy is what silently drops a field the next time one is added.\n const config: DefineMethodConfig =\n refConfig === undefined\n ? (configOrRef as DefineMethodConfig)\n : {\n ...refConfig,\n name: (configOrRef as MethodPlugin).name,\n namespace: (configOrRef as MethodPlugin).namespace,\n };\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 skipInputValidation: config.skipInputValidation,\n skipOutputValidation: config.skipOutputValidation,\n meta: collectLeafMeta(config),\n resolvers: config.resolvers,\n formatter: config.formatter,\n annotator: config.annotator,\n output: config.output,\n positional: config.positional,\n setup: config.setup as MethodPlugin[\"setup\"],\n dispose: config.dispose,\n run: config.run as MethodPlugin[\"run\"],\n };\n}\n\n/** The runtime half of {@link OverridableMetaFields}, since a JavaScript caller\n * never sees the type.\n *\n * An allow-list for the same reason the type is one: a field added to\n * `LeafMetaFields` later must not become patchable because nobody remembered to\n * deny it. Anything off this list changes what runs, what input is accepted, or\n * what safety gate fires, so refusing the call beats dropping the field\n * silently. */\nconst OVERRIDABLE = [\n \"description\",\n \"categories\",\n \"itemType\",\n \"returnType\",\n \"packages\",\n \"experimental\",\n \"deprecation\",\n \"supportsJsonOutput\",\n] as const;\n\nfunction assertOverridable(target: string, fields: object): void {\n const offered = Object.keys(fields).filter(\n (key) => !(OVERRIDABLE as readonly string[]).includes(key),\n );\n if (offered.length === 0) return;\n throw new Error(\n `defineOverride(\"${target}\"): cannot override ${offered.join(\", \")}. ` +\n `An override changes how a surface presents a method, never what it does. ` +\n `The method's declared type is fixed at \\`defineMethod\\` and nothing ` +\n `re-checks it afterwards, so patching behavior here would let a call fail ` +\n `against a contract its own return type says it satisfies. ` +\n `Overridable: ${OVERRIDABLE.join(\", \")}.`,\n );\n}\n\n/** Build the override plugin. Shared by the ref form and the deprecated\n * string-target form, so the two cannot drift on shape or on the guard. */\nfunction buildOverride(\n target: string,\n namespace: string | undefined,\n fields: OverridableMetaFields,\n): MethodOverridePlugin {\n assertOverridable(target, fields);\n return {\n pluginType: \"method-override\",\n name: `override:${target}`,\n id: namespace ? `${namespace}/override:${target}` : `override:${target}`,\n target,\n imports: [],\n importBindings: [],\n meta: collectLeafMeta(fields),\n };\n}\n\n/**\n * Patch how a surface PRESENTS an already-defined method, by reference. Pass\n * the method (or its `declareMethod` stand-in) and any of\n * {@link OverridableMetaFields}. After the SDK materializes, those fields merge\n * onto the target's entry, so the registry / CLI / MCP / docs project the\n * patched values. The target's `run`, resolvers, and declared type are\n * untouched, which is the whole point: see {@link OverridableMetaFields} for\n * the fields that are refused and why.\n *\n * Use it for a tweak one surface wants and the base method should not carry, a\n * CLI deprecating `fetch` while the SDK does not. Include it in an aggregate's\n * `imports` to apply it during `createSdk`, or `addPlugin(sdk, override)` to\n * apply it to a built SDK.\n *\n * Taking the reference rather than an id string is the same choice\n * `defineMethod(ref, ...)` and `defineProperty(ref, ...)` make. No id is\n * respelled, so a rename cannot leave a silent no-op behind, and the name does\n * not restate what the reference already says. `declareMethod` gives you a\n * stand-in when you want to patch a method without importing it.\n *\n * `namespace` names the OVERRIDE, not the target, so two surfaces can each\n * patch the same method in one graph without colliding.\n */\nexport function defineOverride(\n ref: AnyMethodPlugin,\n config: { namespace?: string } & OverridableMetaFields = {},\n): MethodOverridePlugin {\n const { namespace, ...fields } = config;\n return buildOverride(ref.id, namespace, fields);\n}\n\n/**\n * @deprecated Use {@link defineOverride}, which takes the method itself instead\n * of its id spelled out again.\n */\nexport function defineMethodOverride<const TTarget extends string>(\n config: { target: TTarget; namespace?: string } & OverridableMetaFields,\n): MethodOverridePlugin {\n logDeprecation(\n \"defineMethodOverride({ target }) is deprecated. Use defineOverride(method, { ... }), which takes the method or its declareMethod stand-in.\",\n );\n const { target, namespace, ...fields } = config;\n return buildOverride(target, namespace, fields);\n}\n\n/**\n * Refuse an empty absolute path, which the type also rejects.\n *\n * The walk resolves a path with `getAtPath`, which traverses zero segments and\n * hands back the resolved root. That object is not `undefined`, so an empty\n * path reads as already satisfied and the resolver runs before the prerequisite\n * its author meant to declare. Failing open on a gate is worse than not having\n * one, so this refuses rather than ignores.\n *\n * Here as well as in the type, because a JavaScript caller never sees the type.\n */\nfunction assertRequirementPaths(\n requirements: readonly ResolverRequirement[] | undefined,\n): void {\n if (!requirements) return;\n for (const requirement of requirements) {\n if (typeof requirement !== \"string\" && requirement.length === 0) {\n throw new Error(\n \"defineResolver: a requireParameters path must name at least one \" +\n \"segment. An empty path names no parameter, and the engine would \" +\n \"read it as already satisfied.\",\n );\n }\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 ResolverRequirement[];\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. Required: a dynamic resolver IS a candidate-lister;\n * use `type: \"static\"` for a free-text field. */\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 /** Check a chosen/typed value before the engine accepts it. Async with\n * `imports` so it can verify against the source — never against a loaded\n * page (the pick can come from a page the engine no longer holds). Return\n * true to accept or a message to re-ask with; a throw is a lookup failure\n * (retry/cancel), not a rejection. */\n validate?: (bag: {\n imports: ImportsOf<TImports>;\n value: unknown;\n input: TInput;\n /** The value `getContext` returned, if any. */\n context?: TContext;\n }) => Promise<true | string> | true | string;\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 ResolverRequirement[];\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 ResolverRequirement[];\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 ResolverRequirement[];\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 /** Open-ended entries whose keys aren't known up front (a `z.record`). */\n additionalKeys?: AdditionalKeys;\n}): ObjectResolver;\n// array: a homogeneous list resolved through `items`.\nexport function defineResolver(config: {\n type: \"array\";\n requireParameters?: readonly ResolverRequirement[];\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 ResolverRequirement[];\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 additionalKeys?: AdditionalKeys;\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n validate?: (bag: any) => Promise<true | string> | true | string;\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 assertRequirementPaths(config.requireParameters);\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 additionalKeys: config.additionalKeys,\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 validate: config.validate as DynamicResolver[\"validate\"],\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 StandInId<TId> {\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 StandInId<TId>;\n}\n\n/**\n * Declare an OPTIONAL stand-in for a method registered elsewhere: the method twin\n * of `declareOptionalProperty`. Unlike `declareMethod`, an unsatisfied optional\n * reference is NOT a missing dependency; the binding is typed\n * `((input) => output) | undefined`, so the consumer must handle the absent case\n * (`imports.track?.(...)`). Use it to reference a foreign method userland may or\n * may not import, without claiming its slot.\n */\nexport function declareOptionalMethod<\n const TId extends string,\n TInput = unknown,\n TOutput = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): MethodPlugin<LastSegment<TId>, TInput, TOutput> & {\n optional: true;\n} & PluginSummary<never, never> &\n StandInId<TId> {\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 optional: true,\n imports: [],\n importBindings: [],\n run: () => {\n throw new Error(\n `Plugin \"${id}\" is an optional stand-in (declareOptionalMethod) with no ` +\n `implementation. Its binding is \\`undefined\\` unless a real plugin is ` +\n `registered under this id.`,\n );\n },\n // Requires nothing (phantom carrier `<never, never>`): a consumer that\n // imports it still passes `createSdk`'s completeness check unprovided. The\n // `optional: true` literal drives `PluginSurface` to type the binding\n // `| undefined`.\n } as unknown as MethodPlugin<LastSegment<TId>, TInput, TOutput> & {\n optional: true;\n } & PluginSummary<never, never> &\n StandInId<TId>;\n}\n\ntype DefinePropertyConfig = {\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 dispose?: DisposeFn;\n value?: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get?: (bag: any) => unknown;\n dynamicMembers?: readonly DynamicMember[];\n} & LeafMetaFields;\n\n/**\n * Define a property leaf. Either a static `value` or a computed `get`, which\n * re-runs live on each read; an optional `setup` runs once at `createSdk`\n * (dependencies first, like a method's `setup`) to build the state `get` reads.\n * `createSdk`, a dependent's `imports`, or an aggregate's re-export binds it\n * 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 dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n get: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n /** The live per-call context when the property is read from a method's\n * `imports` bag — every method call has one, at any depth. Undefined only\n * where no call is in flight: the property bound onto the SDK object\n * itself, and reads from a `setup`-time imports bag. A context-aware\n * property reads its `callId` off this; because its value is then specific\n * to the reading call, callers must not cache it across calls. */\n callContext?: CallContext;\n }) => TValue;\n /** Templated registry members for this property's dynamic sub-surface (e.g.\n * a proxy): each a bodyless declaration keyed by `path` instead of `name`. */\n dynamicMembers?: readonly DynamicMember[];\n } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> & LeafSummary<TNamespace, TName, TImports>;\n/**\n * Provide a value for a declared property BY REFERENCE: pass the\n * `declareProperty` / `declareOptionalProperty` stand-in instead of respelling\n * its `name` / `namespace`, and `value` is typed against the declaration. The\n * result is a real property that satisfies the stand-in (or overrides its\n * default) by id. The refactor-safe, no-string alternative to matching ids by\n * hand (and the in-graph replacement for `createSdk`'s `configuration` channel).\n */\nexport function defineProperty<\n const TName extends string,\n TValue,\n const TId extends string,\n>(\n ref: PropertyPlugin<TName, TValue> & StandInId<TId>,\n // NoInfer so the REF states the value type. Inferring from both sites let\n // `value: undefined` widen `TValue` until the two agreed, and a consumer\n // reading the declared shape then compiled and crashed.\n config: { value: NoInfer<TValue> } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> & PluginSummary<never, TId>;\nexport function defineProperty(\n config: DefinePropertyConfig | PropertyPlugin,\n refConfig?: { value: unknown } & LeafMetaFields,\n): PropertyPlugin {\n // Ref form, `defineProperty(ref, { value })`: as in `defineMethod`, the only\n // difference is that the identity comes off the stand-in, so borrow it and\n // fall through to the one build below rather than keeping a second literal in\n // step. A value-only config leaves the rest absent, which is what it means.\n const cfg: DefinePropertyConfig =\n refConfig === undefined\n ? (config as DefinePropertyConfig)\n : {\n ...refConfig,\n name: (config as PropertyPlugin).name,\n namespace: (config as PropertyPlugin).namespace,\n };\n const deps = normalizeImports(cfg.imports);\n return {\n pluginType: \"property\",\n name: cfg.name,\n namespace: cfg.namespace,\n id: makeId(cfg.name, cfg.namespace),\n imports: deps.plugins,\n importBindings: deps.bindings,\n setup: cfg.setup as PropertyPlugin[\"setup\"],\n dispose: cfg.dispose,\n value: cfg.value,\n get: cfg.get as PropertyPlugin[\"get\"],\n meta: collectLeafMeta(cfg),\n dynamicMembers: collectDynamicMembers(cfg.dynamicMembers),\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> &\n PluginSummary<TId, never> &\n StandInId<TId> {\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 StandInId<TId>;\n}\n\n/**\n * Declare an OPTIONAL stand-in for a property registered elsewhere. Unlike\n * `declareProperty`, a `declareOptionalProperty` left unsatisfied is NOT a missing\n * dependency: dependents bind `undefined` instead of the build failing. The\n * binding type is therefore `TValue | undefined`, so a consumer must handle the\n * absent case (typically `{ ...DEFAULTS, ...imports.config }`).\n *\n * This lets a plugin own its own defaults and treat a provider as override-only:\n * it builds standalone (no provider registered -> `undefined` -> defaults), and\n * a registered provider layers on top. Used for the SDK's static config\n * (defaults live with each consumer; `createZapierSdk` registers an override)\n * and for framework capabilities a method can run without (e.g. hooks).\n */\nexport function declareOptionalProperty<\n const TId extends string,\n TValue = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): PropertyPlugin<LastSegment<TId>, TValue | undefined> &\n PluginSummary<never, never> &\n StandInId<TId> {\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 optional: true,\n imports: [],\n importBindings: [],\n // Requires nothing (phantom carrier `<never, never>`): a consumer that\n // imports it still passes `createSdk`'s completeness check unprovided. The\n // import binding is still typed `TValue | undefined` from the descriptor.\n } as unknown as PropertyPlugin<LastSegment<TId>, TValue | undefined> &\n PluginSummary<never, never> &\n StandInId<TId>;\n}\n\n/**\n * Declare a DEFAULT provider for a dependency you own: import the capability the\n * given plugin provides, and fall back to that plugin when nothing else provides\n * its id. Kind-agnostic (the plugin supplies id, type, and kind), so no\n * method/property split.\n *\n * A default materializes a real, single node, so it works out of the box and can\n * be wrapped or replaced: an explicit provider of the same id silently preempts\n * it, and two different defaults for one id error only when nothing else provides\n * it. See the Defaults section in the kitcore README for default vs optional\n * reference.\n */\nexport function declareDefault<P extends AnyLeafPlugin>({\n plugin,\n}: {\n plugin: P;\n}): P {\n // `defaultSource` marks this as a default and points at the wrapped plugin, so\n // the materializer can dedup two defaults with the same source and flag two\n // with different sources.\n return { ...plugin, defaultSource: plugin } as P;\n}\n\n/**\n * Define a method-lifecycle hook: a leaf whose `observe` contributes\n * fire-and-forget observers (`onMethodStart` / `onMethodEnd`) the method\n * boundary fires around every method, and whose `wrap` contributes\n * contract-preserving middleware around imported methods. This is how a\n * MODULE plugin provides cross-cutting behavior (the module-model successor\n * to a legacy plugin writing `context.hooks` and to `definePlugin`'s\n * deleted `middleware` map).\n *\n * `setup` runs once and owns the hook's state (e.g. a telemetry queue),\n * delivered to the observers. Each observer's bag\n * mirrors a method's `run` bag minus `next`: `{ imports, input, state }`, where\n * `input` is the lifecycle context (`{ methodName, args, depth, ... }`). The\n * boundary runs observers defensively, so an observer error never breaks the\n * observed call.\n */\nexport function defineHook<\n const TImports extends ImportsInput = readonly [],\n TState = undefined,\n>(config: {\n name: string;\n namespace?: string;\n imports?: TImports & StaticList<TImports>;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n /** Contract-preserving wraps around imported methods, keyed by the target's\n * binding among `imports` (the middleware onion: dependents-outermost in\n * topological order). One bag shape with `run`/`observe`; `next` is the\n * only variant. */\n wrap?: MiddlewareMap<ImportsOf<TImports>, TState>;\n observe?: {\n onMethodStart?: (bag: {\n imports: ImportsOf<TImports>;\n input: OnMethodStartContext;\n state: TState;\n }) => void;\n onMethodEnd?: (bag: {\n imports: ImportsOf<TImports>;\n input: OnMethodEndContext;\n state: TState;\n }) => void;\n };\n /** Cross-cutting pre-run annotation. The boundary composes hook annotators\n * right-additively (a later hook's fields win on collision) ahead of the\n * method's own `annotator`, invokes them best-effort for the outermost\n * surface-origin call only, and merges their returned `Annotations` into the\n * call's bag. Synchronous and import-less; fields needing imports or async\n * work are written mid-`run` via the run bag's `annotate`. Returns a value\n * (unlike `observe`) and never reaches `run`. */\n annotator?: HookAnnotator<TState>;\n}): HookPlugin {\n const deps = normalizeImports(config.imports);\n return {\n pluginType: \"hook\",\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 HookPlugin[\"setup\"],\n dispose: config.dispose as HookPlugin[\"dispose\"],\n wrap: config.wrap as HookPlugin[\"wrap\"],\n observe: config.observe as HookPlugin[\"observe\"],\n annotator: config.annotator as HookPlugin[\"annotator\"],\n };\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 * Function form — the legacy function-plugin identity wrapper: it returns the\n * function unchanged but constrains its return to `PluginProvides` and\n * preserves the narrow inferred shape, so callers derive `*PluginProvides` via\n * `ReturnType<typeof plugin>`. Such a plugin runs through the legacy bridge\n * (`fromFunctionPlugin` / `createPluginStack`), deprecated with it.\n *\n * @deprecated Author plugins with `defineMethod` / `defineProperty` /\n * object-form `definePlugin` instead. This form logs a runtime deprecation and\n * will be removed in a release after the warning ships.\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/**\n * Define a plugin module: an aggregate that re-exports child plugins.\n * `exports` mirrors `imports`: an array where a leaf binds under its own name\n * (`[greet]` binds \"greet\"), a module spreads its bindings, and\n * `selectExports(dep, { hi: \"greet\" })` subsets/renames. It is optional, so an\n * imports-only module can omit it. Re-exporting implies a dependency on the\n * child. To wrap imported methods, export a `defineHook` with `wrap`.\n */\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}): 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 },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): ((sdk: any) => PluginProvides) | AggregatePlugin {\n if (typeof fnOrConfig === \"function\") {\n logDeprecation(\n \"definePlugin(fn) (the function form) is deprecated. Author plugins with defineMethod/defineProperty/definePlugin({ ... }) instead.\",\n );\n return fnOrConfig;\n }\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 // A re-export synthetic (`selectExports` / `omitExports`) is flattened by\n // `normalizeExports` into bare bindings, which drops its own `imports:\n // [source]`. That edge is how `omitExports` keeps an omitted (unbound) leaf\n // materialized + addressable by id, so preserve every exported aggregate's\n // imports as extra reachability edges here (bindings unaffected).\n imports: [...deps.plugins, ...exportedAggregateImports(config.exports)],\n importBindings: deps.bindings,\n exports: normalizeExports(config.exports),\n };\n}\n\n/** The extra graph edges an `exports` array contributes beyond its bare\n * bindings: each exported aggregate's own `imports` (e.g. a `selectExports` /\n * `omitExports` synthetic's `imports: [source]`), so a re-export whose source\n * carries unbound-but-materialized leaves keeps them reachable. */\nfunction exportedAggregateImports(\n exports: ExportsInput | undefined,\n): readonly AnyPlugin[] {\n if (!exports) return [];\n const out: AnyPlugin[] = [];\n for (const element of exports) {\n if (element.pluginType === \"aggregate\") out.push(...element.imports);\n }\n return out;\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\n/**\n * Re-export all of a module's exports EXCEPT the named ones, the denylist\n * complement to {@link selectExports}'s allowlist (think TS `Omit` vs `Pick`).\n * The argument is a list of SOURCE export names to drop (not resulting\n * bindings), so there is no key-semantics ambiguity. An unknown name throws.\n *\n * The omitted leaves stay in the graph (the synthetic aggregate still `imports`\n * the source, so it materializes) and remain addressable by id — they are just\n * not surfaced under a binding. That lets a head replace an export's binding\n * with its own plugin while still depending on the original by id.\n */\nexport function omitExports<\n TExports extends Record<string, AnyLeafPlugin>,\n const TOmit extends readonly (keyof TExports & string)[],\n>(\n source: AggregatePlugin<string, TExports>,\n omit: TOmit,\n): AggregatePlugin<string, Omit<TExports, TOmit[number]>> {\n const omitSet = new Set<string>(omit);\n for (const name of omit) {\n if (!(name in source.exports)) {\n throw new Error(`omitExports: \"${source.id}\" has no export \"${name}\".`);\n }\n }\n const kept: Record<string, AnyLeafPlugin> = {};\n for (const [binding, child] of Object.entries(source.exports)) {\n if (!omitSet.has(binding)) kept[binding] = child;\n }\n return {\n pluginType: \"aggregate\",\n name: makeId(`omit`, source.name, \"aggregate\"),\n id: `${source.id}#omit:${selectSeq++}`,\n imports: [source],\n importBindings: [],\n exports: kept,\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 { logDeprecation } from \"../utils/logging\";\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n \"fromFunctionPlugin() is deprecated. Author plugins with defineMethod/definePlugin instead.\",\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 *\n * @deprecated Build directly with `createSdk(root, { configuration })`\n * instead; it logs a runtime deprecation and will be removed in a release\n * after this warning ships.\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 logDeprecation(\n \"defineLegacyMerge() is deprecated. Build directly with createSdk(root, { configuration }) instead.\",\n );\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 { declareOptionalProperty, defineMethod } from \"./define\";\nimport { getCachedRegistry } from \"./registry-support\";\nimport type { PropertyPlugin, SdkContext } from \"./types\";\nimport { CORE_OPTIONS_ID, type CoreOptions } from \"../utils/core-options\";\n\n/**\n * The optional stand-in for the framework-options bag (`kitcore/coreOptions`).\n * The method boundary resolves the same id internally (for `adaptError`); a\n * plugin that needs the options imports this ref, binding\n * `CoreOptions | undefined` (absent means kitcore's built-in behavior). Heads\n * supply the value via `createSdk`'s `configuration` or a registered property.\n */\nexport const coreOptionsPluginRef = declareOptionalProperty<\n typeof CORE_OPTIONS_ID,\n CoreOptions\n>({ id: CORE_OPTIONS_ID });\n\n/**\n * Escape hatch. A built-in privileged plugin whose value is the live\n * `SdkContext` (the raw plugin graph). Importing it (`imports.context`) lets a\n * body reach internals the model otherwise keeps 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 * use `getRegistryPlugin` for surface introspection, and `resolvePlugin` for\n * out-of-graph access to a binding. Its value is injected at materialization,\n * 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 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. A thin\n * shim over the shared `getCachedRegistry`, the same path the free\n * `getRegistry(sdk)` takes, so a surfaced call and an off-surface call return\n * the identical memoized object. Surfacing is optional, since controllers reach\n * the registry through `getRegistry(sdk)` whether or not a head re-exports this.\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 getCachedRegistry(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, so\n * no adaptation is needed. Non-methods / no resolvers → undefined.\n */\nexport function normalizeResolvers(\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 normalizeResolvers}. 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 * Fold a property entry's templated dynamic members into the registry `meta`\n * map, keyed by each member's derived name (`apps.{appKey}`). These have no\n * static binding; `buildRegistry` still projects them because their root segment\n * resolves to a real member on the surface. Fails loud if that root is not a\n * surfaced binding (a typo'd or dangling path).\n */\nexport function foldDynamicMembers(\n entry: PluginEntry,\n surfaceBindings: ReadonlySet<string>,\n meta: Record<string, PluginMeta>,\n): void {\n if (entry.pluginType !== \"property\" || !entry.dynamicMembers) return;\n for (const member of entry.dynamicMembers) {\n if (!surfaceBindings.has(member.rootBinding)) {\n throw new Error(\n `dynamicMember \"${member.name}\": its root \"${member.rootBinding}\" is ` +\n `not a surfaced member. A dynamic member's path must start with a ` +\n `real binding.`,\n );\n }\n meta[member.name] = member.meta;\n }\n}\n\n/** The per-binding registry inputs projected off the live surface. */\nexport interface SurfaceProjection {\n meta: Record<string, PluginMeta>;\n formatters: Record<string, BoundFormatter>;\n resolvers: Record<string, Record<string, BoundResolver>>;\n positional: Record<string, readonly string[]>;\n skipInputValidation: Record<string, boolean>;\n}\n\n/**\n * Collect the registry projection off the live surface: one meta / formatter /\n * bound-resolver / positional entry per `context.surface` binding (aggregates\n * and non-surfaced internals excluded), plus dynamic-member folding. Shared by\n * the pure module-model `getRegistry` (`buildSurfaceRegistry`) and the legacy\n * bridge's synthesized `getRegistry` (which overlays `context.meta` after).\n * `formatterSdk` is what a legacy formatter adapter captures to call through\n * at render time, so pass it fully built.\n */\nexport function collectSurfaceProjection(\n context: SdkContext,\n formatterSdk: unknown,\n): SurfaceProjection {\n const meta: Record<string, PluginMeta> = {};\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 entries[binding] = entry;\n const m = pluginEntryMeta(entry);\n if (m) meta[binding] = m;\n }\n const surfaceBindings = new Set(Object.keys(context.surface));\n for (const entry of Object.values(entries)) {\n foldDynamicMembers(entry, surfaceBindings, meta);\n }\n const formatters: Record<string, BoundFormatter> = {};\n const resolvers: Record<string, Record<string, BoundResolver>> = {};\n const positional: Record<string, readonly string[]> = {};\n const skipInputValidation: Record<string, boolean> = {};\n for (const [binding, entry] of Object.entries(entries)) {\n const f = normalizeFormatter(entry, formatterSdk);\n if (f) formatters[binding] = f;\n const r = normalizeResolvers(entry);\n if (r) resolvers[binding] = r;\n const p = methodPositional(entry);\n if (p) positional[binding] = p;\n if (entry.pluginType === \"method\" && entry.skipInputValidation)\n skipInputValidation[binding] = true;\n }\n return { meta, formatters, resolvers, positional, skipInputValidation };\n}\n\n/**\n * Where a context keeps its memoized registries, one per package filter.\n *\n * ON THE CONTEXT, not in a module-level `WeakMap`, because a process can hold\n * two physical copies of kitcore. A head bundles one (tsup `noExternal`) while\n * a host can also load `@zapier/kitcore` directly. Both copies recover the same\n * `SdkContext` through `Symbol.for(\"kitcore.context\")`, but a module-level map\n * exists once per copy, so a mutation invalidated through one copy left the\n * other serving a stale registry. Warm both readers, `addPlugin` through one,\n * and the other keeps reporting a surface without the added method.\n *\n * `Symbol.for` for the same reason `CONTEXT` uses it: the two copies have to\n * name the same slot. A symbol key also stays out of `Object.keys`, so it does\n * not join the context's string-keyed surface.\n *\n * The map dies with the context, which dies with the SDK, so this holds nothing\n * longer than the `WeakMap` did.\n *\n * Keyed on the filter, because a filtered read is not a one-off: the MCP server\n * calls `getRegistry({ package: \"mcp\" })` inside its request handlers, so\n * skipping the cache there would rebuild the whole projection per request. The\n * map is bounded by the number of distinct filters a host actually uses, which\n * is one or two.\n */\nconst REGISTRY_CACHE: unique symbol = Symbol.for(\"kitcore.registryCache\");\n\ntype CachingContext = SdkContext & {\n [REGISTRY_CACHE]?: Map<string, RegistryResult>;\n};\n\n/**\n * Freeze the containers before a memoized registry is shared.\n *\n * Every reader holds the same object now, so an in-place `sort` or `splice` on\n * `functions` would reorder the registry for everything else in the process,\n * including the CLI's command generator and MCP's tool list. Before the memo\n * each caller got a private copy and that was harmless, so the hazard is new\n * and worth failing loudly on rather than documenting alone.\n *\n * Every container, including the `functions` array each category carries. The\n * asymmetry is what makes a half-done freeze worse than none: the same sort one\n * level up throws, so an author learns the rule there and gets no warning when\n * they reach for a category's own list.\n *\n * The containers only. Entries are left alone deliberately: they carry zod\n * schemas, and freezing library objects invites breakage for a mutation nobody\n * has a reason to make.\n */\nfunction freezeContainers(registry: RegistryResult): RegistryResult {\n Object.freeze(registry.functions);\n for (const category of registry.categories) {\n Object.freeze(category.functions);\n Object.freeze(category);\n }\n Object.freeze(registry.categories);\n return Object.freeze(registry);\n}\n\n/**\n * The single memoized source of truth behind every registry read. The result is\n * shared by every reader, so it is frozen: see {@link freezeContainers}.\n */\nexport function getCachedRegistry(\n context: SdkContext,\n packageFilter?: string,\n): RegistryResult {\n // `buildRegistry` treats an empty filter as no filter, so both collapse to\n // one key rather than caching the same projection twice.\n const key = packageFilter ?? \"\";\n const caching = context as CachingContext;\n let byFilter = caching[REGISTRY_CACHE];\n if (!byFilter) {\n byFilter = new Map();\n caching[REGISTRY_CACHE] = byFilter;\n }\n let registry = byFilter.get(key);\n if (!registry) {\n registry = freezeContainers(buildSurfaceRegistry(context, packageFilter));\n byFilter.set(key, registry);\n }\n return registry;\n}\n\n/** Drop every memoized registry for a context after its surface mutates\n * (post-seal `addPlugin`), so the next read reflects the change. Clears all\n * filters at once: one added method can appear in any of them.\n *\n * Every kitcore copy in the process reads the same slot, so one call clears the\n * cache for all of them. */\nexport function invalidateRegistryCache(context: SdkContext): void {\n delete (context as CachingContext)[REGISTRY_CACHE];\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 // Resolve a live-getter property to its value so a proxy root (e.g. `apps`)\n // is present for `buildRegistry`'s inclusion filter and its dynamic members\n // survive. Built BEFORE the projection so a legacy formatter adapter\n // captures a complete sdk.\n const surface: Record<string, unknown> = {};\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] =\n entry.pluginType === \"property\" && entry.getValue\n ? entry.getValue()\n : entry.value;\n }\n const projection = collectSurfaceProjection(context, surface);\n // Layer the legacy bridge's registry of record on top, exactly as its own\n // synthesized `getRegistry` does. `context.meta` is written only by the\n // legacy pass, so this is a no-op for a pure module-model SDK, and without it\n // the free `getRegistry(sdk)` and a bridged SDK's surfaced `getRegistry()`\n // return different registries: templated entries like `apps.{appKey}` have no\n // static binding, so the surface projection cannot see them.\n Object.assign(projection.meta, context.meta);\n return buildRegistry({\n sdk: surface,\n ...projection,\n packageFilter,\n });\n}\n","import type { z } from \"zod\";\nimport type { SdkPage } from \"../types/pagination\";\nimport type { OutputDataValidationReport } from \"../types/output-validation\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\n\n/**\n * Output validation: when a method declares an `outputSchema`, the materializer\n * validates and strips `run`'s output against it. An author opts out per method\n * with `skipOutputValidation`, a caller opts out for ONE call with the reserved\n * {@link SKIP_OUTPUT_DATA_VALIDATION} key, and a head opts IN to reporting what the\n * strip removed with the `includeOutputValidationDroppedPaths` core option.\n *\n * Item methods return `{ data }`; the item schema validates `data`. List methods\n * return a page of items; the same item schema validates each item (see the\n * list core in the materializer). Both paths share {@link diffDroppedPaths} and\n * the strip-only assumption below.\n */\n\n/** True for a plain JSON object we recurse into: not an array, not null. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The paths present in `raw` but absent from `parsed`: the keys a strip-parse\n * removed. Behavior matches connectors' `diffDroppedKeys`, so the same stripped\n * response reports the same paths in either ecosystem.\n *\n * Strip-only assumption: a Zod object parse preserves values and only drops\n * unknown keys, so a key missing from `parsed` was stripped. Comparing key\n * PRESENCE rather than values means a field the schema merely re-valued\n * (coercion, `.catch()`, a value-level `.transform()`) keeps its key in both and\n * is correctly not flagged. The accepted edges: a `.default()` that ADDS a key\n * appears only in `parsed`, so it is never mislabeled as dropped, while a\n * key-RENAMING transform could surface the old key as dropped.\n *\n * Paths are relative to `data`, dot-notated for object keys. Keys dropped from\n * array elements collapse under a single `[]` segment and are unioned across\n * elements: `items[].name`, never `items[0].name` / `items[1].name` / … A\n * validated output is overwhelmingly a homogeneous list, so the per-index form\n * is just noise; the tradeoff is that a key dropped from only some elements\n * still surfaces once.\n */\nexport function diffDroppedPaths(\n raw: unknown,\n parsed: unknown,\n prefix = \"\",\n): string[] {\n const paths: string[] = [];\n walkDroppedPaths(raw, parsed, prefix, paths);\n return paths;\n}\n\nfunction walkDroppedPaths(\n raw: unknown,\n parsed: unknown,\n prefix: string,\n out: string[],\n): void {\n if (Array.isArray(raw) && Array.isArray(parsed)) {\n // Collapse every element under one `[]` segment, unioning the dropped keys,\n // so a homogeneous list reports each dropped key once. Bounded by the\n // shorter array so a parse that drops elements never walks past the end of\n // `parsed` and reports its whole tail as dropped.\n const seen = new Set<string>();\n const length = Math.min(raw.length, parsed.length);\n for (let index = 0; index < length; index++) {\n const elementPaths: string[] = [];\n walkDroppedPaths(raw[index], parsed[index], `${prefix}[]`, elementPaths);\n for (const path of elementPaths) {\n if (seen.has(path)) continue;\n seen.add(path);\n out.push(path);\n }\n }\n return;\n }\n\n if (isRecord(raw) && isRecord(parsed)) {\n for (const key of Object.keys(raw)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (!(key in parsed)) {\n // Record the dropped key itself; don't descend into a subtree that no\n // longer exists in `parsed`.\n out.push(path);\n continue;\n }\n walkDroppedPaths(raw[key], parsed[key], path, out);\n }\n return;\n }\n\n // Primitives, or a shape mismatch (object vs array vs primitive): no\n // key-level drop to report here.\n}\n\n/**\n * The reserved call-object key a caller uses to bypass output validation for\n * ONE invocation: a sibling of a tool's `input`, like `cursor` / `pageSize`,\n * never inside it. Named once here so every surface that grows the control later\n * (a CLI flag, an MCP field) spells it the same way.\n *\n * Reserved on item and list only. Raw claims no key in the caller's object; see\n * {@link CallOutputOptions}.\n */\nexport const SKIP_OUTPUT_DATA_VALIDATION = \"skipOutputDataValidation\" as const;\n\n/**\n * Whether this call asked to bypass output validation. A literal `true` only:\n * a control that weakens validation must take nothing looser, so a stray `1` or\n * `\"true\"` arriving from a CLI or a wire means \"don't skip\".\n */\nexport function readSkipOutputDataValidation(options: unknown): boolean {\n return isRecord(options) && options[SKIP_OUTPUT_DATA_VALIDATION] === true;\n}\n\n/** One call's output-validation config: the schema lives in the descriptor's\n * `meta`, the author opt-out is a first-class plugin field, the caller opt-out\n * rides the call object, and the dropped-path report is a head's core option\n * (so it is read per call, not per method). */\nexport interface OutputPolicy {\n outputSchema?: z.ZodSchema;\n skipOutputValidation?: boolean;\n /** This one call asked to skip. Can only ever skip: an author who opted out\n * stays opted out, and a caller can never force validation back on. */\n skippedByCaller?: boolean;\n /** Attach `meta.outputDataValidation.droppedPaths` describing what the strip\n * removed. When false, the diff is never computed. */\n includeOutputValidationDroppedPaths?: boolean;\n /** Names the method in a validation failure, so the message says which one. */\n methodName?: string;\n /** The head's error factory, so an output failure brands like every other\n * framework error instead of escaping as a bare `ZodError`. */\n adaptError?: AdaptError;\n}\n\n/**\n * The schema the framework will parse against, or `undefined` when it will not.\n * An author opt-out wins outright and a caller can only ever subtract, never\n * force validation onto a plugin whose author disabled it.\n *\n * Returns the schema rather than a boolean so that \"we validate\" and \"we have\n * something to validate with\" are one fact the caller narrows on, instead of a\n * boolean plus a non-null assertion on the schema at every use.\n */\nfunction resolveValidatingSchema(\n policy: OutputPolicy,\n): z.ZodSchema | undefined {\n if (policy.skipOutputValidation || policy.skippedByCaller) return undefined;\n return policy.outputSchema;\n}\n\n/**\n * Whether to attach a report with nothing notable in it. A method reports only\n * when the caller's flag CHANGED something. On a plugin\n * the author already opted out of, that flag is a no-op, and saying otherwise\n * would claim a bypass that never happened.\n */\nfunction shouldReport(policy: OutputPolicy): boolean {\n return (\n policy.skippedByCaller === true &&\n policy.outputSchema !== undefined &&\n !policy.skipOutputValidation\n );\n}\n\n/**\n * Parse a value against the output schema, throwing a framework error that says\n * OUTPUT validation and names the method. Zod's own issue text reads \"Invalid\n * input: …\" whatever it validates, so without this framing a response-shape\n * mismatch is indistinguishable from a rejected argument. Mirrors connectors,\n * which wraps the same failure for the same reason, and routes through\n * `createCoreError` so a head's `adaptError` can brand it.\n *\n * `locator` names the position inside the response for a list (`data[3]`), which\n * validates item by item; omitted for an item method's single envelope. `hint`\n * names a likely cause the issue list cannot show on its own.\n *\n * The message names BOTH escapes, because the two audiences cannot use each\n * other's. An author corrects the schema or opts the method out; a caller of a\n * published SDK can do neither, and the per-call bypass is the only thing left\n * to them. That bypass is deliberately undocumented elsewhere: it is a way out\n * of a bad moment, not a feature to reach for, so this failure is where a\n * caller should first hear about it.\n */\nfunction parseOutput(\n schema: z.ZodSchema,\n value: unknown,\n policy: OutputPolicy,\n {\n locator,\n hint,\n callerCanSkip = true,\n }: { locator?: string; hint?: string; callerCanSkip?: boolean } = {},\n): unknown {\n const result = schema.safeParse(value);\n if (result.success) return result.data;\n\n const issues = result.error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"data\";\n return `${path}: ${issue.message}`;\n });\n const subject = policy.methodName ? ` for \"${policy.methodName}\"` : \"\";\n const at = locator ? ` at ${locator}` : \"\";\n\n throw createCoreError(\n {\n code: CoreErrorCode.Validation,\n message:\n `Output validation failed${subject}${at}:\\n ${issues.join(\"\\n \")}\\n\\n` +\n (hint ? `${hint}\\n\\n` : \"\") +\n `The response does not match the method's \\`outputSchema\\`. Correct the ` +\n `schema, or set \\`skipOutputValidation: true\\` on the method to pass the ` +\n `response through unvalidated.` +\n (callerCanSkip\n ? ` A caller who cannot change the method can pass ` +\n `\\`skipOutputDataValidation: true\\` with the input to bypass this one call.`\n : ``),\n details: { zodErrors: result.error.issues, output: value },\n },\n policy.adaptError,\n );\n}\n\n/**\n * Validate + strip an item method's `{ data }` envelope against its\n * `outputSchema`, returning the validated envelope. With\n * `includeOutputValidationDroppedPaths`, stripped paths land in\n * `meta.outputDataValidation.droppedPaths` (additive: existing `meta` is preserved).\n * Parsing is a no-op when there is no `outputSchema`, when the author opted out,\n * when this call opted out, or when the result is not a `{ data }` envelope.\n */\nexport function applyItemOutputPolicy(\n result: unknown,\n policy: OutputPolicy,\n): unknown {\n const schema = resolveValidatingSchema(policy);\n const report = shouldReport(policy);\n if (!schema && !report) return result;\n if (!isRecord(result) || !(\"data\" in result)) return result;\n\n if (!schema) {\n return {\n ...result,\n meta: withOutputValidation(result.meta, { skipped: true }),\n };\n }\n\n const data = parseOutput(schema, result.data, policy);\n const validation = buildValidatedReport({\n policy,\n before: result.data,\n after: data,\n });\n const next: Record<string, unknown> = { ...result, data };\n if (validation) next.meta = withOutputValidation(result.meta, validation);\n return next;\n}\n\n/**\n * Validate a raw method's whole return against its `outputSchema`, handing back\n * the ORIGINAL value untouched.\n *\n * Raw has no envelope, so the payload the schema describes IS the return value.\n * That keeps `outputSchema` meaning one thing in every mode (the payload: the\n * whole return here, `data` for an item, each element for a list) instead of\n * being silently inert in one of them. It also makes a forgotten `output:\n * \"item\"` announce itself, since a returned `{ data }` envelope cannot match a\n * schema describing what is inside it.\n *\n * Check, never replace. Raw's contract is that the framework does not shape the\n * result, and `parse` returns a stripped clone, which would swap out the\n * caller's object and break a method handing back a live one. So extras\n * survive, and there are no dropped paths to report, which raw could not report\n * anyway, having no `meta` to carry.\n *\n * One exception, in the caller: a raw method returning a PROMISE gets a new\n * promise, because the check has to await the value before it can parse it. So\n * a decorated thenable loses its decoration, a `PaginatedSdkResult` losing\n * `pages()`. The schema is not what costs it: `createRawFunction` re-wraps any\n * thenable result to fire `onMethodEnd`, so the decoration is already gone.\n * Nothing in this repo returns one from a raw method.\n */\nexport function applyRawOutputPolicy(\n result: unknown,\n policy: OutputPolicy,\n): unknown {\n const schema = resolveValidatingSchema(policy);\n if (!schema) return result;\n // Catching the mistake is not the same as explaining it. A method that meant\n // to be an item reports \"data: expected string, received undefined\" and\n // nothing points at the missing output mode, so say it where we can see it.\n const looksLikeEnvelope = isRecord(result) && \"data\" in result;\n // The parsed value is deliberately discarded: this is the check, not the\n // shaping.\n parseOutput(schema, result, policy, {\n hint: looksLikeEnvelope\n ? 'This returned a `{ data }` envelope, and with no `output` mode the schema is matched against the WHOLE return. Did you mean `output: \"item\"` (or `\"list\"`)?'\n : undefined,\n // Raw reserves nothing in the caller's call object, so there is no per-call\n // skip to point at. Offering one would be advice that does nothing.\n callerCanSkip: false,\n });\n return result;\n}\n\n/**\n * Merge a report into an existing (possibly absent) meta, under the current key\n * and the deprecated one.\n *\n * `outputValidation` shipped in 0.12.0 and is written for one more release, so\n * a consumer reading it does not silently start seeing `undefined`. It keeps\n * its old emission rule exactly: present only when the strip actually removed\n * something, never on a skip, which the old code could not report at all.\n */\nfunction withOutputValidation(\n existing: unknown,\n outputDataValidation: OutputDataValidationReport,\n): Record<string, unknown> {\n const base = isRecord(existing) ? existing : {};\n const deprecated =\n outputDataValidation.skipped === false && outputDataValidation.droppedPaths\n ? {\n outputValidation: { droppedPaths: outputDataValidation.droppedPaths },\n }\n : {};\n return { ...base, outputDataValidation, ...deprecated };\n}\n\n/**\n * The report to attach after a successful parse, or `undefined` when there is\n * nothing worth saying.\n *\n * Item mode and list mode share this so that the two cannot describe the same\n * outcome differently, and so the rule that the diff is never computed unless\n * the head asked for it has one home rather than two.\n */\nfunction buildValidatedReport({\n policy,\n before,\n after,\n}: {\n policy: OutputPolicy;\n before: unknown;\n after: unknown;\n}): OutputDataValidationReport | undefined {\n // Gated on the head's option alone, which keeps that option's promise that\n // off means no diff is computed.\n const droppedPaths = policy.includeOutputValidationDroppedPaths\n ? diffDroppedPaths(before, after)\n : [];\n // Reached only after a real parse, so a caller's skip is already ruled out\n // and dropped paths are the only thing left worth reporting. That is why\n // there is no `{ skipped: false, droppedPaths: null }` branch here: see\n // {@link OutputDataValidationReport} for why the type carries that arm.\n if (droppedPaths.length === 0) return undefined;\n return {\n skipped: false,\n droppedPaths,\n instruction:\n \"Some fields were removed from `data` by output validation. To receive \" +\n `the raw, unvalidated result instead, set \\`${SKIP_OUTPUT_DATA_VALIDATION}\\`.`,\n };\n}\n\n/**\n * Validate + strip each item of a list page against the item `outputSchema`,\n * returning a new page. With `includeOutputValidationDroppedPaths`, paths\n * stripped from any item land in `page.meta.outputDataValidation.droppedPaths`, set\n * only when something was dropped. Parsing is a no-op when there is no\n * `outputSchema`, when the author opted out, or when this call opted out. This\n * is item mode's sibling: the item schema describes one element, so the whole\n * list conforms element by element.\n *\n * A page's `data` IS the array, so its paths carry the `[]` element segment and\n * are unioned across items (`[].secret`, once, however many items dropped it).\n * That is the same collapse {@link diffDroppedPaths} applies to an array nested\n * inside an item.\n */\nexport function applyListOutputPolicy<T>(\n page: SdkPage<T>,\n policy: OutputPolicy,\n): SdkPage<T> {\n const schema = resolveValidatingSchema(policy);\n const report = shouldReport(policy);\n if (!schema && !report) return page;\n\n if (!schema) {\n return {\n ...page,\n meta: withOutputValidation(page.meta, { skipped: true }),\n };\n }\n\n const data = page.data.map(\n (item, index) =>\n parseOutput(schema, item, policy, { locator: `data[${index}]` }) as T,\n );\n // The arrays go in whole: the array branch of the walk is what collapses\n // elements under `[]` and unions the keys across them.\n const validation = buildValidatedReport({\n policy,\n before: page.data,\n after: data,\n });\n const next: SdkPage<T> = { ...page, data };\n if (validation)\n next.meta = withOutputValidation(\n page.meta,\n validation,\n ) as SdkPage<T>[\"meta\"];\n return next;\n}\n","import { buildHooks } from \"../utils/build-hooks\";\nimport type { MethodHooks } from \"../utils/build-hooks\";\nimport {\n applyPluginToSdk,\n checkRootKeyCollisions,\n splitPluginContribution,\n} from \"../utils/plugin-utils\";\nimport {\n createFunction,\n createPaginatedFunction,\n createRawFunction,\n INTERNAL_CALL,\n resolveCoreOptions,\n} from \"../utils/function-utils\";\nimport {\n childCallContext,\n rootCallContext,\n type Annotations,\n type CallContext,\n} from \"../utils/call-context\";\nimport {\n applyItemOutputPolicy,\n applyListOutputPolicy,\n applyRawOutputPolicy,\n readSkipOutputDataValidation,\n type OutputPolicy,\n} from \"../utils/output-policy\";\nimport {\n stripFrameworkOnlyOptions,\n withheldFromRun,\n ITEM_FRAMEWORK_OPTIONS,\n LIST_FRAMEWORK_OPTIONS,\n} from \"../utils/call-options\";\nimport type { RegistryResult } from \"../registry\";\nimport type { PluginMeta, Plugin, PluginProvides } from \"../types/plugin\";\nimport { legacyGraphEntry } from \"./legacy\";\nimport { CONTEXT, parseId } from \"./shared\";\nimport { CORE_OPTIONS_ID } from \"../utils/core-options\";\nimport { normalizeStability } from \"../utils/stability\";\nimport { runIsolatedObserver } from \"../utils/method-scope\";\n\nimport { getCachedRegistry, invalidateRegistryCache } from \"./registry-support\";\nimport type {\n AddedSurface,\n AggregateEntry,\n AggregatePlugin,\n AggregateSdkOf,\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyMethodPlugin,\n AnyPropertyPlugin,\n AnyPlugin,\n BoundAdditionalKeys,\n BoundField,\n BoundFormatter,\n BoundResolver,\n CompletenessOf,\n CreateSdkOptions,\n DisposeFn,\n Field,\n Formatter,\n ImportBinding,\n ResolverRef,\n MethodSdkOf,\n PropertySdkOf,\n LegacyMergePlugin,\n LegacyPlugin,\n MethodEntry,\n MethodOverridePlugin,\n NormalizedOutput,\n Resolver,\n OutputConfig,\n PluginEntry,\n PropertyEntry,\n ExportSurface,\n SdkContext,\n SdkInternals,\n} from \"./types\";\n\n/** Configuration ids the framework itself consumes (the boundary resolves\n * them internally), so injection never requires a declaring plugin. */\nconst FRAMEWORK_CONFIGURATION_IDS: ReadonlySet<string> = new Set([\n CORE_OPTIONS_ID,\n]);\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\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// The context key lives in `shared` so `types` can name it without importing\n// this module. Re-exported here because that is where consumers reach it.\nexport { CONTEXT } from \"./shared\";\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/**\n * A property that declares `dynamicMembers` must have a value from the moment\n * the SDK is built.\n *\n * The registry decides whether to report `apps.{appKey}` by asking whether\n * `sdk.apps` is a live object, which is the right question: nothing under a\n * null root is callable. But the answer is memoized, and only `addPlugin`\n * drops that memo, because only `addPlugin` changes the surface. A property\n * whose value arrives later is not a surface change, so a read taken during\n * that window is the answer every later read gets.\n *\n * Rather than caching a moving answer or advertising members a caller cannot\n * invoke, the combination is unsupported and says so here. Build the root in\n * `setup` and return it from `get`, which is what a proxy root already does.\n *\n * Checked at BUILD, not at read. A read-time throw would fire inside the very\n * window this rules out, which is the wrong place to learn the rule.\n */\nfunction assertDynamicMemberRoot(entry: PropertyEntry): void {\n if (!entry.dynamicMembers?.length) return;\n const value = entry.getValue ? entry.getValue() : entry.value;\n if (typeof value === \"object\" && value !== null) return;\n throw new Error(\n `Property \"${entry.name}\" declares dynamicMembers, so its value must be an ` +\n `object when the SDK is built; got ${value === null ? \"null\" : typeof value}. ` +\n `Build the root in \\`setup\\` and return it from \\`get\\`, so members like ` +\n `\"${entry.dynamicMembers[0].name}\" are reportable from the first registry read.`,\n );\n}\n\n/**\n * Read an SDK's registry from outside its surface, so a head need not re-export\n * `getRegistryPlugin` for a controller to introspect it. Module-model SDKs go\n * through the shared, memoized {@link getCachedRegistry} (context-keyed, so this\n * and a surfaced `getRegistry()` return the same object). A pure-legacy\n * stack-built SDK has no `[CONTEXT]` graph; for those the only path is a\n * surfaced `getRegistry()`, so fall back to it when present. Each package\n * filter is memoized separately.\n */\nexport function getRegistry(\n sdk: unknown,\n packageFilter?: string,\n): RegistryResult {\n // Guard before the property read: `createController` accepts any object, so a\n // nullish sdk reaches here and would otherwise throw a bare TypeError about a\n // symbol nobody outside kitcore has heard of.\n // A callable counts: an SDK can be a function with methods hung off it, and\n // it may carry a context or a surfaced accessor like any other.\n if ((typeof sdk !== \"object\" && typeof sdk !== \"function\") || sdk === null)\n throw createNoRegistryError();\n const context = getContext(sdk);\n // A context with a surface map is the registry source, empty map included: an\n // imports-only root legitimately surfaces nothing, and its registry is empty\n // rather than unavailable. Legacy-bridged SDKs record their root keys here\n // too, so they read the same way. Only something with no surface at all (a\n // stack-built SDK, or a test double exposing plugins off-context) falls\n // through to a surfaced `getRegistry()`.\n if (context?.surface) return getCachedRegistry(context, packageFilter);\n const surfaced = (sdk as { getRegistry?: unknown }).getRegistry;\n if (typeof surfaced === \"function\") {\n return surfaced.call(\n sdk,\n packageFilter ? { package: packageFilter } : undefined,\n ) as RegistryResult;\n }\n throw createNoRegistryError();\n}\n\nfunction createNoRegistryError(): Error {\n return new Error(\n \"getRegistry: sdk has no kitcore context and no surfaced getRegistry().\",\n );\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 const ak = resolver.additionalKeys;\n if (ak) {\n if (!isResolverRef(ak.values)) out.push(ak.values);\n if (ak.keys && !isResolverRef(ak.keys)) out.push(ak.keys);\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/** True for a `declareDefault` wrapper: a real plugin marked as the DEFAULT\n * provider for its id, preempted by any explicit provider of the same id. */\nfunction isDefault(plugin: AnyPlugin): boolean {\n return (\n (plugin.pluginType === \"method\" || plugin.pluginType === \"property\") &&\n (plugin as { defaultSource?: unknown }).defaultSource !== undefined\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 *\n * `configuration` entries substitute BEFORE the missing-dependency check, so an\n * injected value satisfies a required stand-in the same way a registered\n * provider would (see {@link CreateSdkOptions}).\n */\nfunction collectPlugins(\n root: AnyPlugin,\n materialized: ReadonlySet<string> = new Set(),\n configuration?: Record<string, unknown>,\n): Map<string, AnyPlugin> {\n // Resolution rank: an explicit provider (2) beats a `declareDefault` provider\n // (1) beats a stand-in (0). Higher rank wins; two explicit is a duplicate.\n const rank = (plugin: AnyPlugin): number =>\n isStandIn(plugin) ? 0 : isDefault(plugin) ? 1 : 2;\n\n // Phase 1: collect every candidate reachable from the root, IGNORING\n // preemption, so both a default and the explicit provider that preempts it\n // are seen. An id already in the live graph (incremental addPlugin) is a\n // boundary: it is materialized, so it satisfies a stand-in and is not\n // re-collected.\n const allNodes: AnyPlugin[] = [];\n const seen = new Set<AnyPlugin>();\n const collect = (plugin: AnyPlugin): void => {\n if (materialized.has(plugin.id) || seen.has(plugin)) return;\n seen.add(plugin);\n allNodes.push(plugin);\n for (const edge of edgesOf(plugin)) collect(edge);\n };\n collect(root);\n\n const childrenOf = new Map<AnyPlugin, AnyPlugin[]>();\n const candidatesById = new Map<string, AnyPlugin[]>();\n for (const node of allNodes) {\n childrenOf.set(\n node,\n edgesOf(node).filter((edge) => seen.has(edge)),\n );\n const candidates = candidatesById.get(node.id);\n if (candidates) candidates.push(node);\n else candidatesById.set(node.id, [node]);\n }\n\n // Phase 2: prune to the live set by greatest fixpoint. A node stays live\n // unless it is unreachable through live winners, or a strictly higher-rank\n // candidate for its id is reachable (preemption). Both rules only shrink\n // `live`, so this converges. Resolving preemption BEFORE committing a subtree\n // is what drops a preempted default's private dependencies: once a default\n // loses its id, the deps only it reached become unreachable and fall out too.\n // A dependency shared with a still-live plugin stays reachable by that path.\n const live = new Set<AnyPlugin>(allNodes);\n for (;;) {\n // Reachability through live winners: descend only through live nodes.\n const reachable = new Set<AnyPlugin>();\n if (live.has(root)) reachable.add(root);\n const queue: AnyPlugin[] = reachable.has(root) ? [root] : [];\n while (queue.length) {\n const node = queue.pop() as AnyPlugin;\n for (const child of childrenOf.get(node) ?? []) {\n if (reachable.has(child)) continue;\n reachable.add(child);\n // Only descend past a node that is itself a live winner.\n if (live.has(child)) queue.push(child);\n }\n }\n let changed = false;\n for (const node of live) {\n if (!reachable.has(node)) {\n live.delete(node);\n changed = true;\n }\n }\n // Preemption: within an id, a strictly higher-rank live candidate drops the\n // lower-rank ones.\n for (const candidates of candidatesById.values()) {\n let maxRank = -1;\n for (const candidate of candidates) {\n if (live.has(candidate)) maxRank = Math.max(maxRank, rank(candidate));\n }\n if (maxRank < 0) continue;\n for (const candidate of candidates) {\n if (live.has(candidate) && rank(candidate) < maxRank) {\n live.delete(candidate);\n changed = true;\n }\n }\n }\n if (!changed) break;\n }\n\n // Build the id -> winner map from the live set. Remaining live candidates for\n // an id all share the max rank (lower ranks were preempted), so any tie is a\n // same-rank clash: two explicit is a duplicate; two defaults dedup by source\n // or conflict; multiple stand-ins are just repeated references.\n const byId = new Map<string, AnyPlugin>();\n // Ids where two DIFFERENT defaults collided. Fatal only if a default is still\n // the winner at the end (an explicit provider or configuration settles it).\n const conflictedDefaults = new Set<string>();\n const isOptional = (plugin: AnyPlugin): boolean =>\n \"optional\" in plugin &&\n (plugin as { optional?: boolean }).optional === true;\n for (const [id, candidates] of candidatesById) {\n const liveCandidates = candidates.filter((candidate) =>\n live.has(candidate),\n );\n // Prefer a required (non-optional) candidate: a required reference must win\n // the \"is this satisfied?\" question, so an unprovided id fails regardless of\n // import order. Real providers (rank > 0) are never optional, so this only\n // settles ties among stand-ins.\n const winner =\n liveCandidates.find((candidate) => !isOptional(candidate)) ??\n liveCandidates[0];\n if (!winner) continue;\n if (liveCandidates.length > 1) {\n const winnerRank = rank(winner);\n if (winnerRank === 2) {\n throw new Error(\n `createSdk: duplicate plugin id \"${id}\". Two different ` +\n `plugins registered under the same id.`,\n );\n }\n if (winnerRank === 1) {\n const sources = new Set(\n liveCandidates.map(\n (candidate) =>\n (candidate as { defaultSource?: unknown }).defaultSource,\n ),\n );\n if (sources.size > 1) conflictedDefaults.add(id);\n }\n }\n byId.set(id, winner);\n }\n\n if (configuration) {\n for (const [id, value] of Object.entries(configuration)) {\n const existing = byId.get(id);\n if (!existing) {\n // A framework-consumed id (the method boundary resolves it internally,\n // no plugin declares it) is always known: synthesize the value\n // property directly.\n if (FRAMEWORK_CONFIGURATION_IDS.has(id)) {\n const { name, namespace } = parseId(id);\n byId.set(id, {\n pluginType: \"property\",\n name,\n namespace,\n id,\n imports: [],\n importBindings: [],\n value,\n });\n continue;\n }\n throw new Error(\n `createSdk: configuration id \"${id}\" matches no plugin in the ` +\n `graph. An injected value must satisfy a property stand-in ` +\n `reachable from the root.`,\n );\n }\n if (existing.pluginType !== \"property\") {\n throw new Error(\n `createSdk: configuration id \"${id}\" resolves to a ` +\n `\"${existing.pluginType}\" plugin; only property values can be ` +\n `injected.`,\n );\n }\n if (!isStandIn(existing)) {\n throw new Error(\n `createSdk: configuration id \"${id}\" collides with a registered ` +\n `provider. A property is either injected or provided by a ` +\n `plugin, not both.`,\n );\n }\n byId.set(id, {\n pluginType: \"property\",\n name: existing.name,\n namespace: existing.namespace,\n id,\n imports: [],\n importBindings: [],\n value,\n });\n }\n }\n\n for (const [id, plugin] of byId) {\n if (isStandIn(plugin)) {\n // A `declareOptionalProperty` stand-in left unsatisfied is not an error: it stays\n // in the graph (so topological order is consistent) but materializes no\n // entry, and dependents bind `undefined` (see buildImports).\n if (\"optional\" in plugin && plugin.optional) continue;\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\n for (const id of conflictedDefaults) {\n const winner = byId.get(id);\n if (winner && isDefault(winner)) {\n throw new Error(\n `createSdk: conflicting defaults for \"${id}\". Two different plugins ` +\n `were declared as defaults for the same id and nothing else ` +\n `provides it. Register an explicit (non-default) plugin for this ` +\n `id to choose the winner, or give the implementations distinct ids ` +\n `if they are meant to coexist.`,\n );\n }\n }\n return byId;\n}\n\n/**\n * Which twin `bindValue` binds: the surface callable or a method's internal\n * twin. Distinct from `CallOrigin` (whether a call's root is user work or\n * framework machinery) even though both happen to spell `\"surface\" | \"internal\"`\n * — an import always binds the internal twin yet can still be surface-origin.\n */\ntype BindMode = \"surface\" | \"internal\";\n\ntype InternalMethodCallable = (...args: unknown[]) => unknown;\n\ninterface BindInternalTwinOptions {\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n withContext: (context: CallContext) => InternalMethodCallable;\n internalValue: InternalMethodCallable;\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,\n key,\n entry,\n bindMode = \"surface\",\n ctx,\n frameworkOrigin = false,\n}: {\n target: Record<string, unknown>;\n key: string;\n entry: PluginEntry;\n bindMode?: BindMode;\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n}): void {\n if (entry.pluginType === \"property\" && entry.getValue) {\n // A threaded per-call context flows into the property's getter so a\n // context-aware property (one whose value is derived per call) reads the\n // live callId. Method calls always have a context, at any depth — the\n // boundary resolves one before `run`. The two binds without one are the ones\n // with no call in flight: the SDK object's own property (bound once here) and\n // a `setup`-time imports bag. Those get the bare value.\n const getValue = entry.getValue;\n Object.defineProperty(target, key, {\n get: ctx ? () => getValue(ctx) : getValue,\n enumerable: true,\n configurable: true,\n });\n } else {\n // Import-facing bindings take the internal twin (surface-only concerns\n // like the deprecation signal stay quiet on delegation). With a call\n // context threaded (a per-invocation import bag), the twin carries a child\n // context so the callee sees the right nesting depth and correlation id;\n // without one (build-time binding) it is a parent-less internal call.\n // `frameworkOrigin` marks that parent-less root as framework-internal (so a\n // head can drop its telemetry); the default parent-less twin stays\n // surface-origin so a runtime delegation proxy keeps emitting.\n // Legacy graph entries have no twin and fall back to the one value.\n const value =\n bindMode === \"internal\" && entry.pluginType === \"method\"\n ? (entry.bindInternal?.({ ctx, frameworkOrigin }) ??\n entry.internalValue ??\n entry.value)\n : (entry as MethodEntry | PropertyEntry).value;\n Object.defineProperty(target, key, {\n 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,\n importBindings,\n ctx,\n frameworkOrigin = false,\n}: {\n plugins: Record<string, PluginEntry>;\n importBindings: readonly ImportBinding[];\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n}): Record<string, unknown> {\n const imports: Record<string, unknown> = {};\n for (const { binding, id, optional } of importBindings) {\n const entry = plugins[id];\n if (!entry && optional) {\n // An unsatisfied `declareOptionalProperty` dependency: bind the name as\n // `undefined` so the consumer can fall back to its own defaults.\n Object.defineProperty(imports, binding, {\n value: undefined,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n continue;\n }\n bindValue({\n target: imports,\n key: binding,\n entry,\n bindMode: \"internal\",\n ctx,\n frameworkOrigin,\n });\n }\n return imports;\n}\n\n/**\n * The shared origin rule for a method's import-facing twin, so the positional\n * and single-input projections don't each re-encode it. A threaded `ctx` mints\n * a fresh child per call (callee inherits `callId`/origin, one level deeper); a\n * parent-less twin is the surface-origin `internalValue`, or a fresh\n * framework-internal root only when `frameworkOrigin` is set (kitcore's own\n * build-time passes request that so their calls can be dropped from telemetry).\n * `withContext` adapts the twin's call convention (positional pack vs single\n * input) to the chosen context.\n */\nfunction bindInternalTwin({\n ctx,\n frameworkOrigin,\n withContext,\n internalValue,\n}: BindInternalTwinOptions) {\n if (ctx) {\n return (...args: unknown[]) => withContext(childCallContext(ctx))(...args);\n }\n if (frameworkOrigin) {\n return (...args: unknown[]) =>\n withContext(rootCallContext({ callOrigin: \"internal\" }))(...args);\n }\n return internalValue;\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, states);\n assembleHooks(descriptors, context, states);\n applyMethodOverrides(descriptors, context);\n return context.plugins;\n}\n\n/**\n * Merge one method-override's meta patch onto its target method entry. Fails\n * loud if the target is absent or is not a method: an override must run after\n * its target materializes (the pass order guarantees that within a build;\n * `addPlugin` applies it against the already-live graph).\n */\nfunction applyMethodOverride(\n context: SdkContext,\n override: MethodOverridePlugin,\n): void {\n const entry = context.plugins[override.target];\n if (!entry) {\n throw new Error(\n `defineMethodOverride: no method \"${override.target}\" to override. ` +\n `Include the target method in the SDK build.`,\n );\n }\n if (entry.pluginType !== \"method\") {\n throw new Error(\n `defineMethodOverride: \"${override.target}\" is a ${entry.pluginType}, ` +\n `not a method; only methods can be overridden.`,\n );\n }\n entry.meta = { ...entry.meta, ...override.meta };\n}\n\n/**\n * Final pass: apply every method-override in the graph. Runs after all method\n * entries exist (module or legacy-projected) so each override merges its public\n * meta fields onto the target entry that the surface registry then projects.\n */\nfunction applyMethodOverrides(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n for (const descriptor of descriptors.values()) {\n if (descriptor.pluginType !== \"method-override\") continue;\n applyMethodOverride(context, descriptor);\n }\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 // Resolver imports are framework-internal: an SDK method a resolver calls\n // is machinery, not user work, so its root is internal-origin (dropped\n // from telemetry) rather than a surface-origin emitting root.\n const imports = buildImports({\n plugins,\n importBindings: resolver.importBindings,\n frameworkOrigin: true,\n });\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 if (resolver.additionalKeys) {\n const ak = resolver.additionalKeys;\n const boundAk: BoundAdditionalKeys = {\n values: isResolverRef(ak.values)\n ? ak.values\n : bindResolver(ak.values, plugins),\n minEntries: ak.minEntries,\n maxEntries: ak.maxEntries,\n keyValueType: ak.keyValueType,\n valueValueType: ak.valueValueType,\n };\n if (ak.keys)\n boundAk.keys = isResolverRef(ak.keys)\n ? ak.keys\n : bindResolver(ak.keys, plugins);\n bound.additionalKeys = boundAk;\n }\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 case \"dynamic\": {\n // See the object case: resolver imports are internal-origin.\n const imports = buildImports({\n plugins,\n importBindings: resolver.importBindings,\n frameworkOrigin: true,\n });\n const {\n getContext,\n listItems,\n validate,\n tryResolveWithoutPrompt,\n tryResolveFromSearch,\n } = resolver;\n const bound: BoundResolver = {\n type: \"dynamic\",\n requireParameters: resolver.requireParameters,\n inputType: resolver.inputType,\n placeholder: resolver.placeholder,\n prompt: resolver.prompt,\n listItems: ({ input, context, search, cursor }) =>\n listItems({ imports, input, context, search, cursor }),\n };\n if (getContext)\n bound.getContext = ({ input }) => getContext({ imports, input });\n if (validate) {\n bound.validate = ({ value, input, context }) =>\n validate({ imports, value, input, context });\n }\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 default: {\n // Exhaustiveness: adding a resolver kind without a bind branch fails to\n // compile here (and throws for a hostile untyped descriptor).\n const unhandled: never = resolver;\n throw new Error(\n `unhandled resolver kind: ${(unhandled as { type: string }).type}`,\n );\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 // Formatter imports are framework-internal (see bindResolver): an SDK method\n // a formatter calls is machinery, so its root is internal-origin.\n const imports = buildImports({\n plugins,\n importBindings: formatter.importBindings,\n frameworkOrigin: true,\n });\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 // Record the legacy root keys on the surface, the same way `addPlugin`'s\n // legacy branch does. Without it a bridged SDK has an EMPTY surface map,\n // and any surface-driven reader either sees nothing or, once a module\n // plugin is added later, sees only the module half. A legacy method\n // surfaces under its own name (binding === id).\n for (const name of Object.keys(rootKeys)) context.surface[name] = name;\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 // The SAME memoized read the free `getRegistry(sdk)` takes, so a bridged\n // SDK has one registry rather than two that merely agree. They used to\n // differ in everything but content: this one rebuilt per call, so it was\n // unfrozen, a fresh object each time, and it re-paid the whole projection\n // on every MCP request. `buildSurfaceRegistry` layers `context.meta` and\n // builds its own surface from live getters, which is the only thing this\n // needed `this` for.\n function getRegistry(options?: { package?: string }): RegistryResult {\n return getCachedRegistry(context, options?.package);\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), with list adding\n * the page 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 // A stand-in that survived collection is an unsatisfied optional method\n // (`declareOptionalMethod`): materialize no entry, so dependents bind\n // `undefined` rather than a throwing callable. A required stand-in never\n // reaches here (it is either replaced by its provider or already errored).\n if (isStandIn(descriptor)) 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 skipInputValidation: descriptor.skipInputValidation,\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, ctx?: CallContext): unknown => {\n // The boundary always resolves a context before the fold reaches here;\n // the fallback keeps the run bag's `callContext` non-optional for any\n // parent-less path that might call the core directly.\n const callContext = ctx ?? rootCallContext();\n return descriptor.run({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n ctx: callContext,\n }),\n state: states.get(id),\n input,\n callContext,\n annotate: (metadata: Annotations) => {\n Object.assign(callContext.annotations, metadata);\n },\n });\n };\n // Fold the middleware chain around a core, reading `entry.chain` live. The\n // call context is captured in the closure — the middleware chain stays\n // single-argument (`next(input)`), so `ctx` reaches the run bag and each\n // wrap's imports without threading through every `next` call.\n const fold =\n (coreFn: (input: unknown, ctx?: CallContext) => unknown) =>\n (input: unknown, ctx?: CallContext): unknown => {\n let next: (input: unknown) => unknown = (i) => coreFn(i, ctx);\n for (const wrap of entry.chain) {\n const inner = next;\n next = (i: unknown) =>\n wrap.run({\n imports: buildImports({\n plugins,\n importBindings: wrap.owner.importBindings,\n ctx,\n }),\n next: inner,\n input: i,\n // Overwritten by the chain item's own closure with the owning\n // hook's setup state.\n state: undefined,\n });\n }\n return next(input);\n };\n const sdk = { context };\n\n // Hand the boundary a thin per-method pre-run annotator:\n // `(input) => annotations` it invokes synchronously before `onMethodStart`.\n // It receives only `input` — fields needing imports or async work are\n // written mid-`run` via the run bag's `annotate`. Absent when the method\n // declares no `annotator`.\n const methodAnnotator = descriptor.annotator;\n const boundAnnotator = methodAnnotator\n ? (input: unknown) => methodAnnotator({ input })\n : undefined;\n\n // Built per call, not once: the schema and author opt-out are static, but\n // the caller's opt-out rides this call's options and the core options (the\n // dropped-path report, the head's error factory) resolve live at invocation\n // time like every other core option.\n const outputPolicy = (callOptions: unknown): OutputPolicy => {\n const core = resolveCoreOptions(context);\n return {\n outputSchema: descriptor.meta?.outputSchema,\n skipOutputValidation: descriptor.skipOutputValidation,\n skippedByCaller: readSkipOutputDataValidation(callOptions),\n includeOutputValidationDroppedPaths:\n core?.includeOutputValidationDroppedPaths,\n methodName: descriptor.name,\n adaptError: core?.adaptError,\n };\n };\n\n // How this method's boundary treats the framework's call parameters: what\n // it reads out of the caller's object, and what it hands to `run`. Both\n // depend on the mode, and the item mode reads far less than the list one.\n const frameworkOptions =\n out.type === \"list\" ? LIST_FRAMEWORK_OPTIONS : ITEM_FRAMEWORK_OPTIONS;\n // A fact about the mode, so it is worked out once here rather than per\n // page, and with no reading of the plugin's schema.\n const withheld = withheldFromRun(frameworkOptions);\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((input: unknown, ctx?: CallContext) =>\n callRun(stripFrameworkOnlyOptions(input, withheld), ctx),\n ) as (o?: unknown, ctx?: CallContext) => Promise<unknown>,\n {\n sdk,\n schema: descriptor.inputSchema,\n name: descriptor.name,\n frameworkOptions,\n defaultPageSize: out.defaultPageSize,\n adaptPage: out.adaptPage,\n annotator: boundAnnotator,\n // Validate + strip each item against the item `outputSchema`\n // (item mode's sibling); dropped paths surface as `[].x` in the page's\n // `meta`, unioned across items.\n finalizePage: (page, callOptions) =>\n applyListOutputPolicy(page, outputPolicy(callOptions)),\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n } else if (out.type === \"item\") {\n // `run` returns the `{ data }` envelope itself (enforced by the item\n // overload's typing, like list's strict page); the async core inside the\n // fold guarantees a dependent's middleware sees a Promise of that\n // envelope as `next`'s result. The `name` option gives the boundary's\n // hook payload the method name (the folded core is anonymous).\n // The policy reads the caller's skip off the RAW input, before the\n // framework's own parameters are stripped on their way to `run`.\n const itemCore = async (\n input: unknown,\n ctx?: CallContext,\n ): Promise<unknown> =>\n applyItemOutputPolicy(\n await callRun(stripFrameworkOnlyOptions(input, withheld), ctx),\n outputPolicy(input),\n );\n entry.value = createFunction(\n fold(itemCore) as (o?: unknown, ctx?: CallContext) => Promise<unknown>,\n {\n sdk,\n schema: descriptor.inputSchema,\n name: descriptor.name,\n frameworkOptions,\n annotator: boundAnnotator,\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n } else {\n // raw: the boundary supplies the method lifecycle (scope + hook firing)\n // and error-branded validation, but no envelope and no rethrow\n // normalization: the surface is whatever `run` returns, the original\n // error propagates, and a synchronous `run` stays synchronous.\n // `skipInputValidation` passes the raw input through untouched (no parse\n // → no coercion/strip/clone) while keeping `inputSchema` for projection;\n // the method owns its own validation (e.g. `fetch`).\n // Validate the WHOLE return against `outputSchema`, since raw has no\n // envelope for the schema to describe a slice of. Threaded by hand rather\n // than through a boundary seam because raw promises a synchronous `run`\n // stays synchronous: awaiting unconditionally would turn every raw method\n // into a thenable.\n // Static, so decide once: raw is the default mode and the hot path\n // (`fetch`), and building a policy per call costs a second\n // `resolveCoreOptions` plus, for an async return, a microtask hop, before\n // `applyRawOutputPolicy` discovers there is nothing to check.\n const rawValidates =\n descriptor.meta?.outputSchema !== undefined &&\n !descriptor.skipOutputValidation;\n const validateRaw = (out: unknown): unknown => {\n // No call options: the author's opt-out is the only one raw honors.\n const policy = outputPolicy(undefined);\n if (isPromiseLike(out)) {\n return Promise.resolve(out).then((value) =>\n applyRawOutputPolicy(value, policy),\n );\n }\n return applyRawOutputPolicy(out, policy);\n };\n // Raw reserves NOTHING in the caller's call object: no per-call skip is\n // read, and nothing is stripped on the way to `run`. That whole object is\n // the author's, and raw is the mode most likely to forward it verbatim\n // into a request, so a framework key shadowing a domain one there is the\n // worst version of a problem the framework should not create at all. A\n // caller who passes `skipOutputDataValidation` to a raw method is passing\n // domain input that happens to share the name.\n entry.value = createRawFunction(\n (input: unknown, ctx?: CallContext) => {\n const out = fold(callRun)(input, ctx);\n return rawValidates ? validateRaw(out) : out;\n },\n {\n sdk,\n name: descriptor.name,\n schema: descriptor.skipInputValidation\n ? undefined\n : descriptor.inputSchema,\n positional: descriptor.positional,\n annotator: boundAnnotator,\n // The boundary reads the deprecation LIVE off the entry, so a\n // deprecation merged after build (defineMethodOverride, addPlugin)\n // fires too. Same for the stability level, normalized from the\n // entry meta (declared level or legacy `experimental` boolean).\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n }\n // The import-facing twin: the SAME boundary called with a marker in its\n // second argument slot, so surface-only concerns (the deprecation signal)\n // don't fire when a sibling plugin delegates. The marker is either the\n // `INTERNAL_CALL` sentinel (a parent-less internal call — build-time\n // binding or `resolvePlugin`) or a child `CallContext` minted from the\n // caller's context (a per-invocation delegation, so the callee inherits the\n // `callId` and sits one level deeper). One boundary, thin bindings — no\n // duplicated wrapper stack, and the marker never leaves this writer/reader\n // pair (both created here, by this kitcore copy).\n const canonicalValue = entry.value as (\n input: unknown,\n internal?: typeof INTERNAL_CALL | CallContext,\n ) => unknown;\n // `bindInternal` produces the twin `buildImports` binds; its origin rule\n // lives once in `bindInternalTwin`. The two projections differ only in call\n // convention. Positional projection (see Output): the surface and imports\n // take ordered args; pack them into the canonical `{ input }` before the\n // mode value runs, so validation, middleware, and `run` stay canonical. Set\n // only provided args so trailing optionals (e.g. `fetch(url)`) stay absent.\n if (descriptor.positional) {\n const names = descriptor.positional;\n const pack = (args: unknown[]): Record<string, unknown> => {\n const packed: Record<string, unknown> = {};\n names.forEach((name, i) => {\n if (i < args.length) packed[name] = args[i];\n });\n return packed;\n };\n const internalValue = (...args: unknown[]) =>\n canonicalValue(pack(args), INTERNAL_CALL);\n entry.value = (...args: unknown[]) => canonicalValue(pack(args));\n entry.internalValue = internalValue;\n entry.bindInternal = (opts) =>\n bindInternalTwin({\n ...opts,\n withContext: (context) => {\n return (...args: unknown[]) => canonicalValue(pack(args), context);\n },\n internalValue,\n });\n entry.positional = names;\n } else {\n const internalValue = (input: unknown) =>\n canonicalValue(input, INTERNAL_CALL);\n entry.internalValue = internalValue;\n entry.bindInternal = (opts) =>\n bindInternalTwin({\n ...opts,\n withContext: (context) => (input: unknown) =>\n canonicalValue(input, context),\n internalValue,\n });\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 // overrides only patch meta in the final pass. A stand-in that survived\n // collection is an unsatisfied `declareOptionalProperty`: materialize no entry, so\n // dependents bind `undefined`.\n if (\n !descriptor ||\n descriptor.pluginType === \"aggregate\" ||\n descriptor.pluginType === \"legacy\" ||\n descriptor.pluginType === \"method-override\" ||\n isStandIn(descriptor)\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 // Record teardown in build order (dependencies first); `disposeSdk` walks\n // the list in reverse so dependents release before their dependencies.\n const recordDisposer = (): void => {\n const dispose = (descriptor as { dispose?: DisposeFn }).dispose;\n if (!dispose) return;\n context.disposers?.push({\n id,\n // Teardown is framework-internal: an SDK method a `dispose` calls runs\n // on an internal-origin root (dropped from telemetry).\n dispose: (input?: unknown) =>\n dispose({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n frameworkOrigin: true,\n }),\n state: states.get(id),\n input,\n }),\n });\n };\n if (descriptor.pluginType === \"hook\") {\n // A hook has no surfaced entry; run its `setup` once for the state that\n // `assembleHooks` closes over when composing observers into context.hooks.\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n }),\n })\n : undefined,\n );\n recordDisposer();\n building.delete(id);\n built.add(id);\n return;\n }\n if (descriptor.pluginType === \"method\") {\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n }),\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({\n plugins,\n importBindings: descriptor.importBindings,\n }),\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 dynamicMembers: descriptor.dynamicMembers,\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: (callContext?: CallContext) =>\n get({\n imports: buildImports({\n plugins,\n importBindings,\n ctx: callContext,\n }),\n state: states.get(id),\n callContext,\n }),\n meta: descriptor.meta,\n dynamicMembers: descriptor.dynamicMembers,\n };\n } else {\n plugins[id] = {\n pluginType: \"property\",\n name: descriptor.name,\n value: descriptor.value,\n meta: descriptor.meta,\n dynamicMembers: descriptor.dynamicMembers,\n };\n }\n assertDynamicMemberRoot(plugins[id] as PropertyEntry);\n }\n recordDisposer();\n building.delete(id);\n built.add(id);\n };\n for (const id of descriptors.keys()) ensureBuilt(id);\n}\n\n/**\n * Resolve a plugin's materialized value against a built SDK: a method's\n * callable or a property's value (the same thing an importer receives), NOT\n * the plugin descriptor. For head infrastructure that builds the SDK and\n * needs one of its own internals; consumers use the SDK surface, and in-graph\n * code keeps using `imports`. Read-only against the built graph; nothing\n * materializes. A missing required ref throws; an unsatisfied optional ref\n * resolves `undefined` (matching import behavior); a live `get` property\n * re-reads per call (a read-time snapshot — hold the function, not the value,\n * for liveness). Aggregate refs are not one-ref-one-binding and are\n * unsupported.\n */\nexport function resolvePlugin<TRef extends AnyLeafPlugin>(\n sdk: unknown,\n ref: TRef,\n): ExportSurface<TRef> {\n const entry = getContext(sdk).plugins[ref.id];\n if (!entry) {\n if ((ref as { optional?: boolean }).optional) {\n return undefined as ExportSurface<TRef>;\n }\n throw new Error(\n `resolvePlugin: plugin \"${ref.id}\" is not materialized on the SDK.`,\n );\n }\n // Same binding semantics as buildImports: a method's callable or a\n // property's value — including the internal twin, so out-of-graph\n // infrastructure delegating through resolvePlugin doesn't trip\n // surface-only concerns (deprecation) any more than an importer would. The\n // twin is internal-origin (CLI/MCP infra delegation is machinery, not user\n // work, so it stays out of telemetry); user commands reach methods through\n // the SDK surface (`entry.value`), which emits.\n if (entry.pluginType === \"property\" && entry.getValue) {\n return entry.getValue() as ExportSurface<TRef>;\n }\n if (entry.pluginType === \"method\" && entry.internalValue) {\n return (entry.bindInternal?.({ frameworkOrigin: true }) ??\n entry.internalValue) as ExportSurface<TRef>;\n }\n return (entry as MethodEntry | PropertyEntry).value as ExportSurface<TRef>;\n}\n\n/**\n * Thrown by {@link disposeSdk} when one or more dispose callbacks failed.\n * Every dispose was still attempted; `errors` holds the failures in teardown\n * order.\n */\nexport class CoreDisposeError extends Error {\n readonly name: string = \"CoreDisposeError\";\n readonly errors: unknown[];\n constructor(errors: unknown[]) {\n super(`disposeSdk: ${errors.length} dispose callback(s) failed.`);\n this.errors = errors;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Tear down a built SDK: run every recorded `dispose` (a leaf's `setup` dual)\n * in reverse build order, so dependents release before their dependencies.\n * Each dispose is awaited and run defensively; all are attempted even after a\n * failure, then the failures reject together as {@link CoreDisposeError}.\n * Idempotent: the first call's `input` wins and later calls return the same\n * settled result. A top-level function like `addPlugin`, reaching internals\n * through the `CONTEXT` symbol, so anyone holding the sdk can call it.\n */\nexport function disposeSdk(sdk: unknown, input?: unknown): Promise<void> {\n const context = getContext(sdk);\n if (context.disposed) return context.disposed;\n const disposers = context.disposers ?? [];\n context.disposed = (async () => {\n const errors: unknown[] = [];\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n await disposers[i].dispose(input);\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0) throw new CoreDisposeError(errors);\n })();\n return context.disposed;\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({ target: exports, key: binding, entry: plugins[child.id] });\n }\n plugins[id] = { pluginType: \"aggregate\", name: descriptor.name, exports };\n }\n}\n\n/**\n * Pass 4: assemble wrap chains. Walk hooks in topological order (dependencies\n * first), so a wrapping hook that depends on another sorts after it. Appending\n * in this order leaves each target's chain innermost-first, which the pass-1\n * fold turns into dependents-outermost at call time (retry depends on auth, so\n * retry(auth(core))). A target must be a direct dependency that resolves to a\n * method; the wrap receives the hook's `setup` state alongside the fold's\n * `{ imports, next, input }`.\n */\nfunction assembleMiddleware(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\n): void {\n const plugins = context.plugins;\n for (const id of topoOrder(descriptors)) {\n const descriptor = descriptors.get(id);\n if (!descriptor || descriptor.pluginType !== \"hook\" || !descriptor.wrap) {\n continue;\n }\n for (const [targetBinding, fn] of Object.entries(descriptor.wrap)) {\n const edge = descriptor.importBindings.find(\n (b) => b.binding === targetBinding,\n );\n if (!edge) {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `is not a direct dependency. A wrap target must be a ` +\n `declared import of the wrapping hook.`,\n );\n }\n const target = plugins[edge.id];\n if (!target || target.pluginType !== \"method\") {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `does not resolve to a method.`,\n );\n }\n // A list method's wrap would sit around the page fetcher, not the public\n // PaginatedSdkResult, so it would see raw pages instead of the iterator\n // (see Pass 1). Reject until that contract is settled, rather than\n // silently giving surprising semantics.\n if (target.output?.type === \"list\") {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `resolves to a list-output method, which does not support ` +\n `wrapping yet.`,\n );\n }\n target.chain.push({\n run: (bag) => fn({ ...bag, state: states.get(id) }),\n owner: descriptor,\n });\n }\n }\n}\n\n/**\n * Pass 5: compose module-model hook observers and annotators into the ambient\n * hook registry (`context.hooks`) the method boundary fires. Each `defineHook`'s\n * `observe` fns and its `annotator` are adapted to the boundary's `MethodHooks`\n * shape (the lifecycle context becomes the observer's `input`, alongside its\n * `imports` and `setup` state) and folded in with `buildHooks`, on top of any\n * legacy-contributed hooks. Both run defensively: a thrown observer/annotator\n * error is swallowed so it never breaks the observed call. Walk in topological\n * order so a hook that depends on another composes after it (right-additive,\n * matching legacy ordering).\n */\nfunction assembleHooks(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\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 !== \"hook\" ||\n (!descriptor.observe && !descriptor.annotator)\n ) {\n continue;\n }\n const { observe, annotator } = descriptor;\n const state = states.get(id);\n const contributed: MethodHooks = {};\n if (observe?.onMethodStart || observe?.onMethodEnd) {\n // Hook imports are framework-internal: an SDK method an observer calls is\n // machinery, so its root is internal-origin (belt-and-suspenders with the\n // `runIsolatedObserver` hook suppression below). Only observers receive\n // imports; the annotator runs synchronously with `input` only.\n const imports = buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n frameworkOrigin: true,\n });\n // `runIsolatedObserver` gives each observer both protections: defensive\n // execution (an observer error never breaks the observed call) and hook\n // suppression for any SDK method the observer itself calls (no\n // hook -> observer -> method -> hook recursion).\n if (observe.onMethodStart) {\n const onStart = observe.onMethodStart;\n contributed.onMethodStart = (input) => {\n runIsolatedObserver(() => onStart({ imports, input, state }));\n };\n }\n if (observe.onMethodEnd) {\n const onEnd = observe.onMethodEnd;\n contributed.onMethodEnd = (input) => {\n runIsolatedObserver(() => onEnd({ imports, input, state }));\n };\n }\n }\n // The annotator is a pre-run mapper, not a void observer: it returns\n // Annotations the boundary merges before onMethodStart, so it runs plainly\n // (not through `runIsolatedObserver`) with its own best-effort guard so one\n // throwing annotator neither breaks the call nor suppresses the others.\n if (annotator) {\n const annotatorFn = annotator;\n contributed.annotator = ({ methodName, input }) => {\n try {\n return annotatorFn({ methodName, input, state });\n } catch {\n // Annotation inference must never break the call.\n return {};\n }\n };\n }\n context.hooks = buildHooks(context.hooks, contributed);\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. `options.configuration`\n * injects runtime values by plugin id (see {@link CreateSdkOptions}).\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 options?: CreateSdkOptions,\n): MethodSdkOf<P>;\nexport function createSdk<P extends AnyPropertyPlugin>(\n root: P & CompletenessOf<P>,\n options?: CreateSdkOptions,\n): PropertySdkOf<P>;\nexport function createSdk<P extends AnyAggregatePlugin>(\n root: P & CompletenessOf<P>,\n options?: CreateSdkOptions,\n): AggregateSdkOf<P>;\nexport function createSdk<TSurface>(\n root: LegacyPlugin<TSurface>,\n options?: CreateSdkOptions,\n): TSurface & SdkInternals;\nexport function createSdk<\n TProvides extends PluginProvides,\n TPlugin extends AnyPlugin,\n>(\n root: LegacyMergePlugin<TProvides, TPlugin>,\n options?: CreateSdkOptions,\n): TProvides & {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n} & AddedSurface<TPlugin> &\n SdkInternals;\nexport function createSdk(\n root: AnyPlugin | LegacyMergePlugin,\n options?: CreateSdkOptions,\n): Record<string, unknown> {\n const context: SdkContext = {\n plugins: {},\n meta: {},\n hooks: {},\n surface: {},\n disposers: [],\n };\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(\n collectPlugins(collectRoot, undefined, options?.configuration),\n context,\n );\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({\n target: pluginSurface,\n key: plugin.name,\n entry: plugins[plugin.id],\n });\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(\n collectPlugins(root, undefined, options?.configuration),\n context,\n );\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({ target: sdk, key: root.name, entry: 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. A hook surfaces nothing (it has no entry or callable).\n const surfaceKeys =\n plugin.pluginType === \"aggregate\"\n ? Object.keys((plugin as AggregatePlugin).exports)\n : plugin.pluginType === \"hook\"\n ? []\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 // A hook is done here: materialize already appended its wraps to the live\n // chains and composed its observers; there is no entry to surface.\n if (plugin.pluginType === \"hook\") return;\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({ target: sdk, key: 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 const record = sdk as unknown as Record<string, unknown>;\n // A pure-legacy stack-built SDK (createPluginStack().toSdk()) has no\n // `[CONTEXT]` graph, hence every guard below.\n const context = getContext(record);\n try {\n if (typeof plugin === \"function\") {\n const contribution = applyPluginToSdk(\n record,\n plugin as Plugin<unknown, PluginProvides>,\n options ?? {},\n );\n // Mirror addModelPlugin: keep context.plugins/context.surface\n // authoritative for the legacy path too. applyPluginToSdk only writes\n // sdk + context.meta, so without this a surface-driven reader\n // (getRegistryPlugin) would miss a legacy method added after build. The\n // contribution's keys are already collision-checked against the sdk by\n // mergeContribution.\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 } else if ((plugin as AnyPlugin).pluginType === \"method-override\") {\n // An override surfaces nothing; it patches an existing entry's meta\n // against the live graph (no delta to materialize, no root key to bind).\n applyMethodOverride(context, plugin as MethodOverridePlugin);\n } else {\n addModelPlugin(record, plugin as AnyPlugin, options ?? {});\n }\n } finally {\n // Drop the memoized registry AFTER the surface changes, not before. Before\n // would leave the window open for a read during this call to re-cache a\n // half-updated surface; after, such a read sees the old registry, which is\n // stale but coherent, and this clears it either way. In a `finally` so a\n // throw partway through cannot leave an entry describing a surface that was\n // only partly mutated.\n if (context) invalidateRegistryCache(context);\n }\n}\n","import { z } from \"zod\";\nimport type {\n FunctionRegistryEntry,\n RegistryResult,\n} from \"../../types/registry\";\nimport { getRegistry } from \"../materialize\";\nimport { CoreCancelledSignal } from \"../../types/signals\";\nimport { canonicalInputSchema } from \"../../utils/schema-utils\";\nimport { planParameters } from \"./plan\";\nimport type { EngineContext } from \"./engine\";\nimport { firstPage, toChoice } from \"./questions\";\nimport { start as engineStart, step as engineStep } from \"./walk\";\nimport type {\n ControllerChoice,\n ControllerParameterDescription,\n ControllerMethodDescription,\n ControllerMethodSummary,\n Controller,\n} from \"./types\";\nimport type { SdkInternals } from \"../types\";\n\n/**\n * What the driver needs of a built SDK: one of two ways to reach a registry.\n *\n * The registry is read with the free {@link getRegistry}, which finds it on the\n * SDK's context and falls back to a surfaced `getRegistry()` for a legacy\n * stack-built SDK. So demanding the surfaced method alone is wrong: a bare tool\n * SDK does not surface one, and it cannot always add `getRegistryPlugin`\n * either, because a head bundling its own kitcore copy would collide with it on\n * the shared `kitcore/getRegistry` id.\n *\n * A union, because those really are two different shapes. `SdkInternals` is\n * what every `createSdk` result carries, and the structural branch is the\n * legacy one. Anything else can never back a controller, and saying so here\n * beats an internal registry error on the caller's first `listMethods()`.\n *\n * The context branch is `SdkInternals`, which declares the `[CONTEXT]` symbol\n * materialization actually writes. So this checks the real thing rather than a\n * correlated one.\n */\nexport type ControllerSdk =\n | SdkInternals\n | { getRegistry: (options?: { package?: string }) => RegistryResult };\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 // Read per-field hints from the canonical variant so they match the planned\n // parameters and the generated docs; a raw union has no top-level properties.\n const inputProperties = toJsonSchema(canonicalInputSchema(entry.inputSchema))\n ?.properties as Record<string, Record<string, unknown>> | undefined;\n const parameters: Record<string, ControllerParameterDescription> = {};\n for (const spec of planParameters(entry).parameters) {\n const dynamic =\n spec.resolver?.type === \"dynamic\" ? spec.resolver : undefined;\n parameters[spec.name] = {\n required: spec.required,\n dynamic: Boolean(dynamic),\n ...(dynamic?.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 the registry\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 = getRegistry(sdk).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 // A method that owns its input validation (`skipInputValidation`, e.g.\n // fetch) must not be re-validated by the controller's final `safeParse`;\n // drop the schema so `finalize` returns the resolved input untouched.\n // Planning still reads `entry.inputSchema` directly, so parameters are\n // unaffected.\n schema: entry.skipInputValidation ? undefined : 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: getRegistry(sdk).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 const dynamic =\n spec?.resolver?.type === \"dynamic\" ? spec.resolver : undefined;\n if (!dynamic) 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 dynamic.getContext?.({ input });\n const page = await firstPage(\n dynamic.listItems({ input, context, search, cursor }),\n );\n const config = dynamic.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): value is CoreSignal {\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\n/**\n * Cross-package-safe check for {@link CoreCancelledSignal}. Keys on the\n * signal brand + `code` rather than `instanceof`, so it recognizes a\n * cancel signal raised by a different copy of kitcore (e.g. one bundled\n * into a head vs. one installed standalone).\n */\nexport function isCoreCancelledSignal(\n value: unknown,\n): value is CoreCancelledSignal {\n return isCoreSignal(value) && value.code === \"CANCELLED\";\n}\n","import { z } from \"zod\";\nimport type { FunctionRegistryEntry } from \"../../types/registry\";\nimport { objectShapeOf, unwrapSchema } from \"../../utils/schema-utils\";\nimport type { BoundResolver, ResolverRequirement } 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 /** The field's display label (an object field's `label`, e.g. the title an\n * upstream API supplies); questions use it over the raw key when present. */\n label?: string;\n valueType?: string;\n staticChoices?: ControllerChoice[];\n resolver?: BoundResolver;\n requires: readonly ResolverRequirement[];\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/** 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 // A record is an open-keyed object; coerce a typed answer as JSON like a\n // plain object rather than leaving it a string that fails validation.\n if (inner instanceof z.ZodRecord) 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/** Order specs so each parameter's `requires` precede it, with the SCAN ORDER\n * of `specs` dominating: each step places the first spec (in `specs` order)\n * that is ready, rescanning from the top after every placement. Dependencies\n * only defer a parameter; they never promote a later one past an earlier one\n * that is (or becomes) ready — a queue-based sort would instead emit\n * dependency-distance \"waves\" (asking `connection` before `action` on\n * runAction). Members of a dependency cycle (which shouldn't exist) never\n * become ready; they are appended at the end, between themselves in scan\n * order. */\nfunction topoOrder(specs: Leaf[]): Leaf[] {\n const byName = new Map(specs.map((s) => [s.name, s]));\n const placed = new Set<string>();\n const ordered: Leaf[] = [];\n // An absolute path orders top-level params only when it names one, i.e. a\n // single segment. A deeper path (`[\"input\", \"owner\"]`) points at a field that\n // resolves during the walk, well after this sort, so it cannot constrain the\n // top-level order and is ignored here rather than deadlocking it.\n const topLevelNameOf = (r: Leaf[\"requires\"][number]): string | undefined =>\n typeof r === \"string\"\n ? r\n : r.length === 1 && typeof r[0] === \"string\"\n ? r[0]\n : undefined;\n const isReady = (spec: Leaf): boolean =>\n spec.requires.every((r) => {\n const name = topLevelNameOf(r);\n return name === undefined || !byName.has(name) || placed.has(name);\n });\n for (;;) {\n const next = specs.find((s) => !placed.has(s.name) && isReady(s));\n if (!next) break;\n ordered.push(next);\n placed.add(next.name);\n }\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 = objectShapeOf(entry.inputSchema);\n const resolvers = entry.resolvers ?? {};\n // Off-schema bound CONSTANTS join the plan: a pinned value with no public\n // parameter (e.g. `actionType: \"read\"` on trigger methods). They settle in\n // the walk (satisfying dependents' `requireParameters`) and the final\n // schema parse strips them from the output. Other off-schema resolver kinds\n // stay out: they would prompt for a value the schema then discards.\n const names = shape\n ? [\n ...Object.keys(shape),\n ...Object.keys(resolvers).filter(\n (name) => !(name in shape) && resolvers[name].type === \"constant\",\n ),\n ]\n : Object.keys(resolvers);\n\n const specs: Leaf[] = names.map((name) => {\n const field = shape?.[name];\n const { inner, required } = field\n ? unwrapSchema(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 // Scan priority: off-schema constants, then required parameters, then\n // optionals — declaration order within each group, mirroring the walk's\n // required-first rule inside objects. A consumer answers what the method\n // needs before being offered what it doesn't. The constants go first\n // because they auto-settle without a question, and scanning them last\n // would defer every parameter that requires one (`action` requiring the\n // pinned `actionType`) past unrelated optionals.\n const declared = shape ? specs.filter((s) => s.name in shape) : specs;\n const scan = [\n ...(shape ? specs.filter((s) => !(s.name in shape)) : []),\n ...declared.filter((s) => s.required),\n ...declared.filter((s) => !s.required),\n ];\n return { parameters: topoOrder(scan) };\n}\n","import type { z } from \"zod\";\nimport type { SdkPage } from \"../../types/pagination\";\nimport type {\n BoundField,\n BoundObjectResolver,\n BoundResolver,\n Field,\n ResolverRef,\n} from \"../types\";\nimport type { Leaf } from \"./plan\";\nimport type {\n ControllerPagination,\n ControllerListingPage,\n ControllerListingPosition,\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), next/previous page moves, retry of a failed fetch,\n * `object` resolvers (static `properties`, dynamic `getProperties`, `{ ref }`\n * into `definitions`, nesting), `array` resolvers (min/max, the add/done\n * `collection` decision, items of any kind), and open-keyed record resolvers\n * (`object` with `additionalKeys`: a static/constant key prompt, min/max\n * entries, values resolved as ordinary leaves).\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\nexport function 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\n/** Own-property write that can never reach the prototype chain: a plain\n * `node[key] = v` with `key` of `__proto__` reassigns the prototype (or is\n * swallowed by the accessor) instead of creating an own entry, and\n * `constructor`/`prototype` shadow inherited members. `defineProperty` always\n * writes an own data property, so the tree write is safe for any key. (A record\n * key naming a prototype member is separately rejected upstream to keep it out\n * of the emitted value, a different concern than this write.) */\nfunction defineOwn(\n node: Record<string, unknown>,\n key: string,\n value: unknown,\n): void {\n Object.defineProperty(node, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n\nexport function 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 // Read the own property only (a plain `node[seg]` would surface the\n // prototype for a `__proto__` segment); create a fresh container otherwise.\n const existing = Object.prototype.hasOwnProperty.call(node, seg)\n ? node[seg]\n : undefined;\n if (existing != null && typeof existing === \"object\") {\n node = existing as Record<string, unknown>;\n } else {\n const child: Record<string, unknown> = {};\n defineOwn(node, seg, child);\n node = child;\n }\n }\n defineOwn(node, path[path.length - 1] as string, value);\n}\n\nconst SAFE_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** A path's key: the `settled` set's identity token AND its human-readable form\n * in messages — one format, so it never needs a lossy display twin. Unambiguous\n * (distinct paths never collide) yet readable, shaped like a JS accessor: a\n * plain-identifier segment joins with `.`, a number is `[n]`, anything else (a\n * record key with a `.`, an empty or special string) is bracketed as its\n * JSON-quoted form. So `[\"inputs\",\"a.b.js\"]`-style aliasing can't arise: bare\n * segments are `.`-delimited identifiers and bracketed ones are self-delimiting\n * JSON strings. `inputs.channel`, `records[0].name`, `files[\"a.b.js\"]`. */\nexport const pathToKey = (path: ControllerPath): string => {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else if (SAFE_SEGMENT.test(segment))\n out += out === \"\" ? segment : `.${segment}`;\n else out += `[${JSON.stringify(segment)}]`;\n }\n return out;\n};\n\n/** Whether the engine is done with the position at `path`. */\nexport function isSettled(\n state: ControllerState,\n path: ControllerPath,\n): boolean {\n return state.settled.includes(pathToKey(path));\n}\n\n/** Record a key in the settled set (idempotent): a path's key, or an\n * out-of-tree marker like the optionals gate's. */\nexport function remember(state: ControllerState, k: string): void {\n if (!state.settled.includes(k)) state.settled.push(k);\n}\n\n/** Mark the position at `path` done (idempotent). */\nexport function settle(state: ControllerState, path: ControllerPath): void {\n remember(state, pathToKey(path));\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. */\nexport function 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). Dispatched on `valueType`, so a scalar leaf never parses its answer as\n * JSON; only `object`/`array` leaves do. A parse that fails keeps the raw string\n * so the final `safeParse` reports a real message rather than swallowing it. */\nexport function 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 if (leaf.valueType === \"object\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return raw;\n }\n }\n return raw;\n }\n if (leaf.valueType === \"array\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return raw;\n }\n }\n // A non-JSON free-text array answer stays a string so final validation\n // fails loudly. A text-CLI convention like comma-splitting belongs to the\n // host that owns its input format, not this host-agnostic engine.\n return raw;\n }\n return raw;\n}\n\n/** Run the resolver's `validate` against a chosen/typed value. Returns an\n * error message when invalid, or null when valid / no validator. Recomputes\n * `getContext` so `validate` sees the same `context` the prompt did. May\n * throw (a fetching validate can fail); the caller turns that into a `failed`\n * result rather than a rejection. */\nexport async function validationError(\n leaf: Leaf,\n value: unknown,\n state: ControllerState,\n): Promise<string | null> {\n if (leaf.resolver?.type !== \"dynamic\") return null;\n const validate = leaf.resolver.validate;\n if (!validate) return null;\n const context = await resolveContext(leaf, state.resolved);\n const verdict = await validate({\n value,\n input: mergeInput(state.resolved, leaf.extraInput),\n context,\n });\n if (verdict === true) return null;\n return typeof verdict === \"string\" ? verdict : `${leaf.name}: invalid value`;\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 label: field.label,\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: BoundObjectResolver,\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 resolver kinds the walk settles WITHOUT asking (see `advance`'s\n * auto-settle branches): a constant pins its value, an info leaf is\n * display-only. The single source of truth the gates consult, so gate\n * triggering/counting can't drift from what `advance` actually asks. */\nexport function autoSettles(resolver: BoundResolver): boolean {\n return resolver.type === \"constant\" || resolver.type === \"info\";\n}\n\n/** Merge a leaf's ref-supplied `input` over the running input. */\nexport function 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). */\nexport async 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), array items\n * (numeric segments → the array's item resolver), and record entries (a string\n * segment that isn't a fixed field but sits under an `additionalKeys` object →\n * the record's value resolver, symmetric to the array-item case). Resolving a\n * record value here is what lets its answer flow through the normal leaf path\n * (refine, validate, coerce) rather than a bespoke record-value handler. */\nexport async 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 = boundLeaf(\n \"\",\n leaf.resolver.items,\n leaf.resolver.definitions,\n leaf.resolver.itemValueType,\n );\n } else {\n const parent = leaf;\n const found = children.find((c) => c.name === seg);\n if (found) {\n leaf = found;\n } else if (\n parent?.resolver?.type === \"object\" &&\n parent.resolver.additionalKeys\n ) {\n const ak = parent.resolver.additionalKeys;\n leaf = boundLeaf(\n String(seg),\n ak.values,\n parent.resolver.definitions,\n ak.valueValueType,\n );\n } else {\n return undefined;\n }\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/** Turn a bound resolver (or a `{ ref }` into `definitions`) into a {@link Leaf}\n * for an array item or a record entry's key/value. `valueType` carries the\n * element/entry value type so a free-text answer coerces (number/boolean) like a\n * top-level or object field, rather than staying a string and failing final\n * validation. */\nfunction boundLeaf(\n name: string,\n resolverOrRef: BoundResolver | ResolverRef,\n definitions: Record<string, BoundResolver> | undefined,\n valueType: string | undefined,\n): Leaf {\n if (isRef(resolverOrRef)) {\n return {\n name,\n required: true,\n resolver: definitions?.[resolverOrRef.ref],\n extraInput: resolverOrRef.input,\n valueType,\n requires: [],\n };\n }\n return {\n name,\n required: true,\n resolver: resolverOrRef,\n valueType,\n requires: [],\n };\n}\n\n/** The record (open-keyed object) at `path`: its entry bounds and the leaves its\n * keys and values resolve through. `keys` defaults to a free-text string prompt\n * when the resolver leaves it unset. */\nexport async function recordInfoAt(\n ctx: EngineContext,\n path: ControllerPath,\n resolved: Record<string, unknown>,\n): Promise<{\n min: number;\n max: number;\n keyLeaf: Leaf;\n valueLeaf: Leaf;\n fixedKeys: string[];\n}> {\n const leaf = await leafAt(ctx, path, resolved);\n const resolver = leaf?.resolver;\n if (resolver?.type !== \"object\" || !resolver.additionalKeys) {\n throw new Error(\n `expected an object resolver with additionalKeys at \"${pathToKey(path)}\"`,\n );\n }\n // `getProperties` builds a dynamic fixed-field set that only `childrenAt`\n // (author I/O) knows; combined with open keys the entry count couldn't be\n // taken from static knowledge. Disallow the combo so `fixedKeys` (static\n // `properties`) is the complete fixed set and the record loop needs no\n // per-pass fetch. Static `properties` + open keys is fine.\n if (resolver.getProperties) {\n throw new Error(\n `object resolver at \"${pathToKey(path)}\" cannot combine getProperties with additionalKeys`,\n );\n }\n const ak = resolver.additionalKeys;\n const defs = resolver.definitions;\n const keyLeaf: Leaf = ak.keys\n ? boundLeaf(\"key\", ak.keys, defs, ak.keyValueType ?? \"string\")\n : {\n name: \"key\",\n required: true,\n resolver: { type: \"static\", inputType: \"text\" },\n valueType: \"string\",\n requires: [],\n };\n const valueLeaf = boundLeaf(\"value\", ak.values, defs, ak.valueValueType);\n // A record key is the open, user-supplied name of an entry, collected as a\n // free-text prompt (it can't be a leaf in the value tree). So it must be\n // `static`: a `dynamic` key has no coherent \"pick the key\" flow, and a\n // `constant` (or `info`) key can't yield the distinct keys an open record\n // needs. Values, by contrast, resolve as normal leaves and may be `dynamic`;\n // composite (object/array) values are deferred (multi-step completion isn't\n // wired yet).\n if (keyLeaf.resolver && keyLeaf.resolver.type !== \"static\") {\n throw new Error(\n `record key resolver at \"${pathToKey(path)}\" must be a static free-text prompt, not \"${keyLeaf.resolver.type}\"`,\n );\n }\n if (\n valueLeaf.resolver?.type === \"object\" ||\n valueLeaf.resolver?.type === \"array\"\n ) {\n throw new Error(\n `record value resolver at \"${pathToKey(path)}\" must be a single value, not \"${valueLeaf.resolver.type}\"`,\n );\n }\n return {\n min: ak.minEntries ?? 0,\n max: ak.maxEntries ?? Infinity,\n keyLeaf,\n valueLeaf,\n fixedKeys: Object.keys(resolver.properties ?? {}),\n };\n}\n\n/** The array at `path`: its bounds and the item leaf (named after the array). */\nexport async 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 \"${pathToKey(path)}\"`);\n }\n return {\n min: resolver.minItems ?? 0,\n max: resolver.maxItems ?? Infinity,\n item: boundLeaf(\n String(path[path.length - 1]),\n resolver.items,\n resolver.definitions,\n resolver.itemValueType,\n ),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Fetch machinery (pre-fetch context + listing pages for dynamic resolvers). */\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. */\nexport async function resolveContext(\n leaf: Leaf,\n input: Record<string, unknown>,\n): Promise<unknown> {\n if (leaf.resolver?.type !== \"dynamic\") return undefined;\n return leaf.resolver.getContext?.({\n input: mergeInput(input, leaf.extraInput),\n });\n}\n\n/** The position a listing starts from: page one of a fresh generation, no\n * cursor, no trail. */\nexport function firstPagePosition(\n opts: { search?: string; generation?: number } = {},\n): ControllerListingPosition {\n return {\n ...(opts.search !== undefined ? { search: opts.search } : {}),\n pageCursor: null,\n previousCursors: [],\n generation: opts.generation ?? 0,\n };\n}\n\n/** Fetch exactly the page a {@link ControllerListingPosition} names. The\n * items go to the question being built; only `toPagination`'s coordinates enter\n * the state — pages accumulate host-side, never here.\n *\n * Search-mode with no term is search-first: the catalog behind a search\n * resolver is unbounded, so no fetch happens until the user provides a term.\n * The guard lives here so every path that renders from a position (initial\n * ask, page moves, retry, the rejected-pick re-ask) keeps the invariant. */\nexport async function fetchListing(\n leaf: Leaf,\n input: Record<string, unknown>,\n position: ControllerListingPosition,\n context?: unknown,\n): Promise<ControllerListingPage> {\n if (\n leaf.resolver?.type === \"dynamic\" &&\n leaf.resolver.inputType === \"search\" &&\n position.search === undefined\n ) {\n return { position, items: [] };\n }\n const page = await firstPage(\n leaf.resolver?.type === \"dynamic\"\n ? leaf.resolver.listItems({\n input: mergeInput(input, leaf.extraInput),\n context,\n search: position.search,\n cursor: position.pageCursor ?? undefined,\n })\n : undefined,\n );\n return {\n position,\n items: page.data,\n ...(page.nextCursor != null ? { nextCursor: page.nextCursor } : {}),\n };\n}\n\n/** The coordinates the state keeps from a fetched page (the items ride the\n * question instead). */\nexport function toPagination(\n page: ControllerListingPage,\n): ControllerPagination {\n return {\n position: page.position,\n ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),\n };\n}\n","import type {\n PromptConfig,\n PromptConfigChoice,\n DeprecatedPromptConfigChoice,\n} from \"../../utils/schema-utils\";\nimport type { Leaf } from \"./plan\";\nimport {\n fetchListing,\n firstPagePosition,\n mergeInput,\n resolveContext,\n toPagination,\n} from \"./engine\";\nimport type {\n ControllerAffordance,\n ControllerChoice,\n ControllerError,\n ControllerPagination,\n ControllerListingPage,\n ControllerQuestion,\n ControllerResult,\n ControllerState,\n ControllerPath,\n} from \"./types\";\n\nexport { firstPage } from \"./engine\";\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/* 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 nextPage: {\n action: \"next_page\",\n description: \"Fetch the next page of options\",\n },\n previousPage: {\n action: \"previous_page\",\n description: \"Return to the previous page of options\",\n },\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/** A shared affordance with a context-specific description. The gates all offer\n * `add`/`done` but word them differently (add an entry vs configure fields), so\n * the map stays the single source of the action identifiers and only the\n * wording is overridden — no gate re-spells the action string inline. */\nfunction affordance(\n base: ControllerAffordance,\n description: string,\n): ControllerAffordance {\n return { ...base, description };\n}\n\nfunction selectActions(\n leaf: Leaf,\n page: ControllerListingPage,\n multiple: boolean,\n): ControllerAffordance[] {\n const searchMode =\n leaf.resolver?.type === \"dynamic\" && leaf.resolver.inputType === \"search\";\n // Search-first with nothing listed yet: `search` IS the primary move, and\n // `choose` (an empty choice set) is omitted rather than offered as a menu\n // entry with nothing behind it.\n if (\n searchMode &&\n page.position.search === undefined &&\n page.items.length === 0\n ) {\n const actions: ControllerAffordance[] = multiple\n ? [AFFORDANCE.search]\n : [AFFORDANCE.search, AFFORDANCE.custom];\n if (!leaf.required) actions.push(AFFORDANCE.skip);\n return actions;\n }\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 (searchMode) actions.push(AFFORDANCE.search);\n if (page.nextCursor) actions.push(AFFORDANCE.nextPage);\n if (page.position.previousCursors.length > 0)\n actions.push(AFFORDANCE.previousPage);\n if (!leaf.required) actions.push(AFFORDANCE.skip);\n return actions;\n}\n\n/** A labeled field (an object field carrying its upstream title) renders as\n * \"Channel (required):\" / \"Channel (optional):\"; a bare parameter (no label)\n * returns undefined so the caller falls back to its own default. */\nfunction labeledMessage(leaf: Leaf): string | undefined {\n if (!leaf.label) return undefined;\n return `${leaf.label} (${leaf.required ? \"required\" : \"optional\"}):`;\n}\n\n/** Render a dynamic select question from one fetched page (choices via the\n * resolver's `prompt`, run over that page's items only). */\nexport function selectQuestion(\n leaf: Leaf,\n path: ControllerPath,\n input: Record<string, unknown>,\n page: ControllerListingPage,\n context?: unknown,\n): ControllerQuestion {\n const resolver =\n leaf.resolver?.type === \"dynamic\" ? leaf.resolver : undefined;\n const config: PromptConfig | undefined = resolver?.prompt?.({\n items: page.items,\n input: mergeInput(input, leaf.extraInput),\n context,\n });\n const multiple = config?.type === \"checkbox\";\n return {\n type: \"select\",\n path,\n // A labeled field's title beats the resolver's message: per-field\n // resolvers are shared across fields (one choices-fetcher for every\n // field), so only the leaf knows which field is being asked.\n message: labeledMessage(leaf) ?? config?.message ?? `Select ${leaf.name}:`,\n choices: (config?.choices ?? []).map(toChoice),\n ...(multiple ? { multiple: true } : {}),\n ...(config?.notes?.length ? { notes: config.notes } : {}),\n ...(page.position.search !== undefined\n ? { search: page.position.search }\n : {}),\n ...(resolver?.placeholder ? { placeholder: resolver.placeholder } : {}),\n page: {\n generation: page.position.generation,\n index: page.position.previousCursors.length,\n },\n actions: selectActions(leaf, page, 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 failed\n * position is kept in `state.pagination` so `retry` replays it. */\nexport function 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 path: state.current ?? [],\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 the pagination coordinates to\n * carry forward. */\nexport async function buildQuestion(\n leaf: Leaf,\n path: ControllerPath,\n input: Record<string, unknown>,\n): Promise<{\n question: ControllerQuestion;\n pagination?: ControllerPagination;\n}> {\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\n // prompt. (Search-mode fetches nothing yet: `fetchListing` is search-first\n // and returns the empty page until a term exists, so the host leads with a\n // term prompt. Bounded selects list eagerly so the host can type-to-filter\n // the loaded choices locally.)\n if (resolver?.type === \"dynamic\") {\n const context = await resolveContext(leaf, input);\n const page = await fetchListing(leaf, input, firstPagePosition(), context);\n return {\n question: selectQuestion(leaf, path, input, page, context),\n pagination: toPagination(page),\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 path,\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; every other kind\n // was handled above or auto-settles in the walk). `search` is an affordance,\n // not a text-input subtype, so it maps to plain text here.\n const textSource = resolver?.type === \"static\" ? resolver : undefined;\n const inputType =\n textSource?.inputType && textSource.inputType !== \"search\"\n ? textSource.inputType\n : \"text\";\n const actions: ControllerAffordance[] = [AFFORDANCE.custom];\n if (optional) actions.push(AFFORDANCE.skip);\n return {\n question: {\n type: \"input\",\n path,\n // The optional marker makes Enter-to-pass discoverable on a bare\n // parameter; a labeled field carries its marker via labeledMessage.\n message:\n labeledMessage(leaf) ??\n `Enter ${leaf.name}${optional ? \" (optional)\" : \"\"}:`,\n inputType,\n placeholder: textSource?.placeholder,\n actions,\n },\n };\n}\n\n/** The array's add/done question (the `array_items` gate). `done` is offered\n * once the count is within range (the decision is only reached at\n * `min ≤ count < max`). */\nexport function arrayItemsQuestion(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 path: t.path,\n message: `Add ${t.path[t.path.length - 1]}[${t.count}]?`,\n container: \"array\",\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/** A record's add-another-entry decision (the `record_entries` gate). `add`\n * collects one more key/value entry; `done` (offered once `count ≥ min`)\n * finishes the record. */\nexport function recordEntriesQuestion(t: {\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n}): ControllerQuestion {\n const actions: ControllerAffordance[] = [\n affordance(AFFORDANCE.add, \"Add another entry\"),\n ];\n if (t.count >= t.min) {\n actions.push(affordance(AFFORDANCE.done, \"Finish the entries\"));\n }\n return {\n type: \"collection\",\n path: t.path,\n message: `Add another ${t.path[t.path.length - 1]} entry? (${t.count} so far)`,\n container: \"record\",\n count: t.count,\n min: t.min,\n ...(Number.isFinite(t.max) ? { max: t.max } : {}),\n actions,\n };\n}\n\n/** The `object_optional` gate: one \"provide this optional object at all?\" ask,\n * fired BEFORE the object's fields are fetched so declining costs no I/O. Same\n * question type and add/done actions as the collection loops, worded for the\n * whole-object decision. */\nexport function objectOptionalQuestion(\n path: ControllerPath,\n): ControllerQuestion {\n return {\n type: \"collection\",\n path,\n message: `Add ${path[path.length - 1]}?`,\n container: \"object\",\n actions: [\n affordance(AFFORDANCE.add, \"Provide values for these fields\"),\n affordance(AFFORDANCE.done, \"Skip these fields\"),\n ],\n };\n}\n\n/** The `object_optional_properties` gate: the one bulk ask over an object's\n * remaining optional fields. Required fields were asked individually; the\n * optionals are offered as a batch (`add` walks them, `done` finishes the\n * object). */\nexport function objectOptionalPropertiesQuestion(\n path: ControllerPath,\n pending: Leaf[],\n): ControllerQuestion {\n return {\n type: \"collection\",\n path,\n // The prompt and its context ride separately so a host renders the info\n // line above the confirm without composing any text of its own.\n message: \"Would you like to configure optional fields?\",\n description: `There are ${pending.length} optional field(s) available.`,\n container: \"object\",\n // The gated fields' projection, so a smart host can show WHAT `add` would\n // walk (or render a form section) instead of a blind yes/no.\n fields: pending.map((leaf) => ({\n key: leaf.name,\n ...(leaf.label ? { label: leaf.label } : {}),\n ...(leaf.valueType ? { valueType: leaf.valueType } : {}),\n })),\n actions: [\n affordance(AFFORDANCE.add, \"Configure the optional fields\"),\n affordance(AFFORDANCE.done, \"Skip the optional fields\"),\n ],\n };\n}\n","import type { Leaf } from \"./plan\";\nimport {\n arrayInfoAt,\n autoSettles,\n childrenAt,\n clone,\n coerce,\n fetchListing,\n firstPagePosition,\n getAtPath,\n isSettled,\n leafAt,\n mergeInput,\n pathToKey,\n recordInfoAt,\n remember,\n resolveContext,\n setAtPath,\n settle,\n toPagination,\n validationError,\n type EngineContext,\n} from \"./engine\";\nimport {\n buildQuestion,\n arrayItemsQuestion,\n failedResult,\n objectOptionalQuestion,\n objectOptionalPropertiesQuestion,\n recordEntriesQuestion,\n selectQuestion,\n} from \"./questions\";\nimport type {\n ControllerAction,\n ControllerIssue,\n ControllerPagination,\n ControllerListingPosition,\n ControllerResult,\n ControllerState,\n ControllerPath,\n} from \"./types\";\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, an array's add/done\n * decision, or an optional object's opt-in gate. */\ntype Target =\n | { type: \"leaf\"; path: ControllerPath; leaf: Leaf }\n | {\n type: \"array_items\";\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n }\n | { type: \"object_optional\"; path: ControllerPath; leaf: Leaf }\n | {\n type: \"object_optional_properties\";\n path: ControllerPath;\n pending: Leaf[];\n }\n // A record's add/done decision (open-keyed object entries).\n | {\n type: \"record_entries\";\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n }\n // Force one more record entry (below `minEntries`): ask its key directly.\n | { type: \"record_key\"; path: ControllerPath; leaf: Leaf };\n\n/** The settled-set key that records \"the optionals gate for the object at\n * `path` was accepted\" (so it isn't re-asked). `?` can't appear in a field\n * key, so the marker can't collide with a real child path. */\nconst optionalsMarker = (path: ControllerPath): string =>\n `${pathToKey(path)}?optionals`;\n\n/** Keys a user must never set as a record entry: they name prototype members,\n * so emitting them into the resolved value would let a downstream consumer that\n * merges via `[[Set]]` (`Object.assign`, a naive `for..in`) pollute a prototype.\n * Rejected at the record-key boundary, the only user-supplied key source.\n * `setAtPath`'s own-property writes separately keep the resolution tree safe. */\nconst UNSAFE_RECORD_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\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). A\n // settled item is already complete — e.g. its optionals gate was declined —\n // so descending into it would re-offer the same question forever.\n if (len > 0 && (itemType === \"object\" || itemType === \"array\")) {\n const itemPath = [...path, len - 1];\n if (!isSettled(state, itemPath)) {\n const inner = await findNext(ctx, state, itemPath);\n if (inner) return inner;\n }\n }\n if (len < min) return descendItem(ctx, state, path, len, item);\n if (len < max) return { type: \"array_items\", path, count: len, min, max };\n settle(state, path); // at max\n return null;\n}\n\n/** Walk the record at `path` (an object resolver's open `additionalKeys`\n * entries): force entries below `minEntries` by asking a key, offer add/done in\n * range, auto-finish at `maxEntries`. A non-interactive caller takes the\n * provided object as-is. Only complete entries are ever present here — the\n * key→value collection happens inside `step`, not across `findNext` passes. */\nasync function findInRecord(\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 object as-is (validation checks bounds)\n return null;\n }\n const { min, max, keyLeaf, fixedKeys } = await recordInfoAt(\n ctx,\n path,\n state.resolved,\n );\n const container = getAtPath(state.resolved, path) as Record<string, unknown>;\n // Count only the open entries, not any fixed `properties` sharing the object.\n // `fixedKeys` comes from static knowledge, so no per-pass field fetch.\n const fixed = new Set(fixedKeys);\n const count = Object.keys(container).filter((k) => !fixed.has(k)).length;\n if (count < min) return { type: \"record_key\", path, leaf: keyLeaf };\n if (count < max) return { type: \"record_entries\", path, count, 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 slot type, 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 slotType = seedItemSlot(state, itemPath, item);\n if (slotType === \"object\") return findNext(ctx, state, itemPath);\n if (slotType === \"array\") return findInArray(ctx, state, itemPath);\n return { type: \"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, an array decision, or an object gate. Inside an object\n * (non-root), fields are walked required-first, and the remaining optionals\n * are offered as one batch (the optionals gate) rather than field by field. */\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 const children = await childrenAt(ctx, path, state.resolved);\n const inObject = path.length > 0;\n // Required-first inside an object (stable within each group); the root\n // keeps the plan's topo order.\n const ordered = inObject\n ? [\n ...children.filter((c) => c.required),\n ...children.filter((c) => !c.required),\n ]\n : children;\n // Only fields the walk would actually ask matter to the gates: fields that\n // auto-settle (constant, info) and resolver-less optionals (interactive\n // omits them) never trigger, count toward, or hold up a gate.\n const asksUser = (c: Leaf): boolean =>\n c.resolver ? !autoSettles(c.resolver) : c.required;\n const isPendingChild = (c: Leaf): boolean =>\n container[c.name] === undefined && !isSettled(state, [...path, c.name]);\n const hasAskableRequired = children.some((c) => c.required && asksUser(c));\n for (const leaf of ordered) {\n const childPath = [...path, leaf.name];\n // Defer any child — leaf OR composite — until the siblings it requires are\n // DONE: valued, or settled without a value (a no-auth app's connection\n // auto-resolves { resolvedValue: undefined }; the dependent proceeds with\n // that key absent). A later pass revisits once the dependency lands.\n // Top-level params are already topo-ordered\n // (planParameters), but nested object/array fields are walked in\n // declaration order, so the gate must run before descending into them too,\n // not just on the leaf branch. A nested field's requirement may also name\n // a TOP-LEVEL parameter (a choices fetcher needing `app`), so the root's\n // resolved/settled state satisfies it too.\n if (\n !leaf.requires.every((r) => {\n // An absolute path names exactly one place, so there is nothing to\n // disambiguate: read it and settle-check it where it actually lives.\n // Any settled ANCESTOR counts too. Declining an optional object settles\n // the object, not the leaf inside it, so checking only the full path\n // would defer the dependent on every pass and the walk would end with\n // nothing asked. The bare branch below has always had this via its\n // container check; a path has to say it explicitly.\n if (typeof r !== \"string\") {\n if (getAtPath(state.resolved, [...r]) !== undefined) return true;\n return r.some((_, index) => isSettled(state, r.slice(0, index + 1)));\n }\n return (\n container[r] !== undefined ||\n getAtPath(state.resolved, [r]) !== undefined ||\n isSettled(state, [...path, r]) ||\n isSettled(state, [r])\n );\n })\n ) {\n continue;\n }\n // The optionals gate: once an object's required fields are ALL done, the\n // first still-askable optional field surfaces ONE batch decision instead\n // of a prompt per field. Never while a required field is pending — even\n // one deferred on unmet requires — since declining the gate would silently\n // drop its ask. Only for objects with askable required fields: an\n // all-optional object's opt-in gate already asked for this consent (and\n // required constants don't count; they settle themselves). Never inside an\n // array item: the user opted in at the array's add question, so its\n // optional fields are asked directly rather than behind a second consent.\n const inArrayItem = path.some((segment) => typeof segment === \"number\");\n if (\n inObject &&\n !inArrayItem &&\n state.interactive &&\n hasAskableRequired &&\n !leaf.required &&\n asksUser(leaf) &&\n isPendingChild(leaf) &&\n !state.settled.includes(optionalsMarker(path)) &&\n !children.some((c) => c.required && asksUser(c) && isPendingChild(c))\n ) {\n const pending = ordered.filter(\n (c) => !c.required && asksUser(c) && isPendingChild(c),\n );\n return { type: \"object_optional_properties\", path, pending };\n }\n if (leaf.resolver?.type === \"object\") {\n // Settled means the walk is done with it: the opt-in gate declined it\n // (valueless) or the optionals gate finished it (valued).\n if (isSettled(state, childPath)) continue;\n if (getAtPath(state.resolved, childPath) == null) {\n // No opt-in gate inside an array item (the same rule that suppresses\n // the optionals gate there): the item's fields are walked directly,\n // and skipping them all still omits the container (below).\n if (!leaf.required && !inArrayItem) {\n // Optional container with nothing provided: interactive asks the\n // one-time opt-in gate; headless omits it. Either way the field\n // fetch (`getProperties`) never runs for a declined container.\n if (!state.interactive) {\n settle(state, childPath);\n continue;\n }\n return { type: \"object_optional\", path: childPath, leaf };\n }\n setAtPath(state.resolved, childPath, {});\n }\n // A child object's own open-keyed entries are collected by the recursive\n // `findNext(childPath)` itself (node-level, below), not here — so an object\n // reached any other way (an array item, an object-typed record value) gets\n // them too, not just a parent's fixed child.\n const inner = await findNext(ctx, state, childPath);\n if (inner) return inner;\n // An OPTIONAL container that FINISHES the walk empty is omitted, the\n // same as declining its gate: accepting \"Add inputs?\" and then skipping\n // every field means no inputs, not `inputs: {}`. A null\n // walk result alone is not \"finished\" — every child may just be\n // deferred on unmet requires — so the omission also demands no child be\n // pending; a deferred container stays in place, unsettled, and is\n // revisited once its dependency lands.\n if (!leaf.required) {\n const value = getAtPath(state.resolved, childPath);\n if (\n value !== null &&\n typeof value === \"object\" &&\n Object.keys(value as Record<string, unknown>).length === 0\n ) {\n const grandchildren = await childrenAt(\n ctx,\n childPath,\n state.resolved,\n );\n const pending = grandchildren.some(\n (c) =>\n (value as Record<string, unknown>)[c.name] === undefined &&\n !isSettled(state, [...childPath, c.name]),\n );\n if (!pending) {\n delete container[leaf.name];\n settle(state, childPath);\n }\n }\n }\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 { type: \"leaf\", path: childPath, leaf };\n }\n // Open-keyed entries (an `additionalKeys` object) resolve after this node's\n // fixed children: force entries below min, then offer add/done. Handled at\n // the node itself, keyed off its own resolver, so it fires wherever `findNext`\n // enters an object — a parent's child, an array item, or an object-typed\n // record value — not only in the parent loop above. `leafAt` is the same\n // resolver lookup `recordInfoAt` does and returns undefined for the root, so\n // the root (never `additionalKeys`) skips it.\n //\n // Known limitation (only reachable by a shape nothing ships yet): if this\n // object also has fixed OPTIONAL properties, declining their gate settles the\n // path, so `isSettled` short-circuits the record phase. Fixing that needs the\n // object's phases (optionals vs. open entries) to settle independently.\n if (inObject && !isSettled(state, path)) {\n const self = await leafAt(ctx, path, state.resolved);\n if (self?.resolver?.type === \"object\" && self.resolver.additionalKeys) {\n const rec = await findInRecord(ctx, state, path);\n if (rec) return rec;\n }\n }\n return null;\n}\n\n/** Build the question for a leaf and set it as the outstanding one, or, when the\n * fetch throws, a `failed` result whose `retry` replays the initial first-page\n * fetch. `gate` marks a non-value question (a record key) so `step` routes the\n * answer accordingly; omitting it clears any gate for an ordinary value leaf. */\nasync function askLeaf(\n state: ControllerState,\n path: ControllerPath,\n leaf: Leaf,\n opts: { gate?: ControllerState[\"gate\"]; error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n state.current = path;\n if (opts.gate) state.gate = opts.gate;\n else delete state.gate;\n try {\n const { question, pagination } = await buildQuestion(\n leaf,\n path,\n state.resolved,\n );\n state.pagination = pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question,\n ...(opts.error ? { error: opts.error } : {}),\n },\n };\n } catch (error) {\n state.pagination = failedPagination(undefined, firstPagePosition());\n return failedResult(state, leaf.name, error);\n }\n}\n\n/** Ask for a record entry's key: an `askLeaf` under the `record_key` gate, so\n * `step` routes the answer to key-collection rather than a tree write. */\nasync function askRecordKey(\n state: ControllerState,\n path: ControllerPath,\n keyLeaf: Leaf,\n opts: { error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n return askLeaf(state, path, keyLeaf, { gate: \"record_key\", ...opts });\n}\n\n/** Auto-resolve a fresh leaf WITHOUT asking, per the mode-independent contract:\n * a constant pins its value, an info leaf resolves nothing, and a dynamic\n * resolver's `tryResolveWithoutPrompt` may settle it (a configured default, a\n * no-auth app's absent connection). Returns true when it settled the leaf, so\n * the caller advances instead of prompting. `PromptConfig.validate` is\n * intentionally NOT run here: the resolver produced the value itself, so it is\n * not a user answer to re-validate. Every fresh-leaf ask (top-level walk, added\n * array item, record value) runs this first so they honor the same gates. */\nasync function autoResolveLeaf(\n state: ControllerState,\n path: ControllerPath,\n leaf: Leaf,\n): Promise<boolean> {\n const resolver = leaf.resolver;\n if (resolver && autoSettles(resolver)) {\n if (resolver.type === \"constant\")\n setAtPath(state.resolved, path, resolver.value);\n settle(state, path);\n return true;\n }\n const auto =\n resolver?.type === \"dynamic\"\n ? await resolver.tryResolveWithoutPrompt?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n })\n : undefined;\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 it isn't re-asked.\n if (auto.resolvedValue !== undefined)\n setAtPath(state.resolved, path, auto.resolvedValue);\n settle(state, path);\n return true;\n }\n return false;\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.gate;\n delete state.pagination;\n return { state, result: finalize(ctx, state.resolved) };\n }\n if (target.type === \"array_items\") {\n state.current = target.path;\n state.gate = \"array_items\";\n delete state.pagination;\n return {\n state,\n result: { status: \"ask\", question: arrayItemsQuestion(target) },\n };\n }\n if (target.type === \"object_optional\") {\n state.current = target.path;\n state.gate = \"object_optional\";\n delete state.pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question: objectOptionalQuestion(target.path),\n },\n };\n }\n if (target.type === \"object_optional_properties\") {\n state.current = target.path;\n state.gate = \"object_optional_properties\";\n delete state.pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question: objectOptionalPropertiesQuestion(\n target.path,\n target.pending,\n ),\n },\n };\n }\n if (target.type === \"record_entries\") {\n state.current = target.path;\n state.gate = \"record_entries\";\n delete state.pagination;\n return {\n state,\n result: { status: \"ask\", question: recordEntriesQuestion(target) },\n };\n }\n if (target.type === \"record_key\") {\n return askRecordKey(state, target.path, target.leaf);\n }\n const { path, leaf } = target;\n\n // Auto-settle / skip-check (both modes, any depth): a constant or info leaf,\n // or a dynamic resolver that can answer itself, settles without a question.\n if (await autoResolveLeaf(state, path, leaf)) continue;\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, then advance to the first interaction (or\n * completion). A provided parameter is the caller saying \"use exactly this\n * value\": it settles up front, whatever its resolver type, so resolution only\n * fills the holes the caller left and never runs a provided parameter's\n * resolver. Scalars would be done by presence anyway; the settle matters for\n * composites: the walk must not descend into a provided object or array (no\n * field fetch, no optionals gate, no add/done loop, no nested constant\n * injection). Constants for unprovided parameters still auto-settle inside\n * `advance`. */\nexport async function start(\n ctx: EngineContext,\n input: Record<string, unknown> = {},\n interactive = true,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const state: ControllerState = {\n method: ctx.method,\n resolved: { ...input },\n settled: [],\n interactive,\n };\n for (const [name, value] of Object.entries(input)) {\n if (value !== undefined) settle(state, [name]);\n }\n return advance(ctx, state);\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.gate;\n delete state.pagination;\n return { state, result: { status: \"cancelled\" } };\n }\n\n // Record key collection: the answer is an entry key that opens a value slot,\n // not a write at `state.current`, so handle it before the generic leaf path.\n // The value that follows is an ordinary leaf and flows through the code below.\n if (state.gate === \"record_key\") {\n return stepRecordKey(ctx, state, action);\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 // `state.current` is engine-set to a resolvable path (a leaf, an array item,\n // or a record value), so a missing leaf is a broken invariant, not host\n // input — fail loud rather than writing the raw answer straight to the tree.\n if (!leaf) {\n throw new Error(\n `no resolver for the outstanding question at \"${pathToKey(path)}\"`,\n );\n }\n\n // Stay-on-parameter actions: refine the listing and re-ask.\n if (\n action.type === \"search\" ||\n action.type === \"next_page\" ||\n action.type === \"previous_page\" ||\n action.type === \"retry\"\n ) {\n return refine(ctx, state, leaf, path, action);\n }\n\n // Container decision actions: which decision is outstanding is recorded on\n // the state (`state.gate`), never inferred from value presence or resolver\n // shape.\n if (action.type === \"add\" || action.type === \"done\") {\n const gate = state.gate;\n // A container decision without an outstanding gate is a host bug (e.g.\n // answering a leaf question with add); fail loud instead of silently\n // settling the leaf or dying inside the array machinery.\n if (!gate) {\n throw new Error(\n `action \"${action.type}\" is not supported here: no container decision is outstanding`,\n );\n }\n delete state.current;\n delete state.gate;\n delete state.pagination;\n if (action.type === \"done\") {\n // Array: finish (validation checks min). Entry gate: decline the whole\n // container, valueless, so the walk never fetches its fields. Optionals\n // gate: finish the (valued) object, skipping its remaining optionals.\n settle(state, path);\n return advance(ctx, state);\n }\n if (gate === \"object_optional\") {\n // Accepted: seed the container and let the walk descend into its fields.\n setAtPath(state.resolved, path, {});\n return advance(ctx, state);\n }\n if (gate === \"object_optional_properties\") {\n // Accepted: remember it so the walk asks the optional fields instead of\n // re-offering the gate.\n remember(state, optionalsMarker(path));\n return advance(ctx, state);\n }\n if (gate === \"record_entries\") {\n // Accepted: start a new entry by asking its key.\n const { keyLeaf } = await recordInfoAt(ctx, path, state.resolved);\n return askRecordKey(state, path, keyLeaf);\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: auto-resolve if the contract allows (a constant/auto item\n // settles silently), else ask it. Composite item: seed its slot and let the\n // walk (advance → findNext) descend into it.\n if (seedItemSlot(state, itemPath, item) === \"leaf\") {\n if (await autoResolveLeaf(state, itemPath, item))\n return advance(ctx, state);\n return askLeaf(state, itemPath, item);\n }\n return advance(ctx, state);\n }\n\n // The mirror of the gateless add/done guard: a gate question accepts only\n // add/done. A value answer here would overwrite the container with a scalar\n // (silent until the final parse rejects it); a skip would settle the\n // container by accident.\n if (state.gate) {\n throw new Error(\n `action \"${action.type}\" is not supported here: a container decision (${state.gate}) is outstanding`,\n );\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 let error: string | null;\n try {\n error = await validationError(leaf, action.value, state);\n } catch (thrown) {\n // A fetching validate failed (e.g. network), which is a lookup failure,\n // not a rejection: offer retry/cancel instead of re-asking with a\n // misleading \"invalid value\" message.\n return failedResult(state, leaf.name, thrown);\n }\n if (error) {\n // A dynamic select re-fetches its current page (`resolveContext` and the\n // fetch both hit the resolver's sources, so both degrade to failed/retry\n // rather than escaping step() as a raw throw); a plain leaf just re-asks.\n if (state.pagination && leaf.resolver?.type === \"dynamic\") {\n return renderPageAt(state, leaf, path, state.pagination.position, {\n error,\n });\n }\n return askLeaf(state, path, leaf, { error });\n }\n setAtPath(state.resolved, path, coerce(leaf, action.value)); // 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(\n `action \"${(action as ControllerAction).type}\" is not supported here`,\n );\n }\n\n delete state.current;\n delete state.pagination;\n return advance(ctx, state);\n}\n\n/** Fetch and render the page at `position` for a dynamic leaf's select, keeping\n * its coordinates on the state; on fetch failure, record the position to replay\n * and return a `failed` result. `error` decorates the rendered question (the\n * re-ask after a rejected pick). The state holds only the position, so the page\n * is re-fetched statelessly rather than rebuilt — a search-mode select keeps the\n * results and term the answer came from instead of resetting to search-first. */\nasync function renderPageAt(\n state: ControllerState,\n leaf: Leaf,\n path: ControllerPath,\n position: ControllerListingPosition,\n opts: { error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n try {\n const context = await resolveContext(leaf, state.resolved);\n const page = await fetchListing(leaf, state.resolved, position, context);\n state.pagination = toPagination(page);\n return {\n state,\n result: {\n status: \"ask\",\n question: selectQuestion(leaf, path, state.resolved, page, context),\n ...(opts.error ? { error: opts.error } : {}),\n },\n };\n } catch (error) {\n state.pagination = failedPagination(state.pagination, position);\n return failedResult(state, leaf.name, error);\n }\n}\n\n/** Handle the actions that stay on the current leaf: `search` (exact-match\n * short-circuit, else restart the listing by term under a new generation),\n * `next_page`/`previous_page` (move the one-page window along the cursor\n * trail), and `retry` (replay the failed position). */\nasync function refine(\n ctx: EngineContext,\n state: ControllerState,\n leaf: Leaf,\n path: ControllerPath,\n action:\n | { type: \"search\"; term: string }\n | { type: \"next_page\" }\n | { type: \"previous_page\" }\n | { type: \"retry\" },\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const position = positionAfter(state.pagination, action);\n if (action.type === \"search\") {\n try {\n const exact =\n leaf.resolver?.type === \"dynamic\"\n ? await leaf.resolver.tryResolveFromSearch?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n search: action.term,\n })\n : undefined;\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.pagination;\n return advance(ctx, state);\n }\n } catch (error) {\n // Keep the current position; `retry` replays exactly what failed.\n state.pagination = failedPagination(state.pagination, position);\n return failedResult(state, leaf.name, error);\n }\n }\n return renderPageAt(state, leaf, path, position);\n}\n\n/** Collect a record entry's key — the one bespoke record step, since a key\n * can't be a leaf in the value tree. Validate it's a non-empty, unused key,\n * then open its value at `[...path, key]` as an ordinary leaf via `askLeaf`, so\n * the value resolves through the normal machinery (refine, validate, coerce) —\n * the same path an array item takes. A `skip` abandons the in-progress entry. */\nasync function stepRecordKey(\n ctx: EngineContext,\n state: ControllerState,\n action: ControllerAction,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const path = state.current;\n if (!path)\n throw new Error(\"record key step called with no outstanding question\");\n const { keyLeaf, valueLeaf } = await recordInfoAt(ctx, path, state.resolved);\n\n if (action.type === \"skip\") {\n delete state.gate;\n delete state.current;\n delete state.pagination;\n return advance(ctx, state);\n }\n if (action.type !== \"custom\" && action.type !== \"choose\") {\n throw new Error(\n `action \"${action.type}\" is not supported while entering a record key`,\n );\n }\n const raw = Array.isArray(action.value) ? action.value[0] : action.value;\n const entryKey = String(coerce(keyLeaf, raw));\n if (entryKey.trim() === \"\") {\n return askRecordKey(state, path, keyLeaf, { error: \"A key is required.\" });\n }\n // Keep prototype-member names out of the resolved value entirely: it flows to\n // consumers we don't control (the SDK method, serialization, the CLI's\n // `Object.assign`), and a `[[Set]]`-based merge there would pollute a\n // prototype. (`setAtPath` keeps our own tree safe; this guards what we emit.)\n if (UNSAFE_RECORD_KEYS.has(entryKey)) {\n return askRecordKey(state, path, keyLeaf, {\n error: `\"${entryKey}\" is not an allowed key.`,\n });\n }\n const container = getAtPath(state.resolved, path) as Record<string, unknown>;\n if (Object.prototype.hasOwnProperty.call(container, entryKey)) {\n return askRecordKey(state, path, keyLeaf, {\n error: `\"${entryKey}\" is already set.`,\n });\n }\n // Hand the value to the normal leaf path; the key is now carried by the path.\n // Auto-resolve it first so a constant/auto value settles without a prompt,\n // exactly as a top-level leaf or array item would.\n const valuePath = [...path, entryKey];\n if (await autoResolveLeaf(state, valuePath, valueLeaf)) {\n return advance(ctx, state);\n }\n return askLeaf(state, valuePath, valueLeaf);\n}\n\n/** The one pagination shape every fetch failure writes: the current coordinates\n * survive (position and, when known, `nextCursor`) and `retryPosition`\n * records the fetch to replay. */\nfunction failedPagination(\n pagination: ControllerPagination | undefined,\n retryPosition: ControllerListingPosition,\n): ControllerPagination {\n return {\n position: pagination?.position ?? firstPagePosition(),\n ...(pagination?.nextCursor !== undefined\n ? { nextCursor: pagination.nextCursor }\n : {}),\n retryPosition,\n };\n}\n\n/** The position a refine action moves to: `search` restarts the listing under\n * a new generation (same-term searches still refetch); `next_page` pushes the\n * current page's cursor onto the trail; `previous_page` pops it; `retry`\n * replays the failed position if one is recorded, else the current page's\n * own. */\nfunction positionAfter(\n pagination: ControllerPagination | undefined,\n action:\n | { type: \"search\"; term: string }\n | { type: \"next_page\" }\n | { type: \"previous_page\" }\n | { type: \"retry\" },\n): ControllerListingPosition {\n const current = pagination?.position ?? firstPagePosition();\n switch (action.type) {\n case \"search\":\n return firstPagePosition({\n search: action.term,\n generation: current.generation + 1,\n });\n case \"next_page\": {\n // Without a next cursor (host raced past the last page) re-fetch the\n // current page rather than fabricating one.\n if (pagination?.nextCursor == null) return current;\n return {\n ...(current.search !== undefined ? { search: current.search } : {}),\n pageCursor: pagination.nextCursor,\n previousCursors: [...current.previousCursors, current.pageCursor],\n generation: current.generation,\n };\n }\n case \"previous_page\": {\n // With an empty trail (host answered previous_page on page one) stay put.\n if (current.previousCursors.length === 0) return current;\n return {\n ...(current.search !== undefined ? { search: current.search } : {}),\n pageCursor: current.previousCursors[current.previousCursors.length - 1],\n previousCursors: current.previousCursors.slice(0, -1),\n generation: current.generation,\n };\n }\n case \"retry\":\n return pagination?.retryPosition ?? current;\n }\n}\n","import type { Plugin } from \"../types/plugin\";\nimport type { CoreOptions } from \"./core-options\";\nimport { logDeprecation } from \"./logging\";\n\n/**\n * Register kitcore-level configuration by writing the options to\n * `context.core`; the method boundary falls back to that path when no\n * `kitcore/coreOptions` configuration value exists.\n *\n * @deprecated Inject the `CoreOptions` bag under `CORE_OPTIONS_ID` via\n * `createSdk(root, { configuration })` instead. This factory logs a runtime\n * deprecation and will be removed in a release after the warning ships.\n */\nexport function createCorePlugin(\n options: CoreOptions,\n): Plugin<object, { context: { core: CoreOptions } }> {\n logDeprecation(\n \"createCorePlugin() is deprecated. Inject the options under CORE_OPTIONS_ID via createSdk's configuration instead.\",\n );\n return () => ({\n context: {\n core: options,\n },\n });\n}\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { authorizeHttpRequestPlugin } from \"./authorize-http-request\";\nimport { dispatchHttpRequestPlugin } from \"./dispatch-http-request\";\nimport { prepareHttpRequestPlugin } from \"./prepare-http-request\";\nimport { receiveHttpResponsePlugin } from \"./receive-http-response\";\nimport type { AttemptHttpRequestInput, HttpResponse } from \"./types\";\n\n/**\n * One physical attempt: prepare, authorize, dispatch, receive.\n *\n * This exists as its own stage to give the ATTEMPT scope a seam. See\n * {@link AttemptHttpRequestInput} for why the operation and the attempt are\n * different lifecycles, and why re-issuing a request has to wrap here rather\n * than around `sendHttpRequest`.\n *\n * Do not fold this back into `sendHttpRequest` to save an indirection: doing so\n * removes the only boundary below `initializeHttpRequest`, and a retry wrap\n * would then re-initialize and mint a fresh `operationId` per attempt.\n */\nexport const attemptHttpRequestPlugin = defineMethod({\n name: \"attemptHttpRequest\",\n namespace: \"kitcore\",\n imports: [\n declareDefault({ plugin: prepareHttpRequestPlugin }),\n declareDefault({ plugin: authorizeHttpRequestPlugin }),\n declareDefault({ plugin: dispatchHttpRequestPlugin }),\n declareDefault({ plugin: receiveHttpResponsePlugin }),\n ],\n inputSchema: z.custom<AttemptHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input, imports }): Promise<HttpResponse> => {\n const { attempt } = input;\n const preparedRequest = await imports.prepareHttpRequest({\n request: input.request,\n attempt,\n });\n const authorizedRequest = await imports.authorizeHttpRequest({\n request: preparedRequest,\n attempt,\n });\n const response = await imports.dispatchHttpRequest({\n request: authorizedRequest,\n attempt,\n });\n\n return imports.receiveHttpResponse({\n request: authorizedRequest,\n response,\n attempt,\n });\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport { CoreErrorCode, createCoreError } from \"../types/errors\";\nimport type { AuthorizeHttpRequestInput, HttpRequest } from \"./types\";\n\n/**\n * Name the scheme that went unclaimed, and NOTHING else off the reference.\n *\n * A reference is opaque, so its value can be anything a caller passes,\n * including a raw credential. The scheme is the half that identifies which\n * provider was supposed to claim it, and the only half safe to put in an error\n * that will be logged.\n *\n * Parsed here rather than through `normalizeConnection` on purpose. The\n * transport treats `connection` as an opaque string and the connections module\n * owns scheme semantics, including whatever default a head assigns to a bare\n * reference. Reaching for that rule here would join two modules that are\n * independent today, and would report an interpretation where this stage should\n * report what it actually saw on the request.\n */\nfunction describeUnclaimedConnection(connection: string): string {\n const delimiterIndex = connection.indexOf(\":\");\n if (delimiterIndex === -1) {\n return 'no auth provider claimed this connection, and it carries no \"scheme:\" prefix';\n }\n return `no auth provider claimed the \"${connection.slice(0, delimiterIndex)}\" connection scheme`;\n}\n\nexport const authorizeHttpRequestPlugin = defineMethod({\n name: \"authorizeHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<AuthorizeHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpRequest> => {\n const { connection } = input.request;\n if (connection != null) {\n throw createCoreError({\n code: CoreErrorCode.Unknown,\n message: `authorizeHttpRequest: ${describeUnclaimedConnection(connection)}, so the request was not sent.`,\n });\n }\n\n return input.request;\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type {\n DispatchHttpRequestInput,\n HttpFetchInit,\n HttpRequest,\n HttpResponse,\n} from \"./types\";\n\nfunction toFetchInput(request: HttpRequest) {\n const init: Record<string, unknown> = { ...request };\n const { url } = request;\n delete init.url;\n delete init.connection;\n return { url, init: init as HttpFetchInit };\n}\n\nexport const dispatchHttpRequestPlugin = defineMethod({\n name: \"dispatchHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<DispatchHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpResponse> => {\n const { url, init } = toFetchInput(input.request);\n return fetch(url, init);\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { HttpRequest, PrepareHttpRequestInput } from \"./types\";\n\nexport const prepareHttpRequestPlugin = defineMethod({\n name: \"prepareHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<PrepareHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpRequest> => input.request,\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { HttpResponse, ReceiveHttpResponseInput } from \"./types\";\n\nexport const receiveHttpResponsePlugin = defineMethod({\n name: \"receiveHttpResponse\",\n namespace: \"kitcore\",\n inputSchema: z.custom<ReceiveHttpResponseInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpResponse> => input.response,\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type {\n HttpOperationContext,\n HttpRequest,\n InitializeHttpRequestInput,\n} from \"./types\";\n\n/**\n * Whether this body can be sent a second time.\n *\n * An ALLOWLIST, not a check for streams. The single-use set is open: a web\n * `ReadableStream` is the obvious member, but undici also takes any async\n * iterable as a body, so `fs.createReadStream(...)`, `Readable.from(...)`, and\n * an async generator are all single-use too, and none of them look alike.\n * Naming the replayable types instead closes the set, because the replayable\n * ones are exactly what `BodyInit` defines.\n *\n * The two mistakes are not equal, which is what settles the direction. Only\n * `retryHttpRequest` reads this. A wrong \"no\" costs a retry that would have\n * worked. A wrong \"yes\" resends a consumed stream, and undici throws\n * `TypeError: Response body object should not be disturbed or locked`, turning\n * a legible 503 into a type error the caller cannot act on.\n *\n * A body from another realm fails `instanceof` and comes out non-replayable.\n * That is the harmless side of the same trade.\n */\nfunction isReplayableBody(body: InitializeHttpRequestInput[\"request\"][\"body\"]) {\n // A string, and anything else primitive fetch will stringify.\n if (body == null || typeof body !== \"object\") return true;\n return (\n (typeof Blob !== \"undefined\" && body instanceof Blob) || // File extends Blob\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" &&\n body instanceof URLSearchParams) ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) // every TypedArray, plus DataView\n );\n}\n\n/**\n * The seam where a caller's `url` becomes the string every stage below sees.\n *\n * Copies only when there is something to normalize. `sendHttpRequest` promises\n * that skipping input validation keeps the caller's object identity intact, so\n * a request that already carries a string url must come out the same object.\n */\nfunction withStringUrl(request: InitializeHttpRequestInput[\"request\"]) {\n return typeof request.url === \"string\"\n ? (request as HttpRequest)\n : { ...request, url: String(request.url) };\n}\n\n/**\n * Completes the operation context: normalizes the caller's request and records\n * whether its body can be sent again. Everything below this stage reads those\n * two facts off `attempt.operation`, and neither changes across retries.\n */\nexport const initializeHttpRequestPlugin = defineMethod({\n name: \"initializeHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<InitializeHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpOperationContext> => {\n const request = withStringUrl(input.request);\n\n return {\n ...input.operation,\n request,\n replayable: isReplayableBody(request.body),\n };\n },\n});\n","import { declareOptionalProperty, defineHook } from \"../model\";\nimport { attemptHttpRequestPlugin } from \"./attempt-http-request\";\nimport type { HttpFetchInit, HttpRequest, HttpResponse } from \"./types\";\n\n/**\n * Options for {@link retryHttpRequestPlugin}, supplied by id like every other\n * kitcore configuration value. Absent means the defaults below.\n */\nexport interface RetryHttpRequestOptions {\n /** Total attempts including the first. Default 3. */\n maxAttempts?: number;\n /** Refuse a delay longer than this and give up instead. Default 60 seconds. */\n maxDelayMilliseconds?: number;\n /** Statuses to retry on an idempotent method. Default 429, 500, 502, 503, 504. */\n retryStatuses?: readonly number[];\n /**\n * Statuses to retry on a NON-idempotent method. Default 429 only: a rate\n * limit rejects the request before the server does any work, so it is known\n * not to have executed. A 502 or 504 carries no such promise.\n */\n nonIdempotentRetryStatuses?: readonly number[];\n /** Methods safe to resend. Default the RFC 9110 idempotent set. */\n idempotentMethods?: readonly string[];\n /**\n * Retry when an attempt THROWS (a network failure) rather than answering.\n * Default false. A thrown request may still have reached the server, and\n * turning this on silently widens what gets resent, so it is a deliberate\n * choice rather than a default.\n */\n retryOnError?: boolean;\n}\n\nexport const RETRY_HTTP_REQUEST_OPTIONS_ID = \"kitcore/retryHttpRequestOptions\";\n\nexport const retryHttpRequestOptionsPluginRef = declareOptionalProperty<\n typeof RETRY_HTTP_REQUEST_OPTIONS_ID,\n RetryHttpRequestOptions\n>({ id: RETRY_HTTP_REQUEST_OPTIONS_ID });\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_MAX_DELAY_MILLISECONDS = 60_000;\nconst DEFAULT_RETRY_STATUSES = [429, 500, 502, 503, 504] as const;\nconst DEFAULT_NON_IDEMPOTENT_RETRY_STATUSES = [429] as const;\nconst DEFAULT_IDEMPOTENT_METHODS = [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"OPTIONS\",\n \"TRACE\",\n] as const;\nconst BASE_BACKOFF_MILLISECONDS = 1_000;\n/** Randomize up to this fraction of the delay, so many clients retrying the\n * same outage do not synchronize into a second thundering herd. */\nconst JITTER_FACTOR = 0.5;\n\n/**\n * `Retry-After` is either a delay in seconds or an HTTP date (RFC 9110), and\n * `X-RateLimit-Reset` is a Unix timestamp in seconds. Both are how a server\n * says WHEN to come back, which is strictly better than guessing.\n */\nfunction directedDelayMilliseconds(response: HttpResponse): number | undefined {\n const retryAfter = response.headers.get(\"retry-after\");\n if (retryAfter) {\n const seconds = Number.parseInt(retryAfter, 10);\n // Clamped like the date branch below. A negative `Retry-After` is a server\n // bug, and unclamped it passes the ceiling check and resends with no wait\n // at all, which is the opposite of what the header asked for.\n if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1_000);\n const date = Date.parse(retryAfter);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n }\n const reset = response.headers.get(\"x-ratelimit-reset\");\n if (reset) {\n const resetSeconds = Number.parseInt(reset, 10);\n if (!Number.isNaN(resetSeconds)) {\n return Math.max(0, resetSeconds * 1_000 - Date.now());\n }\n }\n return undefined;\n}\n\nfunction backoffMilliseconds(attemptNumber: number): number {\n const base = BASE_BACKOFF_MILLISECONDS * 2 ** (attemptNumber - 1);\n return base + Math.random() * JITTER_FACTOR * base;\n}\n\n/** The reason a caller gave for aborting, or a stand-in when the platform's\n * signal carries none. */\nfunction abortReason(signal: HttpFetchInit[\"signal\"]): unknown {\n const reason = (signal as { reason?: unknown } | null | undefined)?.reason;\n return reason ?? new Error(\"The request was aborted.\");\n}\n\n/**\n * Wait between attempts, unless the caller cancels first.\n *\n * An abort REJECTS rather than resolving, which is what makes cancellation\n * reach the retry loop at all. A resolved wait returns to the top of the loop\n * and sends the next attempt on a signal that is already aborted: that attempt\n * fails instantly, and with `retryOnError` the loop then spins through every\n * remaining attempt at zero delay. Rejecting instead ends the operation the way\n * `fetch` itself ends an aborted one.\n */\nfunction sleep(\n milliseconds: number,\n signal: HttpFetchInit[\"signal\"],\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(finish, milliseconds);\n function finish() {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n resolve();\n }\n function cancel() {\n clearTimeout(timer);\n reject(abortReason(signal));\n }\n if (signal?.aborted) return cancel();\n signal?.addEventListener(\"abort\", cancel, { once: true });\n });\n}\n\nfunction isIdempotent(\n request: HttpRequest,\n idempotentMethods: readonly string[],\n): boolean {\n const method = (request.method ?? \"GET\").toUpperCase();\n return idempotentMethods.includes(method);\n}\n\n/**\n * Re-issue a failed attempt, opt-in by composition.\n *\n * Wraps `attemptHttpRequest` rather than `sendHttpRequest`, which is what makes\n * the retry correct rather than merely present: `initializeHttpRequest` has\n * already run, so every attempt shares one `operationId`, and this can read\n * `attempt.operation.replayable` before resending.\n *\n * Three independent gates, each answering a different question:\n *\n * replayable CAN we resend? a consumed stream body cannot go out again\n * idempotent is it SAFE? a 504 may mean the server DID process it\n * status SHOULD we? policy, configurable\n *\n * The idempotency gate is the subtle one. A 429 is DIRECTED: the server told us\n * when to return, and a rate limit rejects before doing work, so it is known not\n * to have executed and any method may be resent. A 5xx is SPECULATIVE: no\n * instruction, and the request may have succeeded with the response lost, so\n * resending a POST would double-execute it.\n *\n * Exhausting the retries RETURNS the last response rather than throwing.\n * Deciding what counts as a failure belongs to `receiveHttpResponse` and a\n * head's error mapping; this decides only whether to try again.\n *\n * Cancellation is the one exception, and it throws. A caller who aborts wants\n * the operation to stop, not to receive whichever response the last attempt\n * happened to produce, so an abort during the wait ends the loop with the\n * caller's own reason.\n */\nexport const retryHttpRequestPlugin = defineHook({\n name: \"retryHttpRequest\",\n imports: [attemptHttpRequestPlugin, retryHttpRequestOptionsPluginRef],\n wrap: {\n attemptHttpRequest: async ({ input, imports, next }) => {\n const options: RetryHttpRequestOptions =\n imports.retryHttpRequestOptions ?? {};\n const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const maxDelayMilliseconds =\n options.maxDelayMilliseconds ?? DEFAULT_MAX_DELAY_MILLISECONDS;\n const idempotentMethods =\n options.idempotentMethods ?? DEFAULT_IDEMPOTENT_METHODS;\n const statuses = isIdempotent(input.request, idempotentMethods)\n ? (options.retryStatuses ?? DEFAULT_RETRY_STATUSES)\n : (options.nonIdempotentRetryStatuses ??\n DEFAULT_NON_IDEMPOTENT_RETRY_STATUSES);\n\n for (let attemptNumber = 1; ; attemptNumber++) {\n const attempt = {\n ...input.attempt,\n attemptNumber,\n // Per-attempt scratch: a cross-stage handoff from a previous attempt\n // describes a request that is no longer in flight. `operation` rides\n // through unchanged, so the id and the caller's original request are\n // the same for every attempt.\n state: {},\n };\n\n let response: HttpResponse | undefined;\n try {\n response = await next({ ...input, attempt });\n } catch (error) {\n if (\n !options.retryOnError ||\n !canRetry(\n attemptNumber,\n maxAttempts,\n input.attempt.operation.replayable,\n )\n ) {\n throw error;\n }\n await sleep(\n Math.min(backoffMilliseconds(attemptNumber), maxDelayMilliseconds),\n attempt.signal,\n );\n continue;\n }\n\n if (\n !statuses.includes(response.status) ||\n !canRetry(\n attemptNumber,\n maxAttempts,\n input.attempt.operation.replayable,\n )\n ) {\n return response;\n }\n\n // The ceiling means two different things depending on who set the\n // delay. A server asking for longer than we are willing to wait is a\n // refusal, not an invitation to ignore it and hammer sooner. Our own\n // backoff exceeding it is nobody's refusal, so it clamps.\n //\n // Treating both as a refusal turned the ceiling into an off switch:\n // `{ maxDelayMilliseconds: 500 }` reads as \"keep the waits short\", but\n // the first backoff is 1000 to 1500ms, so the loop returned after one\n // attempt and retry did nothing at all.\n const directed = directedDelayMilliseconds(response);\n if (directed != null && directed > maxDelayMilliseconds)\n return response;\n const delay = Math.min(\n directed ?? backoffMilliseconds(attemptNumber),\n maxDelayMilliseconds,\n );\n\n // Release the response we are about to drop, after every path that can\n // still return it. An unread body keeps its socket occupied: undici can\n // pause mid-message on a large response, and the connection stays open\n // until something drains or cancels it. `receiveHttpResponse` is\n // identity by default, so nothing guarantees a read.\n //\n // Before the sleep, not after, so an abort during the backoff releases\n // it too: `sleep` rejects, and the response would otherwise be dropped\n // unread. The rejection is swallowed because a `receiveHttpResponse`\n // wrap may have consumed the body already, which locks the stream and\n // makes `cancel()` throw.\n await response.body?.cancel().catch(() => {});\n await sleep(delay, attempt.signal);\n }\n },\n },\n});\n\nfunction canRetry(\n attemptNumber: number,\n maxAttempts: number,\n replayable: boolean,\n): boolean {\n return attemptNumber < maxAttempts && replayable;\n}\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { attemptHttpRequestPlugin } from \"./attempt-http-request\";\nimport { initializeHttpRequestPlugin } from \"./initialize-http-request\";\nimport type { HttpOperationStart, HttpRequestInput } from \"./types\";\n\nfunction createOperationId() {\n return globalThis.crypto?.randomUUID?.() ?? `http-${Date.now()}`;\n}\n\n/**\n * The transport orchestrator: turn an {@link HttpRequestInput} into a native\n * `Response`. It owns the OPERATION, the things that happen once per caller\n * request, and delegates the per-attempt work to `attemptHttpRequest`:\n *\n * initialize once -> attempt (prepare, authorize, dispatch, receive)\n *\n * The split is the seam that makes re-issuing a request possible. A wrap here\n * sees the whole operation (a concurrency permit, an overall deadline); a wrap\n * on `attemptHttpRequest` sees one attempt and may run it more than once\n * (retry, an approval re-issue). Cross-cutting behavior should still wrap the\n * narrowest stage it owns.\n *\n * A caller's `url` may be a `URL`; initialize normalizes it, so every stage\n * from prepare onward receives a plain string.\n *\n * A raw method: it owns its input (the fetch-shaped `HttpRequest`), so\n * `skipInputValidation` keeps the caller's object identity intact: no parse, no\n * coercion, no clone. The `inputSchema` is projection-only (never run as a\n * validator) and exists so the registry has a shape to describe.\n *\n * An unresolved `connection` fails in the default authorize stage: no auth wrap\n * consumed it, so the request would otherwise go out unauthenticated.\n *\n * No retry by default: with nothing composed this runs exactly one attempt.\n * `retryHttpRequestPlugin` is opt-in.\n */\nexport const sendHttpRequestPlugin = defineMethod({\n name: \"sendHttpRequest\",\n namespace: \"kitcore\",\n imports: [\n declareDefault({ plugin: initializeHttpRequestPlugin }),\n declareDefault({ plugin: attemptHttpRequestPlugin }),\n ],\n inputSchema: z.custom<HttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input, imports }) => {\n const start: HttpOperationStart = {\n operationId: createOperationId(),\n signal: input.signal,\n };\n // Initialize COMPLETES the operation context rather than returning a bag of\n // its own: what it derives (the normalized request, replayability) is true\n // of the whole operation, so it belongs beside the id every stage already\n // reads.\n const operation = await imports.initializeHttpRequest({\n request: input,\n operation: start,\n });\n\n return imports.attemptHttpRequest({\n request: operation.request,\n attempt: {\n attemptNumber: 1,\n operation,\n signal: operation.signal,\n state: {},\n },\n });\n },\n});\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { sendHttpRequestPlugin } from \"./send-http-request\";\nimport type { HttpRequestInput } from \"./types\";\n\n/**\n * `fetch` — native `fetch(url, init)` ergonomics over the transport. It\n * delegates to `sendHttpRequest`, inheriting its stage pipeline and any wraps\n * composed around those stages.\n *\n * It imports the transport as a DEFAULT (`declareDefault`), so `fetchPlugin`\n * works alone: with nothing else composed, the default pipeline dispatches\n * through `globalThis.fetch`. A composed transport provider of the same id\n * preempts the default, so hello-world is just `fetchPlugin`.\n *\n * `fetch` is branch-free and never inspects `connection` — it just delegates, and\n * the default authorizer fails loud on an unresolved reference. A raw method\n * (`skipInputValidation`): the caller's `init` passes through untouched, so this\n * is global `fetch` plus the `url` / `connection` shape. Content-type inference\n * for non-standard bodies (a plain object → JSON) is a head ergonomic, not\n * kitcore-generic.\n *\n * `url` takes a `URL` as well as a string, matching global `fetch`. A `Request`\n * is the one first argument global `fetch` takes that this does not; see\n * {@link HttpRequestInput}.\n */\nexport const fetchPlugin = defineMethod({\n name: \"fetch\",\n namespace: \"kitcore\",\n imports: [declareDefault({ plugin: sendHttpRequestPlugin })],\n positional: [\"url\", \"init\"],\n inputSchema: z.custom<{\n url: string | URL;\n init?: Omit<HttpRequestInput, \"url\">;\n }>(),\n skipInputValidation: true,\n run: ({ input, imports }) => {\n const { url, init } = input;\n return imports.sendHttpRequest({ url, ...init });\n },\n});\n","import type { HttpRequest } from \"./types\";\n\n/**\n * Header names whose value is a credential.\n *\n * A fixed list rather than a pattern. A pattern over header names would either\n * miss a bespoke one or mask something harmless, and a reader cannot tell which\n * happened from the output.\n */\nconst CREDENTIAL_HEADERS = [\"authorization\", \"x-api-key\"];\n\n/**\n * Show enough of a secret to recognize it, never enough to use it.\n *\n * Recognizing matters: the usual debugging question is \"which token did it\n * send\", and an all-asterisks value cannot answer it. Four characters at each\n * end identify a token among the two or three a developer is juggling.\n *\n * A short value gets one character, because four and four of an eight\n * character secret is the secret.\n */\nfunction maskSecret(secret: string): string {\n if (secret.length > 12) {\n return `${secret.slice(0, 4)}...${secret.slice(-4)}`;\n }\n return `${secret.charAt(0)}...`;\n}\n\n/**\n * Mask a credential header's value, keeping any scheme prefix (`Bearer `,\n * `Basic `) so the reader can still see which scheme was used.\n */\nfunction maskCredentialHeader(value: string): string {\n const spaceIndex = value.indexOf(\" \");\n if (spaceIndex > 0 && spaceIndex < value.length - 1) {\n return `${value.slice(0, spaceIndex + 1)}${maskSecret(value.slice(spaceIndex + 1))}`;\n }\n return maskSecret(value);\n}\n\n/**\n * Headers with every credential value masked, as a plain object a logger can\n * print. Header names come back lowercased, because `Headers` normalizes them.\n */\nexport function redactHeaders(\n headers?: HeadersInit,\n): Record<string, string> | undefined {\n if (!headers) return headers;\n\n const normalized = new Headers(headers);\n for (const [name, value] of normalized.entries()) {\n if (CREDENTIAL_HEADERS.includes(name.toLowerCase())) {\n normalized.set(name, maskCredentialHeader(value));\n }\n }\n return Object.fromEntries(normalized);\n}\n\n/**\n * A log-safe view of a request: credential headers masked, and `connection`\n * masked with it.\n *\n * `connection` is the half a head cannot redact for itself. The transport\n * treats it as an opaque string, so its value is whatever a caller passed,\n * including a raw credential (see {@link HttpRequest}). A hook printing a\n * stage's `args` would put it on the terminal.\n *\n * The url and the body are NOT redacted. A token can ride either, in a query\n * parameter or a form field, but kitcore does not know which one, and masking\n * by guessed name would hide the wrong thing while claiming the rest is safe.\n * A head that puts credentials there has to redact them itself.\n *\n * Returns a new object. The pipeline treats `HttpOperationContext.request` as\n * read-only, and a logger must not be the thing that breaks that.\n */\nexport function redactHttpRequest(request: HttpRequest): HttpRequest {\n const redacted: HttpRequest = { ...request };\n if (request.headers) redacted.headers = redactHeaders(request.headers);\n if (request.connection != null) {\n redacted.connection = maskSecret(request.connection);\n }\n return redacted;\n}\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { DefaultConnectionSchemeInput } from \"./types\";\n\nexport const defaultConnectionSchemePlugin = defineMethod({\n name: \"defaultConnectionScheme\",\n namespace: \"kitcore\",\n inputSchema: z.custom<DefaultConnectionSchemeInput>(),\n skipInputValidation: true,\n run: (): string | undefined => undefined,\n});\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { defaultConnectionSchemePlugin } from \"./default-connection-scheme\";\nimport type { NormalizedConnection, NormalizeConnectionInput } from \"./types\";\n\nexport const normalizeConnectionPlugin = defineMethod({\n name: \"normalizeConnection\",\n namespace: \"kitcore\",\n imports: [declareDefault({ plugin: defaultConnectionSchemePlugin })],\n inputSchema: z.custom<NormalizeConnectionInput>(),\n skipInputValidation: true,\n run: ({ input, imports }): NormalizedConnection | undefined => {\n const { connection } = input;\n if (connection == null) {\n return undefined;\n }\n\n const delimiterIndex = connection.indexOf(\":\");\n if (delimiterIndex !== -1) {\n return {\n connection,\n scheme: connection.slice(0, delimiterIndex),\n value: connection.slice(delimiterIndex + 1),\n };\n }\n\n const scheme = imports.defaultConnectionScheme({ connection });\n return {\n connection,\n scheme,\n value: connection,\n };\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { ResolveConnectionInput } from \"./types\";\n\n/**\n * SELECT which connection REFERENCE a call should use: the explicit one if the\n * caller passed it, else `undefined`. It deals only in references, never a\n * secret. Turning a reference into a credential is `authorizeHttpRequest`.\n *\n * The default is a pass-through, so this exists to be wrapped. A head adds\n * discovery or defaulting with a `defineHook` over `resolveConnection`, keyed by\n * `input.connectionType` (reading a connection id from an env var, say). Because\n * it is an ordinary method rather than an interactive prompt, a caller in plain\n * code gets the head's defaulting too, not only a caller driven by the\n * controller.\n *\n * Returning `undefined` is not an error here. Whether a missing connection is\n * fatal depends on what the caller declared it needs, which this stage cannot\n * see, so this stays policy-free.\n */\nexport const resolveConnectionPlugin = defineMethod({\n name: \"resolveConnection\",\n namespace: \"kitcore\",\n inputSchema: z.custom<ResolveConnectionInput>(),\n skipInputValidation: true,\n run: ({ input }: { input: ResolveConnectionInput }): string | undefined =>\n input.connection,\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;AAA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W,CAAC;AAC7D,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACT;AAAA,EACF;AACF,CAAC;;;ACjCD,IAAAC,eAAkB;AAoBX,IAAM,0BAA0B,aAAa;AAAA,EAClD,MAAM;AAAA,EACN,WAAW;AAAA,EACX,aAAa,eAAE,OAA+B;AAAA,EAC9C,qBAAqB;AAAA,EACrB,KAAK,CAAC,EAAE,MAAM,MACZ,MAAM;AACV,CAAC;","names":["start","import_zod","parseOrThrow","exports","import_zod","isRecord","exports","getContext","getRegistry","out","context","plugins","import_zod","import_zod","topoOrder","actions","start","step","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","start","import_zod","import_zod","import_zod","import_zod"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/utils/string-utils.ts","../src/utils/schema-utils.ts","../src/utils/stability.ts","../src/registry.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/call-options.ts","../src/utils/async-context.ts","../src/utils/method-scope.ts","../src/utils/call-context.ts","../src/utils/core-options.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/utils/output-policy.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/model/resolution/questions.ts","../src/model/resolution/walk.ts","../src/utils/core-plugin.ts","../src/transport/attempt-http-request.ts","../src/transport/authorize-http-request.ts","../src/transport/dispatch-http-request.ts","../src/transport/prepare-http-request.ts","../src/transport/receive-http-response.ts","../src/transport/initialize-http-request.ts","../src/transport/retry-http-request.ts","../src/transport/send-http-request.ts","../src/transport/fetch.ts","../src/transport/redact.ts","../src/connections/default-connection-scheme.ts","../src/connections/normalize-connection.ts","../src/connections/resolve-connection.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 disposeSdk,\n resolvePlugin,\n CoreDisposeError,\n fromFunctionPlugin,\n defineLegacyMerge,\n dangerousContextPlugin,\n getRegistryPlugin,\n coreOptionsPluginRef,\n getContext,\n getRegistry,\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 defineOverride,\n /** @deprecated Use `defineOverride`. */\n defineMethodOverride,\n defineResolver,\n defineFormatter,\n defineHook,\n defineProperty,\n declareMethod,\n declareProperty,\n declareOptionalProperty,\n declareOptionalMethod,\n declareDefault,\n selectExports,\n omitExports,\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 CreateSdkOptions,\n DisposeFn,\n SdkContext,\n SdkContextCarrier,\n LeafMeta,\n OverridableMetaFields,\n MethodPlugin,\n MethodAnnotator,\n MethodOverridePlugin,\n HookPlugin,\n HookAnnotator,\n DynamicMember,\n PropertyPlugin,\n AggregatePlugin,\n PluginSurface,\n MethodAttachment,\n Formatter,\n // The model resolver descriptor (the `defineResolver` result). It can't take\n // the bare name `Resolver` during the transition: `export *` from schema-utils\n // already publishes a legacy `Resolver`, and two public `Resolver`s would\n // collide. A head still needs to name it to annotate a `defineResolver`\n // result (the same reason `Formatter` is exported), so it ships as\n // `ModelResolver`; once the legacy `Resolver` is deleted this is renamed to\n // `Resolver`.\n Resolver as ModelResolver,\n ResolverRequirement,\n BoundResolver,\n BoundFormatter,\n ResolverType,\n ListItemsResult,\n PluginSummary,\n StandInId,\n LeafSummary,\n // Resolution controller surface.\n Controller,\n ControllerSdk,\n ControllerState,\n ControllerResult,\n ControllerError,\n ControllerIssue,\n ControllerQuestion,\n ControllerAction,\n ControllerPagination,\n ControllerListingPage,\n ControllerListingPosition,\n ControllerSelectPage,\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 { CORE_OPTIONS_ID, defaultLogDeprecation } from \"./utils/core-options\";\nexport type {\n CoreOptions,\n DeprecationWarning,\n StabilityNotice,\n} from \"./utils/core-options\";\n\nexport type {\n MethodHooks,\n ComposedAnnotator,\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\n// Types only: heads name `CallContext` (the run bag / annotate helper) and\n// `Annotations` (the annotator return). The minting/brand functions stay\n// internal — a head reads/writes `.annotations` on a context it is handed; it\n// never mints or brand-checks one.\nexport type {\n CallContext,\n Annotations,\n CallOrigin,\n} from \"./utils/call-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 {\n createDeprecationLogger,\n createStabilityNoticeLogger,\n} from \"./utils/logging\";\nexport type { StabilityNoticeLogger } 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 ResponseMeta,\n OutputDataValidationReport,\n} from \"./types/output-validation\";\n\nexport type {\n CategoryDefinition,\n FunctionRegistryEntry,\n FunctionDeprecation,\n RegistryResult,\n} from \"./types/registry\";\n\n// The stability ladder: the levels array (single source of truth for the\n// type, tier iteration order, and docs render order), the normalizer the\n// registry projection uses, and the one label renderer every\n// description-rendering consumer (CLI help, MCP tool descriptions) calls.\nexport {\n STABILITY_LEVELS,\n STABILITY_TITLES,\n normalizeStability,\n applyStabilityLabel,\n} from \"./utils/stability\";\nexport type { StabilityLevel } from \"./utils/stability\";\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 isCoreCancelledSignal,\n} from \"./types/signals\";\n\n// Transport: the swappable `sendHttpRequest` pipeline and its fetch-shaped\n// request type. Wrap focused behavior around the narrowest stage; see\n// docs/design/2026-08-03-kitcore-transport.md.\nexport {\n attemptHttpRequestPlugin,\n authorizeHttpRequestPlugin,\n dispatchHttpRequestPlugin,\n initializeHttpRequestPlugin,\n prepareHttpRequestPlugin,\n receiveHttpResponsePlugin,\n sendHttpRequestPlugin,\n fetchPlugin,\n retryHttpRequestPlugin,\n retryHttpRequestOptionsPluginRef,\n RETRY_HTTP_REQUEST_OPTIONS_ID,\n redactHeaders,\n redactHttpRequest,\n} from \"./transport\";\nexport type {\n AttemptHttpRequestInput,\n AuthorizeHttpRequestInput,\n DispatchHttpRequestInput,\n HttpAttemptContext,\n HttpFetchInit,\n HttpPipelineState,\n InitializeHttpRequestInput,\n HttpOperationContext,\n HttpOperationStart,\n PrepareHttpRequestInput,\n HttpRequest,\n HttpRequestInput,\n HttpResponse,\n ReceiveHttpResponseInput,\n RetryHttpRequestOptions,\n SendHttpRequest,\n} from \"./transport\";\n\n// Connections: generic opaque reference normalization. Heads may provide a\n// default scheme; kitcore does not assign one.\nexport {\n defaultConnectionSchemePlugin,\n normalizeConnectionPlugin,\n resolveConnectionPlugin,\n} from \"./connections\";\nexport type {\n DefaultConnectionSchemeInput,\n NormalizedConnection,\n NormalizeConnectionInput,\n ResolveConnectionInput,\n} from \"./connections\";\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","import { z } from \"zod\";\n\n/**\n * Plugins with a required-parameter rename declare two schemas: a canonical one\n * (new names only, carrying `.meta({ aliases })`) and a `z.union([canonical,\n * deprecated])` for runtime input parsing (so callers passing old names still\n * validate). The union has no object shape, so everything that reads parameter\n * shape/requiredness — the registry projection, generated docs, and the\n * resolution planner — must read the canonical variant, not the union.\n *\n * Convention: the FIRST union variant is the canonical schema. Every plugin\n * that uses unions follows this; it's explicit and needs no extra metadata.\n * Runtime validation still uses the full union; only shape reading canonicalizes.\n */\nexport function 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\n/** Strip optional/default/nullable wrappers to the inner schema, tracking\n * whether the wrappers made the field non-required. */\nexport function unwrapSchema(schema: z.ZodType): {\n inner: z.ZodType;\n required: boolean;\n} {\n let inner = schema;\n let required = true;\n for (;;) {\n // `unwrap()` is typed against zod's core base, so each result is cast back\n // to the classic `ZodType` this module and its callers speak.\n if (inner instanceof z.ZodOptional || inner instanceof z.ZodDefault) {\n required = false;\n inner = inner.unwrap() as z.ZodType;\n } else if (inner instanceof z.ZodNullable) {\n // Nullable alone still demands the key, so requiredness is unchanged.\n inner = inner.unwrap() as z.ZodType;\n } else {\n break;\n }\n }\n return { inner, required };\n}\n\n/**\n * The object shape of a method's input schema, or undefined when the schema is\n * absent or not a plain object. A required-rename union (`z.union([canonical,\n * deprecated])`) is canonicalized to its first variant first, and\n * optional/default/nullable wrappers are stripped, so a schema whose fields are\n * readable at all is read rather than treated as shapeless.\n */\nexport function objectShapeOf(\n schema: z.ZodSchema | undefined,\n): Record<string, z.ZodType> | undefined {\n const canonical = canonicalInputSchema(schema);\n if (!canonical) return undefined;\n const { inner } = unwrapSchema(canonical);\n if (inner instanceof z.ZodObject) {\n return inner.shape as Record<string, z.ZodType>;\n }\n return undefined;\n}\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 * four 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 * - `validate`— validation is the resolver's top-level `validate`, which\n * never routes through rendering (and gets `imports`).\n */\nexport type ResolverPromptConfig = Omit<\n PromptConfig,\n \"name\" | \"default\" | \"filter\" | \"validate\"\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// Negatable Parameter Metadata\n// ============================================================================\n\n/**\n * Marks an optional boolean schema for which omission is distinct from false:\n * omitting the value means \"use the server default\" or \"preserve the current\n * value\", so an explicit false needs its own affordance. A string supplies\n * the domain antonym — \"disabled\" for `enabled` — which each surface renders\n * in its own vocabulary (a CLI as a flag spelling, a tool description as\n * prose). `true` requests generic negation when the domain has no antonym.\n *\n * Declare it via `.meta({ negatable: \"disabled\" } satisfies NegatableMetadata)`.\n * The `satisfies` matters: zod's metadata type permits arbitrary keys, so it\n * is the only compile-time check against a misspelled key.\n */\nexport interface NegatableMetadata {\n negatable: true | string;\n}\n\n/**\n * Read a schema's `negatable` metadata: `true`, the domain antonym, or\n * undefined when the schema doesn't declare one. Unwraps optional/default\n * wrappers like `isPositional`, so the `.meta()` call may sit on any layer\n * of the chain.\n */\nexport function getNegatable(\n schema: z.ZodType,\n): NegatableMetadata[\"negatable\"] | undefined {\n const negatable = (\n schema as { meta?: () => { negatable?: unknown } | undefined }\n ).meta?.()?.negatable;\n if (negatable === true) return true;\n if (typeof negatable === \"string\" && negatable.length > 0) return negatable;\n\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) {\n return getNegatable(schema._zod.def.innerType as z.ZodType);\n }\n\n return undefined;\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.\n// The return type is annotated rather than inferred: left inferred, the\n// declaration rollup expands `z.enum`'s mapped type through an `infer` step and\n// emits a form TypeScript then rejects (TS2536), which surfaces to any consumer\n// typechecking with `skipLibCheck: false`.\nexport function openEnum<const T extends readonly [string, ...string[]]>(\n values: T,\n description: string,\n): z.ZodUnion<readonly [z.ZodEnum<{ [K in T[number]]: K }>, z.ZodString]> {\n return z.union([z.enum(values), z.string()]).describe(description);\n}\n","/**\n * API stability tiers.\n *\n * A plugin declares exactly one level via `PluginMeta.stability`; tier\n * membership (which subpath aggregate exports the plugin) is structural,\n * so nothing here compares levels ordinally. The array is the single\n * source of truth: it derives the {@link StabilityLevel} type, gives the\n * ladder tests their adjacent-tier iteration order, and gives docs a\n * render order.\n */\nexport const STABILITY_LEVELS = [\"stable\", \"beta\", \"experimental\"] as const;\n\nexport type StabilityLevel = (typeof STABILITY_LEVELS)[number];\n\n/**\n * Title-case display names for each level, for section-level badges in\n * generated docs (e.g. `Code Workflows (Beta)`). Inline description\n * labels go through {@link applyStabilityLabel} instead.\n */\nexport const STABILITY_TITLES = {\n stable: \"Stable\",\n beta: \"Beta\",\n experimental: \"Experimental\",\n} as const satisfies Record<StabilityLevel, string>;\n\n/**\n * Normalize authored meta to a concrete level: absent means `\"stable\"`,\n * and the deprecated `experimental: true` boolean means `\"experimental\"`.\n * The registry projection runs every entry through this, so\n * `FunctionRegistryEntry.stability` is always concrete and consumers\n * never branch on `undefined`.\n *\n * The declared value can cross a JSON boundary from a hand-written\n * plugin, so at runtime it may be any string. An unrecognized level\n * clamps to `\"experimental\"` — the author declared the method not\n * stable, and clamping keeps the raw string out of notices and labels.\n * It doesn't throw because this also runs in the `getStability` live\n * read on the call path, where a throw would break the observed call.\n */\nexport function normalizeStability(meta: {\n stability?: StabilityLevel;\n experimental?: boolean;\n}): StabilityLevel {\n if (meta.stability !== undefined) {\n return (STABILITY_LEVELS as readonly string[]).includes(meta.stability)\n ? meta.stability\n : \"experimental\";\n }\n return meta.experimental ? \"experimental\" : \"stable\";\n}\n\n/**\n * The shared label renderer: every consumer that renders a registry\n * entry's description (CLI help, MCP tool descriptions) labels it\n * through this function, so a new consumer cannot silently drop the\n * label. `stability` stays structured data on the registry entry — the\n * label is applied at render time, never baked into the stored\n * description (docs badge at the section level, so baking it in would\n * double-badge).\n *\n * The label follows the plugin's declared level, not the subpath that\n * surfaced it: a beta method surfaced through an experimental-tier\n * consumer still reads \"(beta)\".\n */\nexport function applyStabilityLabel({\n description,\n stability,\n placement = \"suffix\",\n}: {\n description: string;\n /** Absent means stable (the value may arrive from outside the\n * normalized registry projection, e.g. hand-built JSON). */\n stability: StabilityLevel | undefined;\n /**\n * `\"suffix\"` renders `<description> (beta)` (CLI help);\n * `\"prefix\"` renders `[Beta] <description>` (MCP tool descriptions,\n * where the front of the string is what an LLM reads first).\n */\n placement?: \"suffix\" | \"prefix\";\n}): string {\n if (stability === undefined || stability === \"stable\") return description;\n return placement === \"prefix\"\n ? `[${STABILITY_TITLES[stability]}] ${description}`\n : `${description} (${stability})`;\n}\n","import 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\";\nimport { canonicalInputSchema } from \"./utils/schema-utils\";\nimport { normalizeStability } from \"./utils/stability\";\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\nexport function buildRegistry({\n sdk,\n meta,\n formatters,\n resolvers,\n positional,\n skipInputValidation,\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, lifted off materialized method entries by the\n * caller (like `formatters`). A bound runtime thing, not descriptive meta, so\n * supplied separately rather than read off `PluginMeta`. */\n resolvers?: Record<string, Record<string, BoundResolver>>;\n /** Per-binding positional projections, lifted off materialized method entries\n * by the caller (like `resolvers`). A runtime projection, not meta. */\n positional?: Record<string, readonly string[]>;\n /** Per-binding `skipInputValidation` flags, lifted off materialized method\n * entries. A boundary fact (not meta) the controller reads to skip its final\n * validation for methods that own their input. */\n skipInputValidation?: Record<string, boolean>;\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 const stability = normalizeStability(m);\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 outputSchema: m.outputSchema,\n positional: positional?.[key],\n skipInputValidation: skipInputValidation?.[key],\n categories: (m.categories ?? []).map((c) =>\n typeof c === \"string\" ? c : c.key,\n ),\n resolvers: resolvers?.[key],\n formatter: formatters?.[key],\n stability,\n // Deprecated derived read, literal by name: only the experimental\n // tier reads true. Beta reads false — the \"not stable\" warning duty\n // lives in `stability` and the runtime notice, not this boolean.\n experimental: stability === \"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 * Method-call lifecycle hooks. Plugins contribute `onMethodStart` and/or\n * `onMethodEnd` observers, plus an optional pre-run `annotator` that returns\n * fields merged into the call's annotation bag; `buildHooks` composes each\n * across plugins so multiple contributors coexist. Composition is right-additive\n * (newer plugins fire — and `annotator` fields win — after earlier ones); only\n * opt-in methods built through `createPluginMethod` /\n * `createPaginatedPluginMethod` trigger the hooks.\n */\n\nimport type { Annotations, CallOrigin } from \"./call-context\";\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 /** The call's correlation id, copied from the per-call context; `null` where\n * id minting was unavailable. */\n callId: string | null;\n /**\n * Origin of the call's root, copied from the per-call context. `\"surface\"` =\n * surface-origin (an SDK-surface call or a runtime delegation — real user\n * work); `\"internal\"` = a framework-internal call minted by kitcore's own\n * machinery (resolver/formatter/dispose/observer twins, `resolvePlugin`).\n * Orthogonal to `depth` (an internal call is still `depth 0`); a head can drop\n * internal-origin calls from telemetry.\n */\n callOrigin: CallOrigin;\n /**\n * The call's annotation bag, carried live from the per-call context. At\n * `onMethodStart` it holds the early-knowable fields (boundary annotator +\n * a method's pre-run `annotator`); by `onMethodEnd` any mid-`run` writes\n * are visible too (same object reference throughout the call).\n */\n annotations: Annotations;\n}\n\nexport type OnMethodStart = (ctx: OnMethodStartContext) => void;\n\nexport interface OnMethodEndContext extends OnMethodStartContext {\n durationMs: number;\n error?: Error;\n}\n\nexport type OnMethodEnd = (ctx: OnMethodEndContext) => void;\n\n/**\n * A composed pre-run annotator: given a call's method name and (normalized,\n * pre-validation) input, it returns {@link Annotations} the boundary merges into\n * the call's bag before `onMethodStart`. Unlike the `void` lifecycle observers,\n * this one returns a value; composition merges the returned bags rather than\n * chaining side effects. A contributor with nothing to add returns an empty bag,\n * so absence is modelled by no annotator rather than an `undefined` return.\n */\nexport type ComposedAnnotator = (ctx: {\n methodName: string;\n input: unknown;\n}) => Annotations;\n\nexport interface MethodHooks {\n onMethodStart?: OnMethodStart;\n onMethodEnd?: OnMethodEnd;\n annotator?: ComposedAnnotator;\n}\n\n// Functions already isolated by `isolate` (leaf wrappers, and composites built\n// only from them). Membership lets `isolate` skip re-wrapping during the\n// incremental composition buildHooks performs, so each observer ends up behind\n// exactly one try/catch instead of one per pass. A WeakSet keys on identity and\n// releases entries when the functions are collected, so it holds no state of\n// its own.\nconst isolated = new WeakSet<object>();\n\n/**\n * Wrap one fire-and-forget observer so it runs in isolation, or pass through\n * `undefined`. A throwing observer must not break the observed method or its\n * sibling observers, so a throw is logged and swallowed rather than\n * propagated. Idempotent: an already-isolated function is returned unchanged,\n * so repeated composition never stacks redundant wrappers. A routed error\n * handler is deliberately not supported: this composes at build time and has\n * no access to the per-SDK configuration such a handler would live on.\n */\nfunction isolate<C>(\n observer: ((ctx: C) => void) | undefined,\n): ((ctx: C) => void) | undefined {\n if (!observer) return undefined;\n if (isolated.has(observer)) return observer;\n const wrapped = (ctx: C) => {\n try {\n observer(ctx);\n } catch (error) {\n console.error(\n \"[core] A method-lifecycle observer threw and was ignored. \" +\n \"Observers are fire-and-forget and must not throw.\",\n error,\n );\n }\n };\n isolated.add(wrapped);\n return wrapped;\n}\n\n/**\n * Compose two same-shaped observer hooks into one that runs `existing` then\n * `added`, each isolated so a throw reaches neither the method boundary nor\n * the sibling observer. Returns the lone (wrapped) side when only one is set,\n * or `undefined` when neither is. The composed function only calls isolated\n * parts, so it cannot throw either; marking it isolated lets a later pass fold\n * it in without re-wrapping. 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 const wrappedExisting = isolate(existing);\n const wrappedAdded = isolate(added);\n if (!wrappedExisting) return wrappedAdded;\n if (!wrappedAdded) return wrappedExisting;\n const composed = (ctx: C) => {\n wrappedExisting(ctx);\n wrappedAdded(ctx);\n };\n isolated.add(composed);\n return composed;\n}\n\n/**\n * Compose two annotators into one that merges both returned bags (`added` wins\n * on key collision, keeping composition right-additive like {@link composeVoid}).\n * Each contributor is guarded at registration (see `assembleHooks`), so neither\n * side throws here.\n */\nfunction composeAnnotators(\n existing: ComposedAnnotator | undefined,\n added: ComposedAnnotator | undefined,\n): ComposedAnnotator | undefined {\n if (!existing) return added;\n if (!added) return existing;\n return (ctx) => ({ ...existing(ctx), ...added(ctx) });\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. `annotator` is the one\n * non-`void` member: it returns `Annotations` the boundary merges before\n * `onMethodStart`, so it uses `composeAnnotators` rather than `composeVoid`.\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 const annotator = composeAnnotators(existing.annotator, added.annotator);\n if (annotator) result.annotator = annotator;\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\nexport interface StabilityNoticeLogger {\n logStabilityNotice(message: string): void;\n resetStabilityNotices(): void;\n}\n\n/**\n * Create a package-tagged stability-notice logger: the deprecation logger's\n * sibling for non-stable (beta / experimental) API warnings, with the same\n * once-per-process dedupe policy and its own independent message Set.\n */\nexport function createStabilityNoticeLogger(\n tag: string,\n): StabilityNoticeLogger {\n const loggedNotices = new Set<string>();\n\n return {\n logStabilityNotice(message: string): void {\n if (loggedNotices.has(message)) return;\n loggedNotices.add(message);\n\n console.warn(`[${tag}] ${message}`);\n },\n\n resetStabilityNotices(): void {\n loggedNotices.clear();\n },\n };\n}\n\nexport const { logStabilityNotice, resetStabilityNotices } =\n createStabilityNoticeLogger(\"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\nimport { logDeprecation } from \"./logging\";\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 CONCAT: \"concat\",\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 Lists\n// ============================================================================\n\ninterface PaginatedResult<TItem> {\n data: TItem[];\n nextCursor?: string;\n}\n\n/**\n * Supplies one list to `concatLists`: called with that list's own cursor,\n * resolves one page. An SDK paginated method fits directly\n * (`({ cursor }) => sdk.listThings({ cursor })`; awaiting a paginated\n * result yields the requested page).\n */\ntype ListSource<TItem> = (options: {\n cursor?: string;\n}) => PromiseLike<PaginatedResult<TItem>>;\n\ninterface ConcatCursorEnvelope {\n v: typeof CURSOR_VERSION;\n source: typeof CURSOR_SOURCE.CONCAT;\n index: number;\n cursor?: string;\n}\n\nfunction encodeConcatCursor(index: number, cursor: string | undefined): string {\n const envelope: ConcatCursorEnvelope = {\n v: CURSOR_VERSION,\n source: CURSOR_SOURCE.CONCAT,\n index,\n cursor,\n };\n return encodeBase64(JSON.stringify(envelope));\n}\n\nfunction decodeConcatCursor(incoming?: string): {\n index: number;\n cursor: string | undefined;\n} {\n if (!incoming) {\n return { index: 0, cursor: undefined };\n }\n try {\n const envelope = JSON.parse(decodeBase64(incoming)) as ConcatCursorEnvelope;\n if (\n envelope.v === CURSOR_VERSION &&\n envelope.source === CURSOR_SOURCE.CONCAT &&\n typeof envelope.index === \"number\"\n ) {\n return { index: envelope.index, cursor: envelope.cursor };\n }\n } catch {\n // Fall through to the plain-cursor fallback below.\n }\n // Not a concat envelope: treat it as the first list's own cursor.\n return { index: 0, cursor: incoming };\n}\n\n/**\n * List one page of several paginated lists joined end to end. Lists are\n * drained in order; pass a page's `nextCursor` back in to get the next page.\n *\n * Pagination is stateless: every outgoing cursor encodes which list to\n * resume plus that list's own cursor, so a fresh `concatLists` call\n * continues exactly where the previous page left off. A cursor stores its\n * position by list index, so it is only valid while `sources` keeps the\n * same lists in the same order. Lists must produce disjoint items\n * themselves; there is no cross-list dedupe (an in-memory seen-set could\n * not survive the cursor round-trip).\n *\n * Uses paginateBuffered internally to normalize page sizes across list\n * boundaries: if the first list only has 2 items, they'll be buffered with\n * items from the next list into a full page.\n */\nexport async function concatLists<TItem>({\n sources,\n pageSize = 100,\n cursor,\n}: {\n /** The lists to concatenate, each supplied as a page-fetching source. */\n sources: ListSource<TItem>[];\n pageSize?: number;\n /** Cursor from a previous `concatLists` page; resumes there. */\n cursor?: string;\n}): Promise<PaginatedResult<TItem>> {\n if (sources.length === 0) {\n return { data: [] };\n }\n\n const pageFunction = async (options: {\n cursor?: string;\n maxItems?: number;\n pageSize?: number;\n }): Promise<PaginatedResult<TItem>> => {\n let { index, cursor: listCursor } = decodeConcatCursor(options.cursor);\n\n while (index < sources.length) {\n const page = await sources[index]({ cursor: listCursor });\n const hasMoreInList = page.nextCursor != null;\n\n if (page.data.length === 0 && !hasMoreInList) {\n index++;\n listCursor = undefined;\n continue;\n }\n\n return {\n data: page.data,\n nextCursor: hasMoreInList\n ? encodeConcatCursor(index, page.nextCursor)\n : index < sources.length - 1\n ? encodeConcatCursor(index + 1, undefined)\n : undefined,\n };\n }\n\n return { data: [] };\n };\n\n const result = await paginateBuffered(pageFunction, {\n pageSize,\n cursor,\n }).next();\n return result.done ? { data: [] } : result.value;\n}\n\n/**\n * @deprecated Use {@link concatLists}; awaiting either yields the same one\n * page. The page-iterable half of the old return shape is gone; to walk\n * pages, pass each page's `nextCursor` to a fresh call.\n */\nexport function concatPaginated<TItem>({\n sources,\n pageSize,\n cursor,\n}: {\n sources: ListSource<TItem>[];\n pageSize?: number;\n cursor?: string;\n}): Promise<PaginatedResult<TItem>> {\n logDeprecation(\"concatPaginated() is deprecated. Use concatLists() instead.\");\n return concatLists({ sources, pageSize, cursor });\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 *\n * @deprecated Call `.pages()` on the paginated result instead; it returns a\n * plain AsyncIterable over pages with no wrapper needed.\n */\nexport function toIterable<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n logDeprecation(\n \"toIterable() is deprecated. Call .pages() on the paginated result instead.\",\n );\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","import { z } from \"zod\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\n\n/**\n * The floor the framework holds its own call parameters to, and the only\n * statement of their shapes. Which of them a given boundary reads at all is\n * that boundary's {@link FrameworkOptionsPolicy}.\n *\n * MINIMAL on purpose. It rejects what the machinery cannot act on and nothing\n * else, leaving a plugin free to tighten it. `pageSize` is at least 1 because a\n * page loop asking upstream for zero items does not terminate. `maxItems` may\n * be 0, since \"return nothing\" is a coherent request the loop already handles.\n * `cursor` is any string: its meaning belongs to the head's API, including\n * whatever a reverse-paginating one encodes in it.\n *\n * A plugin that wants a tighter rule writes it in its own `inputSchema`, and\n * both run. See {@link parseCallOptions}.\n */\nexport const CallFrameworkOptionsSchema = z.object({\n /** Page to fetch. Opaque to kitcore: the head's API defines the format. */\n cursor: z.string().optional(),\n /** Items per page. */\n pageSize: z.number().int().min(1).optional(),\n /** Stop after this many items, across pages. */\n maxItems: z.number().int().min(0).optional(),\n /** Bypass output validation for this one call. */\n skipOutputDataValidation: z.boolean().optional(),\n});\n\nexport type CallFrameworkOptions = z.infer<typeof CallFrameworkOptionsSchema>;\nexport type CallFrameworkOptionKey = keyof CallFrameworkOptions;\n\n/**\n * What one boundary does with the framework's call parameters.\n *\n * There is no global answer, because the modes differ. A list call feeds a page\n * loop; an item call has no loop to feed; a legacy handler honors nothing the\n * framework added after it was written.\n *\n * This is a fact about the MODE, decided when the boundary is built. It says\n * nothing about the plugin's schema, which is the difference between this and\n * everything {@link parseCallOptions} used to infer.\n */\nexport interface FrameworkOptionsPolicy {\n /** The parameters this boundary reads. Each is also held to\n * {@link CallFrameworkOptionsSchema}, whatever the plugin's schema says. */\n claims: readonly CallFrameworkOptionKey[];\n /** The subset handed to `run` even when the plugin's schema dropped it,\n * because `run` cannot do its job without it. A list `run` is asked for one\n * page, so it gets that page. */\n injects: readonly CallFrameworkOptionKey[];\n}\n\n/** Item mode: no page loop, so the caller's output skip is all it reads. */\nexport const ITEM_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"skipOutputDataValidation\"],\n injects: [],\n};\n\n/** List mode: the page loop plus the caller's output skip. */\nexport const LIST_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"cursor\", \"pageSize\", \"maxItems\", \"skipOutputDataValidation\"],\n injects: [\"cursor\", \"pageSize\"],\n};\n\n/**\n * A legacy paginated handler: the page loop, and nothing else. Nothing in the\n * legacy path honors a caller's output skip, so that key there is whatever the\n * handler's own schema says it is.\n *\n * Everything it claims it also hands over, because the legacy path leaves a\n * handler's input alone. That is what keeps a handler written before any of\n * this working unchanged.\n */\nexport const PAGE_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [\"cursor\", \"pageSize\", \"maxItems\"],\n injects: [\"cursor\", \"pageSize\", \"maxItems\"],\n};\n\n/** Reads nothing: every key in the call object belongs to the plugin. */\nexport const NO_FRAMEWORK_OPTIONS: FrameworkOptionsPolicy = {\n claims: [],\n injects: [],\n};\n\n/** A validated call, in the two halves the boundary hands on. */\nexport interface ParsedCallOptions {\n /** The framework's parameters, held to the floor above. */\n framework: CallFrameworkOptions;\n /** The plugin's parse output, or the raw call when it has no schema. */\n domain: unknown;\n /** Framework keys the plugin's schema refused, so the boundary supplies them\n * rather than the plugin's output. */\n supplied: ReadonlySet<string>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The framework keys a strict schema rejected outright, from the issues of a\n * failed parse. Only top-level rejections count: a nested `unrecognized_keys`\n * is a rule about the plugin's own nested object, not about our parameters. */\nfunction strictlyRefused(\n error: z.ZodError,\n claims: readonly string[],\n): string[] {\n const refused = new Set<string>();\n for (const issue of error.issues) {\n if (issue.code !== \"unrecognized_keys\" || issue.path.length > 0) continue;\n for (const key of issue.keys) {\n if (claims.includes(key)) refused.add(key);\n }\n }\n return [...refused];\n}\n\nfunction withoutKeys(\n options: Record<string, unknown>,\n keys: readonly string[],\n): Record<string, unknown> {\n const next: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if (!keys.includes(key)) next[key] = value;\n }\n return next;\n}\n\n/**\n * Validate a call against BOTH schemas, each on its own terms.\n *\n * The framework's parameters are held to {@link CallFrameworkOptionsSchema}\n * whatever the plugin says, so an invalid `pageSize` never reaches a page loop.\n * That runs even with no plugin schema at all, because the floor is the\n * framework's own rule and not something a plugin can opt out of by declaring\n * nothing.\n *\n * The plugin's schema then sees the WHOLE call. That is what keeps a declared\n * constraint alive: an author who writes `pageSize: z.number().max(100)` gets\n * their cap, on top of our floor. Zod strips keys an object schema does not\n * declare, so a plugin that never mentions `cursor` simply drops it and the\n * boundary puts it back.\n *\n * A `strict()` schema is the one shape that cannot ignore what it did not\n * declare. When it rejects our parameters by name, they are removed and the\n * parse runs again, so the plugin still sees exactly the input it meant to\n * describe. The retry is also what makes the ERROR honest: reported as-is, the\n * message would name `cursor` beside the caller's real typo, and a caller would\n * reasonably conclude they may not pass a `cursor` they may in fact pass.\n *\n * Detecting ownership from what the schema DID, rather than from reading its\n * structure, is the point. A wrapper (`.transform()`, `.refine()`) hides an\n * object's shape from any reader, but it cannot hide the parse result.\n */\nexport function parseCallOptions(\n options: unknown,\n {\n schema,\n policy = NO_FRAMEWORK_OPTIONS,\n adaptError,\n }: {\n schema?: z.ZodSchema;\n policy?: FrameworkOptionsPolicy;\n adaptError?: AdaptError;\n } = {},\n): ParsedCallOptions {\n const claims = policy.claims as readonly string[];\n const call = isRecord(options) ? options : undefined;\n\n // The floor, always. A plugin cannot opt out of it by having no schema.\n let framework: CallFrameworkOptions = {};\n if (call && claims.length > 0) {\n const present: Record<string, unknown> = {};\n for (const key of claims) {\n if (key in call) present[key] = call[key];\n }\n framework = parseOrThrow(CallFrameworkOptionsSchema, present, adaptError);\n }\n\n if (!schema) return { framework, domain: options, supplied: new Set() };\n\n const first = schema.safeParse(options);\n if (first.success) {\n // The plugin's schema accepted (or silently dropped) our parameters, so its\n // output is authoritative for everything it kept.\n return { framework, domain: first.data, supplied: new Set() };\n }\n\n const refused = call ? strictlyRefused(first.error, claims) : [];\n if (refused.length === 0) throw toCoreError(first.error, options, adaptError);\n\n const retry = schema.safeParse(withoutKeys(call!, refused));\n if (!retry.success) {\n throw toCoreError(retry.error, options, adaptError);\n }\n return { framework, domain: retry.data, supplied: new Set(refused) };\n}\n\n/**\n * Put the two halves back together for the boundary.\n *\n * The framework's validated value wins for every parameter it claims. A caller\n * who asks for `pageSize: 5` gets 5, whatever the plugin's schema produced for\n * that key, because the framework owns these and the caller's value already\n * passed both gates.\n *\n * Only the keys the caller actually passed are in `framework`, so a plugin's\n * `.default()` still applies to a key the caller omitted. A cap is unaffected\n * too: `z.number().max(100)` REJECTS 500 rather than rewriting it, so the throw\n * happens before this.\n *\n * What this does override is a plugin rewriting a claimed key mid-parse, a\n * transform emitting `pageSize: 999` over the caller's 5. That is the plugin\n * silently answering a question the caller already answered, and the framework\n * is the one that owns the question.\n *\n * Everything claimed comes back, not just what `run` will see. A page loop\n * needs `maxItems`, and an output policy needs the caller's skip, and both read\n * this object before `run` does. What `run` itself sees is decided later, at\n * the innermost core: see {@link withheldFromRun}.\n */\nexport function mergeCallOptions({\n framework,\n domain,\n}: ParsedCallOptions): unknown {\n const claimed = Object.entries(framework);\n if (!isRecord(domain) || claimed.length === 0) return domain;\n return { ...domain, ...Object.fromEntries(claimed) };\n}\n\n/**\n * The framework parameters that must not reach a plugin's `run`: everything\n * this boundary claims, minus what it injects.\n *\n * A fact about the mode alone, with no reading of the plugin's schema. What is\n * left is a value the framework consumes itself, `maxItems` for the page loop\n * and the caller's output skip, and a `run` can act on neither. Several `run`\n * bodies spread their whole input into a delegate or a request, so they would\n * ride along uninvited.\n */\nexport function withheldFromRun(\n policy: FrameworkOptionsPolicy,\n): ReadonlySet<string> {\n return new Set(policy.claims.filter((key) => !policy.injects.includes(key)));\n}\n\n/**\n * Drop those parameters. Runs at the innermost core, INSIDE the middleware\n * fold, so every `wrap` still sees the whole call object, and so does the\n * boundary's hook payload, which sits outside the fold entirely.\n */\nexport function stripFrameworkOnlyOptions(\n options: unknown,\n withheld: ReadonlySet<string>,\n): unknown {\n if (withheld.size === 0 || !isRecord(options)) return options;\n const entries = Object.entries(options);\n if (!entries.some(([key]) => withheld.has(key))) return options;\n return Object.fromEntries(entries.filter(([key]) => !withheld.has(key)));\n}\n\nfunction parseOrThrow<TSchema extends z.ZodSchema>(\n schema: TSchema,\n input: unknown,\n adaptError?: AdaptError,\n): z.infer<TSchema> {\n const result = schema.safeParse(input);\n if (result.success) return result.data;\n throw toCoreError(result.error, input, adaptError);\n}\n\nfunction toCoreError(\n error: z.ZodError,\n input: unknown,\n adaptError?: AdaptError,\n): Error {\n const messages = error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"input\";\n return `${path}: ${issue.message}`;\n });\n return createCoreError(\n {\n code: CoreErrorCode.Validation,\n message: `Validation failed:\\n ${messages.join(\"\\n \")}`,\n details: { zodErrors: error.issues, input },\n },\n adaptError,\n );\n}\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// This package's `browser` field maps it to `false`, so a browser bundler stubs\n// the module rather than failing to resolve it; instantiation then throws here\n// and the context falls back to inert-but-safe (every `run` just calls `fn`,\n// every `get` returns undefined). The catch is the backstop that makes that\n// stubbing survivable, and it 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; additional fields remain available\n * for plugin-specific scoped state.\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// Sync re-entrancy guard for lifecycle observers: while an observer runs, any\n// SDK method it calls must not fire hooks (else observing a call that itself\n// calls a method would recurse: hook -> observer -> method -> hook -> ...).\n// Observers are synchronous fire-and-forget, so a module-level counter is\n// race-free; a method invoked from an observer captures the suppression at\n// call entry, keeping its deferred end-hook paired with its suppressed start.\nlet observerReentrancy = 0;\n\n/** Run a lifecycle observer isolated: defensively (an observer error never\n * breaks the observed call) and with hook firing suppressed for any method\n * the observer itself calls (see the re-entrancy note above). */\nexport function runIsolatedObserver(fn: () => void): void {\n observerReentrancy++;\n try {\n fn();\n } catch {\n // Observers are isolated: a telemetry error must not break the call.\n } finally {\n observerReentrancy--;\n }\n}\n\n/** True while a lifecycle observer is executing (see runIsolatedObserver). */\nexport function isInsideObserver(): boolean {\n return observerReentrancy > 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 * Per-call context threaded explicitly through the method boundary in place of\n * ambient AsyncLocalStorage. It carries call identity, nesting depth, and a\n * per-invocation annotation bag. Because it travels as data, correlation and\n * nested-call dedup work without `async_hooks` — including in browsers, where\n * the old ALS store was inert and nested calls all looked top-level.\n *\n * Framework-neutral: heads surface `callId` under their own name (e.g. a\n * correlation id) and own their annotation field names.\n */\n\n/**\n * A private brand (a fresh `Symbol()`, never `Symbol.for`) makes a CallContext\n * unforgeable: no outside code can name the symbol to synthesize an id-bearing\n * context, and the brand never collides across bundled copies. This is the same\n * unforgeability the `INTERNAL_CALL` sentinel relies on.\n */\nconst CALL_CONTEXT_BRAND: unique symbol = Symbol(\"kitcore.callContext\");\n\n/**\n * The per-invocation annotation bag: an open string-keyed map a head fills with\n * telemetry-shaping fields (via the boundary annotator, a method's pre-run\n * `annotator`, or the run bag's mid-`run` `annotate`) and reads back on the\n * method-lifecycle hook context. Framework-neutral: kitcore does not know or\n * constrain the keys.\n */\nexport type Annotations = Record<string, unknown>;\n\n/**\n * Origin of a call's root. `\"surface\"` = entered through the SDK surface, or a\n * parent-less runtime delegation that still represents real user work;\n * `\"internal\"` = a framework-internal root minted by kitcore's own machinery,\n * which a head can suppress from telemetry.\n */\nexport type CallOrigin = \"surface\" | \"internal\";\n\nexport interface CallContext {\n /**\n * Minted once at the root call; copied verbatim to every nested (child) call.\n * `readonly`: method code owns only the `annotations` bag. A child copies this\n * off the live parent when the delegated call fires, so mutating it mid-run\n * would corrupt the child's correlation id.\n */\n readonly callId: string | null;\n /**\n * 0 at the outermost call; `parent.depth + 1` for a delegated call. `readonly`\n * for the same reason as `callId` — a mutated depth would mis-nest children\n * and, where ALS can't correct it (browsers), duplicate telemetry.\n */\n readonly depth: number;\n /**\n * Per-invocation scratch space. Never forwarded to callees — a child call\n * gets a fresh bag — so annotations describe one method's own invocation.\n * Method `run` code contributes through the run bag's `annotate` function\n * rather than writing here directly; the bag reference is fixed, only its\n * contents change.\n */\n readonly annotations: Annotations;\n /**\n * Origin of the call's root, copied verbatim to every child. `\"surface\"`\n * (the default) marks a surface-origin root — a call that entered through the\n * SDK surface, or a parent-less runtime delegation that still represents real\n * user work (e.g. a delegation proxy reaching another method). `\"internal\"`\n * marks a framework-internal root minted by kitcore's own build-time machinery\n * (resolver/formatter/dispose/observer twins, `resolvePlugin`), which a head\n * can suppress from telemetry. Orthogonal to `depth`: an internal root is\n * still `depth 0`. `readonly` so a child can't inherit a mutated origin.\n */\n readonly callOrigin: CallOrigin;\n readonly [CALL_CONTEXT_BRAND]: true;\n}\n\n/**\n * Strict brand check. A bare value in the boundary's second argument slot — the\n * array index from `items.map(sdk.method)`, say — fails this, so such a call is\n * treated as a root rather than an id-bearing child.\n */\nexport function isCallContext(value: unknown): value is CallContext {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { [CALL_CONTEXT_BRAND]?: unknown })[CALL_CONTEXT_BRAND] === true\n );\n}\n\n/**\n * Mint a call id: prefer `crypto.randomUUID()`, fall back to a v4 UUID built\n * from `crypto.getRandomValues`, and degrade to `null` rather than throwing\n * where neither is available (e.g. a non-secure browser context). The boundary\n * must never throw on id minting, so this is fully guarded.\n */\nfunction generateCallId(): string | null {\n try {\n const webCrypto = (\n globalThis as {\n crypto?: {\n randomUUID?: () => string;\n getRandomValues?: (array: Uint8Array) => Uint8Array;\n };\n }\n ).crypto;\n if (webCrypto?.randomUUID) {\n return webCrypto.randomUUID();\n }\n if (webCrypto?.getRandomValues) {\n const bytes = webCrypto.getRandomValues(new Uint8Array(16));\n const hex = Array.from(bytes, (byte, i) => {\n // Stamp the version (4) and variant (10xx) nibbles per RFC 4122.\n const value =\n i === 6\n ? (byte & 0x0f) | 0x40\n : i === 8\n ? (byte & 0x3f) | 0x80\n : byte;\n return value.toString(16).padStart(2, \"0\");\n });\n return [\n hex.slice(0, 4).join(\"\"),\n hex.slice(4, 6).join(\"\"),\n hex.slice(6, 8).join(\"\"),\n hex.slice(8, 10).join(\"\"),\n hex.slice(10, 16).join(\"\"),\n ].join(\"-\");\n }\n } catch {\n // Fall through to null.\n }\n return null;\n}\n\n/**\n * A fresh root context: a new `callId`, depth 0, and an empty annotation bag.\n * Surface-origin (`callOrigin: \"surface\"`) unless a caller opts into a\n * framework-internal root — only kitcore's own build-time machinery does.\n */\nexport function rootCallContext({\n callOrigin = \"surface\",\n}: { callOrigin?: CallOrigin } = {}): CallContext {\n return {\n callId: generateCallId(),\n depth: 0,\n annotations: {},\n callOrigin,\n [CALL_CONTEXT_BRAND]: true,\n };\n}\n\n/**\n * A child of `parent`: same `callId`, `depth + 1`, and a fresh annotation bag\n * (annotations are per-invocation and never inherited). Origin is inherited, so\n * a delegated subtree carries its root's `callOrigin`.\n */\nexport function childCallContext(parent: CallContext): CallContext {\n return {\n callId: parent.callId,\n depth: parent.depth + 1,\n annotations: {},\n callOrigin: parent.callOrigin,\n [CALL_CONTEXT_BRAND]: true,\n };\n}\n","/**\n * Framework options (`CoreOptions`) and their well-known configuration id.\n * Heads inject the bag under `CORE_OPTIONS_ID` via `createSdk`'s\n * `configuration`; the method boundary resolves it by id at every invocation\n * (`resolveCoreOptions`), and `coreOptionsPluginRef` (model/builtins) is the\n * importable stand-in for plugins that need the same options.\n */\n\nimport type { AdaptError } from \"../types/errors\";\nimport type { FunctionDeprecation } from \"../types/registry\";\nimport type { StabilityLevel } from \"./stability\";\nimport { logDeprecation, logStabilityNotice } from \"./logging\";\n\n/**\n * What the boundary reports when a deprecated method is called: the method\n * plus its declared `deprecation` meta, whole, so future declaration fields\n * ride along without a signature change. `type` makes the record\n * self-describing (the shape a future unified event channel would carry;\n * see docs/design/2026-06-04-unified-event-bus.md).\n */\nexport interface DeprecationWarning {\n type: \"deprecation\";\n methodName: string;\n deprecation: FunctionDeprecation;\n}\n\n/**\n * The default `logDeprecation` handler: format the one-line warning and pass\n * it through kitcore's deduping logger, so the built-in policy is\n * once-per-process per message.\n */\nexport function defaultLogDeprecation({\n methodName,\n deprecation,\n}: DeprecationWarning): void {\n logDeprecation(`${methodName}() is deprecated. ${deprecation.message}`);\n}\n\n/**\n * What the boundary reports when a non-stable (beta / experimental) method\n * is called: the method plus its declared level. `DeprecationWarning`'s\n * sibling — same self-describing shape, same handler-not-observer contract.\n */\nexport interface StabilityNotice {\n type: \"stability\";\n methodName: string;\n stability: StabilityLevel;\n}\n\n// What each non-stable tier's warning must convey. Stable never signals,\n// so it has no entry.\nconst STABILITY_NOTICE_DETAILS: Record<\n Exclude<StabilityLevel, \"stable\">,\n string\n> = {\n beta: \"Its API shape is settled, but it is not yet covered by stable-tier guarantees.\",\n experimental: \"It may change shape or disappear without notice.\",\n};\n\n/**\n * The default `logStabilityNotice` handler: format the one-line warning and\n * pass it through kitcore's deduping logger (once-per-process per message),\n * exactly like {@link defaultLogDeprecation}.\n */\nexport function defaultLogStabilityNotice({\n methodName,\n stability,\n}: StabilityNotice): void {\n if (stability === \"stable\") return;\n logStabilityNotice(\n `${methodName}() is a ${stability} API. ${STABILITY_NOTICE_DETAILS[stability]}`,\n );\n}\n\n/**\n * The well-known id for framework options: heads inject a `CoreOptions` bag\n * under it via `createSdk`'s `configuration` (or register a property plugin),\n * and the method boundary resolves it by id at every invocation, falling back\n * to the legacy `context.core` write while the deprecated `createCorePlugin`\n * path still exists.\n */\nexport const CORE_OPTIONS_ID = \"kitcore/coreOptions\";\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 * The deprecation HANDLER (adaptError's sibling, not an observer): the\n * framework signals every call of a method declaring `deprecation` meta,\n * and this gate decides what happens — policy (how often to tell; the\n * deduping deprecation loggers make once-per-process one line) and\n * presentation. Exactly one: absent falls back to\n * {@link defaultLogDeprecation}, supplied replaces it. Runs isolated, so a\n * throwing handler never breaks the observed call. Additive observation\n * (many subscribers, e.g. telemetry counting hits) is a different concept\n * reserved for an `on*`-named observer when the unified event bus lands.\n */\n logDeprecation?: (warning: DeprecationWarning) => void;\n /**\n * `logDeprecation`'s sibling for API stability: the framework signals\n * every surface call of a method declaring a non-stable `stability`\n * level (beta / experimental), and this gate decides what happens.\n * Exactly one: absent falls back to {@link defaultLogStabilityNotice}\n * (once-per-process per message), supplied replaces it. Runs isolated,\n * so a throwing handler never breaks the observed call. Internal\n * delegation never signals, matching the deprecation contract.\n */\n logStabilityNotice?: (notice: StabilityNotice) => void;\n /**\n * Report what output validation stripped, on the response's\n * `meta.outputDataValidation.droppedPaths`. Off by\n * default: the report is a debugging aid for reconciling a schema against the\n * wire, and a sidecar every caller has to ignore is worse than one a head\n * turns on while it audits its schemas. Off also skips the recursive\n * raw-vs-parsed diff, so the strip costs a parse and nothing more.\n */\n includeOutputValidationDroppedPaths?: boolean;\n}\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 { validateOptions } from \"./validation\";\nimport {\n mergeCallOptions,\n parseCallOptions,\n type FrameworkOptionsPolicy,\n} from \"./call-options\";\nimport {\n getCurrentDepth,\n isInsideObserver,\n runInMethodScope,\n runIsolatedObserver,\n} from \"./method-scope\";\nimport {\n isCallContext,\n rootCallContext,\n type Annotations,\n type CallContext,\n} from \"./call-context\";\nimport type { ComposedAnnotator, MethodHooks } from \"./build-hooks\";\nimport {\n CORE_OPTIONS_ID,\n defaultLogDeprecation,\n defaultLogStabilityNotice,\n type CoreOptions,\n type DeprecationWarning,\n type StabilityNotice,\n} from \"./core-options\";\nimport type { FunctionDeprecation } from \"../types/registry\";\nimport type { StabilityLevel } from \"./stability\";\n\n/**\n * Minimal SDK shape the function wrappers accept. The wrappers only\n * touch `context.hooks` and the resolved core options, but we keep\n * `context` 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 };\ntype PluginsContext = {\n plugins?: Record<\n string,\n { value?: unknown; getValue?: () => unknown } | undefined\n >;\n};\n\n/**\n * Resolve the framework options at invocation time: the module-model value\n * registered (or injected) under `kitcore/coreOptions` wins; the legacy\n * `context.core` write is the fallback while both paths exist. Read live per\n * call, preserving the late-binding contract for framework state.\n */\nexport function resolveCoreOptions(context: unknown): CoreOptions | undefined {\n const entry = (context as PluginsContext).plugins?.[CORE_OPTIONS_ID];\n if (entry) {\n return (entry.getValue ? entry.getValue() : entry.value) as\n | CoreOptions\n | undefined;\n }\n return (context as CoreContext).core;\n}\n\n/**\n * Marks a call as internal delegation (one plugin calling another through its\n * `imports` bag or `resolvePlugin`): materialization's import-facing bindings\n * pass this sentinel in the boundary's second argument slot, and the boundary\n * reads it via `arguments[1]` so its declared signature and arity stay\n * single-parameter. Surface-only concerns (the deprecation signal) fire only\n * when the sentinel is absent — the consumer chose the deprecated surface;\n * a delegating sibling did not. Identity-checked because surface callables\n * leak into arg-forwarding call sites (`items.map(sdk.method)` passes an\n * index here). A private `Symbol()` on purpose: the writer (internal binding)\n * and reader (boundary) are always created together by the same kitcore copy,\n * so it never crosses bundled-copy lines (contrast `CONTEXT`, which other\n * copies read by design and so lives in the global registry) — and\n * `Symbol.for` would make \"internal\" forgeable by any code.\n */\nexport const INTERNAL_CALL: unique symbol = Symbol(\"kitcore.internalCall\");\n\n/**\n * Resolve the per-call context from the boundary's second argument slot. A\n * caller's internal twin passes a child {@link CallContext} there (nested call,\n * inherits the root's `callId`); anything else — the `INTERNAL_CALL` sentinel, a\n * stray `items.map(sdk.method)` index, or nothing — is an outermost call and\n * mints a fresh root. Depth and correlation ride this value instead of ambient\n * ALS, so nesting is tracked correctly even where `async_hooks` is unavailable.\n */\nfunction resolveCallContext(secondArg: unknown): CallContext {\n return isCallContext(secondArg) ? secondArg : rootCallContext();\n}\n\n// A hook annotator may close over an SDK and invoke another method despite not\n// receiving imports. Suppress hook annotation for that nested invocation so it\n// cannot recurse; the nested method's own annotator and lifecycle still run.\nlet hookAnnotatorReentrancy = 0;\n\ninterface ApplyAnnotationsOptions {\n context: CallContext;\n methodName: string;\n input: unknown;\n hookAnnotator?: ComposedAnnotator;\n methodAnnotator?: (input: unknown) => Annotations;\n}\n\n/**\n * Populate the call's annotation bag before `onMethodStart`: composed hook\n * annotators first, then the method's own annotator. Both annotation sources are\n * best-effort and receive raw, pre-validation input. Hook annotators run only\n * for the outermost surface-origin invocation and are suppressed inside\n * observers and during hook-annotator re-entry. The method annotator runs for\n * every invocation so method behavior does not depend on its entry path.\n */\nfunction applyAnnotations({\n context,\n methodName,\n input,\n hookAnnotator,\n methodAnnotator,\n}: ApplyAnnotationsOptions): void {\n if (\n hookAnnotator &&\n !isInsideObserver() &&\n context.depth === 0 &&\n context.callOrigin !== \"internal\" &&\n hookAnnotatorReentrancy === 0\n ) {\n hookAnnotatorReentrancy++;\n try {\n Object.assign(context.annotations, hookAnnotator({ methodName, input }));\n } catch {\n // Annotation inference must never break the call.\n } finally {\n hookAnnotatorReentrancy--;\n }\n }\n try {\n Object.assign(context.annotations, methodAnnotator?.(input));\n } catch {\n // Annotation inference must never break the call.\n }\n}\n\n/**\n * A declared deprecation IS the runtime signal: the boundary reports every\n * SURFACE call of a deprecated method to the head's `logDeprecation` handler\n * (policy + presentation live there; the default dedupes once-per-process\n * through kitcore's logger). Internal delegation (see {@link INTERNAL_CALL})\n * never signals: a user running `curl` must not be warned that `fetch` is\n * deprecated because curl delegates to it. `getDeprecation` is a live read of\n * the method entry's meta, so a deprecation merged after build\n * (`defineMethodOverride`, an `addPlugin`-applied override) still fires. Runs\n * isolated, so a throwing handler never breaks the call and a deprecated\n * method the handler itself calls doesn't recurse.\n */\nfunction signalDeprecation(\n context: unknown,\n methodName: string,\n getDeprecation?: () => FunctionDeprecation | undefined,\n): void {\n if (isInsideObserver()) return;\n const deprecation = getDeprecation?.();\n if (!deprecation?.message) return;\n const warning: DeprecationWarning = {\n type: \"deprecation\",\n methodName,\n deprecation,\n };\n const handler =\n resolveCoreOptions(context)?.logDeprecation ?? defaultLogDeprecation;\n runIsolatedObserver(() => handler(warning));\n}\n\n/**\n * `signalDeprecation`'s sibling for API stability: the boundary reports\n * every SURFACE call of a beta / experimental method to the head's\n * `logStabilityNotice` handler (the default dedupes once-per-process), so a\n * consumer of a bundled build gets told at runtime what the editor and docs\n * badges say at authoring time. Same contract throughout: internal\n * delegation never signals, `getStability` is a live read of the method\n * entry's meta, and the handler runs isolated so a throw never breaks the\n * observed call.\n */\nfunction signalStability(\n context: unknown,\n methodName: string,\n getStability?: () => StabilityLevel | undefined,\n): void {\n if (isInsideObserver()) return;\n const stability = getStability?.();\n if (!stability || stability === \"stable\") return;\n const notice: StabilityNotice = {\n type: \"stability\",\n methodName,\n stability,\n };\n const handler =\n resolveCoreOptions(context)?.logStabilityNotice ??\n defaultLogStabilityNotice;\n runIsolatedObserver(() => handler(notice));\n}\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, context?: CallContext) => Promise<TResult>,\n options: {\n sdk: FunctionSdk;\n schema?: z.ZodSchema<TSchemaOptions>;\n name?: string;\n /** Pre-run per-method annotator (see applyAnnotations): invoked before\n * onMethodStart with the normalized input, its result merged into the\n * call's annotation bag. */\n annotator?: (input: unknown) => Annotations;\n /** Which framework call parameters this callable reads; see\n * `FrameworkOptionsPolicy`. Omitted means none, which is what a legacy\n * handler wants: nothing there honors a framework parameter, so every key\n * in the call object is the handler's own. */\n frameworkOptions?: FrameworkOptionsPolicy;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n) {\n const {\n sdk,\n schema,\n name,\n annotator,\n frameworkOptions,\n getDeprecation,\n getStability,\n } = 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 const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, functionName, getDeprecation);\n signalStability(sdk.context, functionName, getStability);\n }\n return runInMethodScope(async () => {\n const startTime = Date.now();\n const normalizedOptions = (callOptions ?? {}) as TOptions;\n const args: unknown[] = [normalizedOptions];\n // Dedup depth comes from the explicit context — the signal that\n // survives where `async_hooks` is unavailable (browsers). ALS still\n // contributes while it lives, so nested paths that don't yet thread a\n // context stay deduped; that term drops once ALS is retired.\n const depth = Math.max(context.depth, getCurrentDepth());\n // Read live: a plugin contributing hooks or adaptError after\n // this method was constructed should still apply.\n const insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n\n applyAnnotations({\n context,\n methodName: functionName,\n input: normalizedOptions,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n\n // callId and the annotations bag ride every payload for this call; the\n // bag is one shared reference, so mid-`run` writes are visible by\n // onMethodEnd.\n const hookBase = {\n methodName: functionName,\n args,\n isPaginated: false,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n\n hooks?.onMethodStart?.({ ...hookBase });\n\n try {\n // Both schemas run, each on its own terms, and the framework's\n // half wins for anything the plugin's schema refused. See\n // `parseCallOptions`.\n const parsed = parseCallOptions(normalizedOptions, {\n schema,\n policy: frameworkOptions,\n adaptError,\n });\n const result: TResult = await coreFn(\n mergeCallOptions(parsed) as TOptions,\n context,\n );\n\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n });\n\n return result;\n } catch (error) {\n const normalizedError = normalizeError(error, adaptError);\n\n hooks?.onMethodEnd?.({\n ...hookBase,\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 * Wrap a raw method's core with the boundary lifecycle: method scope, live\n * `context.hooks` firing (start/end with `error` on failure), and\n * error-branded input validation via the resolved core options. Unlike\n * `createFunction` there is no envelope and no error normalization on the\n * rethrow path: the ORIGINAL error propagates (raw callers keep error\n * identity, e.g. an `AbortError`), with only the hook payload's `error`\n * coerced for observers. A synchronous core stays synchronous: hooks fire\n * around the call without forcing a promise.\n *\n * `positional` projects the canonical input back onto the caller's argument\n * list for the hook payload, so observers see the call as it was made\n * (`fetch(url, init)`, not one packed object).\n */\nexport function createRawFunction(\n coreFn: (input: unknown, context?: CallContext) => unknown,\n options: {\n sdk: FunctionSdk;\n name: string;\n schema?: z.ZodSchema;\n positional?: readonly string[];\n /** Pre-run per-method annotator (see applyAnnotations). */\n annotator?: (input: unknown) => Annotations;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n): (input: unknown) => unknown {\n const {\n sdk,\n name,\n schema,\n positional,\n annotator,\n getDeprecation,\n getStability,\n } = options;\n // A function expression (not an arrow) so `arguments[1]` can carry the\n // internal-call sentinel (or a child call context) without widening the\n // declared signature.\n return function (rawInput: unknown): unknown {\n const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, name, getDeprecation);\n signalStability(sdk.context, name, getStability);\n }\n return runInMethodScope(() => {\n const startTime = Date.now();\n // Dedup depth comes from the explicit context (the signal that survives\n // where `async_hooks` is unavailable); ALS still contributes until it is\n // retired, so nested paths not yet threading a context stay deduped.\n const depth = Math.max(context.depth, getCurrentDepth());\n const insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n // Validation is the transforming path, so it normalizes a bare call to\n // `{}` before parsing (as `createFunction` always did; a method must\n // never require `fn({})`). The unvalidated path stays genuinely\n // untouched — `skipInputValidation` methods own their input, undefined\n // included.\n const input = schema ? (rawInput ?? {}) : rawInput;\n applyAnnotations({\n context,\n methodName: name,\n input,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n const record = input as Record<string, unknown> | undefined;\n const args: unknown[] = positional\n ? positional\n .filter((key) => record?.[key] !== undefined)\n .map((key) => record?.[key])\n : [input];\n const hookBase = {\n methodName: name,\n args,\n isPaginated: false,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n hooks?.onMethodStart?.({ ...hookBase });\n const fireEnd = (error?: Error): void => {\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n ...(error ? { error } : {}),\n });\n };\n try {\n const parsed = schema\n ? validateOptions(schema, input, { adaptError })\n : input;\n const result = coreFn(parsed, context);\n if (\n result !== null &&\n typeof result === \"object\" &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n return (result as Promise<unknown>).then(\n (value) => {\n fireEnd();\n return value;\n },\n (error: unknown) => {\n fireEnd(\n error instanceof Error ? error : new Error(String(error)),\n );\n throw error;\n },\n );\n }\n fireEnd();\n return result;\n } catch (error) {\n fireEnd(error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n });\n };\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 *\n * `meta` is deliberately NOT allowed even though `SdkPage` declares it: the\n * framework attaches it after this guard, so a page arriving here with `meta`\n * came from a handler or `adaptPage` overstepping the sidecar's owner.\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, context?: CallContext) => Promise<TResponse>,\n {\n sdk,\n adaptPage,\n finalizePage,\n }: {\n sdk: FunctionSdk;\n adaptPage?: (response: TResponse) => SdkPage<TItem>;\n /** Applied to the canonical page after the shape guard, e.g. to validate +\n * strip items and attach `meta.outputDataValidation`. Receives this call's\n * options too, since per-call controls (output validation) ride there and the\n * finalizer itself is built once. */\n finalizePage?: (\n page: SdkPage<TItem>,\n callOptions: unknown,\n ) => 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 callContext?: CallContext,\n ): Promise<SdkPage<TItem>> {\n try {\n const response = await coreFn(options, callContext);\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 finalizePage ? finalizePage(page, options) : page;\n } catch (error) {\n throw normalizeError(\n error,\n resolveCoreOptions(sdk.context)?.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 context?: CallContext,\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 /** Pre-run per-method annotator (see applyAnnotations). */\n annotator?: (input: unknown) => Annotations;\n /** Applied to each canonical page after the shape guard (output validation),\n * with this call's options so it can read per-call controls. */\n finalizePage?: (\n page: SdkPage<TItem>,\n callOptions: unknown,\n ) => SdkPage<TItem>;\n /** Which framework call parameters this callable reads; see\n * `FrameworkOptionsPolicy`. */\n frameworkOptions?: FrameworkOptionsPolicy;\n /** Live read of the method's deprecation meta (see signalDeprecation). */\n getDeprecation?: () => FunctionDeprecation | undefined;\n /** Live read of the method's stability level (see signalStability). */\n getStability?: () => StabilityLevel | undefined;\n },\n): (\n options?: TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n },\n) => PaginatedSdkResult<TItem> {\n const {\n sdk,\n schema,\n name,\n defaultPageSize,\n adaptPage,\n annotator,\n finalizePage,\n frameworkOptions,\n getDeprecation,\n getStability,\n } = options;\n const pageFunction = createPageFunction(coreFn, {\n sdk,\n adaptPage,\n finalizePage,\n });\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 const internal = arguments[1];\n const context = resolveCallContext(internal);\n if (!isCallContext(internal) && internal !== INTERNAL_CALL) {\n signalDeprecation(sdk.context, functionName, getDeprecation);\n signalStability(sdk.context, functionName, getStability);\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 // Dedup depth comes from the explicit context (the signal that survives\n // where `async_hooks` is unavailable); ALS still contributes until it\n // is retired, so nested paths not yet threading a context stay deduped.\n const depth = Math.max(context.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 insideObserver = isInsideObserver();\n const hooks = insideObserver\n ? undefined\n : (sdk.context as HooksContext).hooks;\n const adaptError = resolveCoreOptions(sdk.context)?.adaptError;\n\n applyAnnotations({\n context,\n methodName: functionName,\n input: normalizedOptions,\n hookAnnotator: hooks?.annotator,\n methodAnnotator: annotator,\n });\n\n // Shared across onMethodStart and the deferred/sync onMethodEnd sites\n // below, so every payload for this call carries the same callId and the\n // one live annotations bag.\n const hookBase = {\n methodName: functionName,\n args,\n isPaginated: true,\n depth,\n callId: context.callId,\n callOrigin: context.callOrigin,\n annotations: context.annotations,\n };\n\n hooks?.onMethodStart?.({ ...hookBase });\n\n // Input validation and first-page kickoff run inside a try so a\n // synchronous throw (a schema-invalid call) still fires onMethodEnd and\n // normalizes the error, rather than escaping between onMethodStart and\n // the deferred end (which observers would see as a started-but-never-\n // ended call). On success the deferred end below is the only one that\n // fires; on a sync throw only this catch fires. The two are mutually\n // exclusive (a throw here means no firstPagePromise exists).\n try {\n // Both schemas run, each on its own terms. See `parseCallOptions`.\n // The page loop reads its controls off the merged object, so the\n // framework's half has to be on it whatever the plugin declared.\n const validatedOptions = mergeCallOptions(\n parseCallOptions(normalizedOptions, {\n schema,\n policy: frameworkOptions,\n adaptError,\n }),\n ) as TUserOptions & {\n cursor?: string;\n pageSize?: number;\n maxItems?: number;\n };\n\n const pageSize = validatedOptions.pageSize ?? defaultPageSize;\n const optimizedOptions = {\n ...validatedOptions,\n pageSize,\n };\n\n // Every page shares this one `context`, so a paginated call keeps a\n // single `callId`/depth across pages. The wrapper closes over it, so\n // pages pulled lazily by the consumer — after this synchronous body\n // (and its method scope) has returned — still carry the context that\n // ambient ALS could not reach.\n const iterator = paginate(\n (pageOptions: Parameters<typeof pageFunction>[0]) =>\n pageFunction(pageOptions, context),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n optimizedOptions as any,\n );\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 once the first page settles. The two-arg\n // `then(onFulfilled, onRejected)` (not `then().catch()`) keeps the\n // rejection handler one hop off `firstPagePromise`, beside the\n // success handler, rather than a hop behind it. Both are registered\n // before the caller awaits the same promise, so onMethodEnd fires\n // before the caller resumes on failure too, matching the\n // non-paginated path. It also makes the two handlers mutually\n // exclusive, so a throw in the success handler can't re-fire the end\n // through a trailing `.catch`.\n if (hooks?.onMethodEnd) {\n firstPagePromise.then(\n () => {\n hooks.onMethodEnd!({\n ...hookBase,\n durationMs: Date.now() - startTime,\n });\n },\n (error) => {\n hooks.onMethodEnd!({\n ...hookBase,\n durationMs: Date.now() - startTime,\n error:\n error instanceof Error ? error : new Error(String(error)),\n });\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 views over ONE page stream: it emits the\n // buffered first page, then the rest of the shared cursor. Bare\n // iteration and `.pages()` hand back this single stream; `.items()`\n // is a view that pulls the same stream and flattens each page.\n // Because the buffered page is emitted by exactly one stream,\n // consuming any view drains the others (the second sees nothing)\n // rather than replaying page 1 over an exhausted cursor (the\n // 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 // `.pages()` is a plain iterable (not a thenable), so unlike the\n // result itself it survives being returned from an async function.\n return Object.assign(firstPagePromise, {\n [Symbol.asyncIterator]() {\n return pageStream;\n },\n pages: function () {\n return {\n [Symbol.asyncIterator]() {\n return pageStream;\n },\n };\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 } catch (error) {\n const normalizedError = normalizeError(error, adaptError);\n hooks?.onMethodEnd?.({\n ...hookBase,\n durationMs: Date.now() - startTime,\n error: normalizedError,\n });\n throw normalizedError;\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 { PAGE_FRAMEWORK_OPTIONS } from \"./call-options\";\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n \"createPluginMethod() is deprecated. Author methods with defineMethod instead.\",\n );\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n 'createPaginatedPluginMethod() is deprecated. Author list methods with defineMethod output \"list\" instead.',\n );\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 // The page loop reads the page controls out of the call object, so a\n // handler's schema does not have to declare them. It reads nothing else:\n // no legacy handler honors the caller's output skip.\n frameworkOptions: PAGE_FRAMEWORK_OPTIONS,\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 */\n/**\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\n */\nexport function createPluginStack<TRequires = object>(): PluginStack<\n TRequires,\n {\n context: {\n meta: Record<string, PluginMeta>;\n hooks: MethodHooks;\n };\n }\n> {\n logDeprecation(\n \"createPluginStack() is deprecated. Compose with definePlugin and build with createSdk instead.\",\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","/**\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 *\n * `Symbol.for`, not `Symbol()`: heads bundle kitcore (tsup `noExternal`), so\n * an sdk built by one bundle's copy must still be readable by another copy's\n * `getContext` / `resolvePlugin` (e.g. a CLI sdk inspected with helpers\n * imported from `@zapier/zapier-sdk`). The global symbol registry makes every\n * copy agree on the key.\n */\nexport const CONTEXT: unique symbol = Symbol.for(\"kitcore.context\");\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 { CONTEXT } from \"./shared\";\nimport type { Annotations, CallContext } from \"../utils/call-context\";\nimport type { PluginMeta, PluginProvides } from \"../types/plugin\";\nimport type {\n MethodHooks,\n OnMethodStartContext,\n OnMethodEndContext,\n} 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 { StabilityLevel } from \"../utils/stability\";\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 /** Behavioral opt-out that rides on this config for every `defineMethod`\n * overload (all merge `LeafMetaFields`), the partner of `outputSchema`: when\n * true, the materializer skips validating/stripping the output. It is\n * consumed at build time and stored as a first-class plugin field, NOT folded\n * into the projected meta (hence absent from `LEAF_META_KEYS`), so it stays\n * off the registry / CLI / MCP surface, exactly like `skipInputValidation`. */\n skipOutputValidation?: boolean;\n packages?: string[];\n stability?: StabilityLevel;\n /** @deprecated Use `stability: \"experimental\"` instead. */\n experimental?: boolean;\n confirm?: \"create-secret\" | \"delete\";\n deprecation?: FunctionDeprecation;\n aliases?: Record<string, string>;\n supportsJsonOutput?: boolean;\n}\n\n/**\n * The meta an override may patch onto an already-built method.\n *\n * An allow-list, so a field added to {@link LeafMetaFields} later is refused\n * until someone decides it is safe. Naming the dangerous fields instead would\n * hand every future field to overrides by default, and the default has to be\n * the safe one: an override changes how a surface PRESENTS a method, never what\n * runs, what input is accepted, or what safety gate fires. Nothing re-checks\n * the method's declared TypeScript type after `defineMethod` fixes it.\n *\n * What that rule rules out, and why each is dangerous rather than merely\n * unused:\n *\n * - `outputSchema` decides what output validation enforces. Patching it makes\n * a call fail against a contract its own return type says it satisfies.\n * - `confirm` gates a host's confirmation prompt. Patching it can drop the\n * prompt in front of a destructive call.\n * - `type` reaches `confirm` indirectly: the registry derives\n * `confirm: m.confirm ?? (m.type === \"delete\" ? \"delete\" : undefined)`, so\n * moving a method off `\"delete\"` removes the same prompt quietly.\n * - `aliases` maps a parameter to a CLI flag, so patching it changes which\n * input a caller can pass.\n * - `skipOutputValidation` is already unreachable, being absent from\n * `LEAF_META_KEYS` and never folded into the projected meta.\n */\nexport type OverridableMetaFields = Pick<\n LeafMetaFields,\n | \"description\"\n | \"categories\"\n | \"itemType\"\n | \"returnType\"\n | \"packages\"\n | \"experimental\"\n | \"deprecation\"\n | \"supportsJsonOutput\"\n>;\n\n/** One segment of a {@link DynamicMember} path: a literal binding/segment name,\n * or a `{ param }` placeholder for an open-ended key (rendered `{param}`). */\nexport type DynamicMemberSegment = string | { param: string };\n\n/**\n * A templated registry member: a dynamic sub-surface with no static binding\n * (e.g. `apps.{appKey}.{actionType}.{actionKey}`), backed at runtime by a proxy.\n * It is a bodyless declaration — the same descriptive fields an author sets on a\n * leaf, keyed by a `path` instead of a `name`. The framework derives the\n * registry name by joining the path (params rendered `{param}`) and folds these\n * fields into a `PluginMeta` for the registry / CLI / MCP / docs projection.\n * `path[0]` must be a literal that resolves to a real surfaced binding (the\n * owning member).\n */\nexport type DynamicMember = {\n path: readonly DynamicMemberSegment[];\n /** Projection-only input schema (no runtime; the proxy validates its own). */\n inputSchema?: z.ZodType;\n} & LeafMetaFields;\n\n/** A {@link DynamicMember} normalized at define time: the derived registry name,\n * the literal root segment (validated against the surface), and the folded meta. */\nexport interface NormalizedDynamicMember {\n name: string;\n rootBinding: string;\n meta: PluginMeta;\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 \"packages\",\n \"stability\",\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 /** True when the edge came from a `declareOptionalProperty` stand-in: if no real\n * plugin satisfies the id, the binding resolves to `undefined` instead of\n * failing the build as a missing dependency. */\n optional?: boolean;\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 * What `run` sees, given what a CALLER may pass.\n *\n * Subtracts exactly what the runtime strips on the way in, so the type and\n * `stripFrameworkOnlyOptions` cannot drift. The subtraction is unconditional,\n * matching the runtime: a method that DECLARES `maxItems` still does not\n * receive it, because a list `run` fetches one page and the cap spans pages.\n */\nexport type ItemRunInput<TInput> = Omit<TInput, \"skipOutputDataValidation\">;\n\n/** The list twin of {@link ItemRunInput}, plus the page `run` is asked for. */\nexport type ListRunInput<TInput> = Omit<\n TInput,\n \"skipOutputDataValidation\" | \"maxItems\"\n> &\n PageFetchInput;\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 — exactly the dependency's {@link PluginSurface}.\n */\nexport type BindingsOf<TDep extends AnyPlugin> = PluginSurface<TDep>;\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; `callContext` is the live per-call\n * context (call identity plus the annotation bag the boundary reads back on the\n * lifecycle hooks); `annotate` merges mid-run-derived telemetry fields into that\n * bag. Prefer `annotate` over writing `callContext.annotations` directly.\n */\nexport interface MethodRunBag<TImports, TInput, TState = unknown> {\n imports: TImports;\n state: TState;\n input: TInput;\n callContext: CallContext;\n /** Merge mid-run-derived telemetry fields into the call's annotation bag. The\n * declarative pre-run sibling is the method's `annotator` config; both add\n * to the same bag, one during `run`, one before it. */\n annotate: (metadata: Annotations) => void;\n}\n\n/**\n * A method's declarative pre-`run` annotator: given the method's raw,\n * pre-validation `input`, it returns {@link Annotations} the boundary merges\n * into the call's bag before `onMethodStart`. The input is `unknown` because\n * schema coercion/transformation has not run; an annotator must narrow it before\n * reading fields. A provider with nothing to add returns an empty bag, so absence\n * is modelled by no provider rather than an `undefined` return.\n */\nexport type MethodAnnotator = (bag: { input: unknown }) => Annotations;\n\n/**\n * A hook's declarative pre-`run` annotator: like {@link MethodAnnotator} but\n * cross-cutting, so it also receives the `methodName` and the hook's `state`.\n * Many hooks' annotators coexist; the boundary composes them.\n */\nexport type HookAnnotator<TState = unknown> = (bag: {\n methodName: string;\n input: unknown;\n state: TState;\n}) => Annotations;\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/**\n * One entry in `requireParameters`. A bare NAME is looked up in the resolver's\n * own container first, then at the root. That is convenient, and ambiguous when\n * both hold the name: the container wins, silently. An ARRAY is an absolute\n * path from the root (`[\"input\", \"owner\"]`), matching the engine's own path\n * representation, so it says exactly which value is meant, and it also reaches\n * a field inside another parameter that no bare name can name.\n *\n * An index in a path is LITERAL. `[\"filters\", 0, \"operator\"]` names the first\n * item and no other, so it cannot address the array item currently being\n * walked. A requirement inside an array item names its sibling with a bare\n * name, which resolves against the item.\n *\n * A dotted string is NOT a path: the engine looks the whole string up as one\n * key, so `\"input.owner\"` silently never matches. Use the array form.\n */\nexport type ResolverRequirement =\n | string\n // A NON-EMPTY tuple. An empty path names nothing, and the walk resolves a\n // path with `getAtPath`, which traverses zero segments and hands back the\n // resolved root. That object is not `undefined`, so the gate would read the\n // requirement as already satisfied and run the resolver early.\n | readonly [string | number, ...(string | number)[]];\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 /** Parameters that must resolve before this resolver runs (it reads their\n * values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. See {@link ResolverRequirement} for the\n * bare-name vs absolute-path forms. */\n requireParameters?: readonly ResolverRequirement[];\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 (the engine awaits the first page + `nextCursor`), never a\n * bare array. `cursor` is the stateless re-entry hook for \"load more\": the\n * engine awaits one page, carries `nextCursor`, and calls again with `cursor`.\n * Required: a dynamic resolver IS a candidate-lister; a free-text field (with\n * or without auto-resolution someday) is the `static` kind's job. */\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 /** The CURRENT page's items only — the engine windows the listing one\n * page at a time (an accumulating host may be showing more). Rendering\n * input only; validation is the top-level `validate`. */\n items: unknown[];\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n }) => ResolverPromptConfig;\n /** Check a chosen/typed value before the engine accepts it. Async with\n * `imports` so it can verify against the source (`tryResolveFromSearch`'s\n * sibling for picks) — never against a loaded page: pagination means the\n * pick can come from a page the engine no longer holds. Return true to\n * accept or a message to re-ask with. A throw is a lookup failure (the\n * host gets retry/cancel), not a rejection. */\n validate?: (bag: {\n imports: Record<string, unknown>;\n value: unknown;\n input: Record<string, unknown>;\n /** The value `getContext` returned, if any. */\n context?: unknown;\n }) => Promise<true | string> | true | string;\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 /** Open-ended entries whose keys aren't known up front (a `z.record`): the\n * walk collects entries in an add/done loop, asking each entry's key (via\n * `keys`, default a free-text string) then its value (via `values`), and\n * assembling them onto the object alongside any fixed `properties`. The\n * JSON-Schema `additionalProperties` analog. */\n additionalKeys?: AdditionalKeys;\n}\n\n/** The open-keyed-entry spec for an {@link ObjectResolver.additionalKeys}. */\nexport interface AdditionalKeys {\n /** Resolver for each entry's key; defaults to a free-text string prompt. A\n * `{ ref }` resolves against the object's `definitions`. */\n keys?: Resolver | ResolverRef;\n /** Resolver for each entry's value. A `{ ref }` resolves against the\n * object's `definitions`. */\n values: Resolver | ResolverRef;\n minEntries?: number;\n maxEntries?: number;\n /** Coarse value types so a free-text key/value answer coerces (usually\n * `\"string\"` for the key), the way `Field.valueType` does. */\n keyValueType?: string;\n valueValueType?: string;\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 * (the engine awaits the first page + `nextCursor`), or a plain page / promise\n * of one. No bare array and no scalar: it behaves like any other list method,\n * 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/** Fields shared by every bound resolver kind. */\ninterface BoundResolverBase {\n /** Parameters that must resolve before this resolver runs (it reads their\n * values from `input`). The param-dataflow prerequisite, distinct from\n * `imports`' SDK-capability graph. See {@link ResolverRequirement}. */\n requireParameters?: readonly ResolverRequirement[];\n}\n\n/** Free-text input, no candidate list. */\nexport interface BoundStaticResolver extends BoundResolverBase {\n type: \"static\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: string;\n}\n\n/** A fixed value the author pinned; auto-settles, never asks. */\nexport interface BoundConstantResolver extends BoundResolverBase {\n type: \"constant\";\n value: unknown;\n}\n\n/** Display-only text; resolves no value, never asks. */\nexport interface BoundInfoResolver extends BoundResolverBase {\n type: \"info\";\n text: string;\n}\n\n/** List candidate items (`listItems`) and prompt to pick one; carries the\n * auto-resolution hooks (`tryResolveWithoutPrompt`, `tryResolveFromSearch`). */\nexport interface BoundDynamicResolver extends BoundResolverBase {\n type: \"dynamic\";\n inputType?: \"text\" | \"password\" | \"email\" | \"search\";\n placeholder?: 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 prompt?: (bag: {\n items: unknown[];\n input: Record<string, unknown>;\n context?: unknown;\n }) => ResolverPromptConfig;\n validate?: (bag: {\n value: unknown;\n input: Record<string, unknown>;\n context?: unknown;\n }) => Promise<true | string> | true | string;\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/** Keyed members: static `properties` (bound) or a `getProperties`-built\n * (unbound) field map; `definitions` holds ref targets. `additionalKeys`\n * carries open-ended entries (a `z.record`). */\nexport interface BoundObjectResolver extends BoundResolverBase {\n type: \"object\";\n properties?: Record<string, BoundField>;\n definitions?: Record<string, BoundResolver>;\n getProperties?: (bag: {\n input: Record<string, unknown>;\n }) => PromiseLike<Record<string, Field>>;\n additionalKeys?: BoundAdditionalKeys;\n}\n\n/** The bound form of {@link AdditionalKeys}: `keys`/`values` are bound (or a\n * `{ ref }` into the object's `definitions`). */\nexport interface BoundAdditionalKeys {\n keys?: BoundResolver | ResolverRef;\n values: BoundResolver | ResolverRef;\n minEntries?: number;\n maxEntries?: number;\n keyValueType?: string;\n valueValueType?: string;\n}\n\n/** A homogeneous list resolved through `items` (bound, or a ref into\n * `definitions`). */\nexport interface BoundArrayResolver extends BoundResolverBase {\n type: \"array\";\n items: BoundResolver | ResolverRef;\n minItems?: number;\n maxItems?: number;\n /** The element's coarse value type, used to coerce a free-text item answer\n * before validation (see {@link ArrayResolver.itemValueType}). */\n itemValueType?: string;\n definitions?: Record<string, BoundResolver>;\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). A discriminated union mirroring\n * {@link Resolver}, so kind-specific field access compiles only behind a\n * `type` narrow (the binder's switch is the one exhaustiveness-checked\n * dispatch; the engine's if-chains get the field-access check).\n */\nexport type BoundResolver =\n | BoundStaticResolver\n | BoundConstantResolver\n | BoundInfoResolver\n | BoundDynamicResolver\n | BoundObjectResolver\n | BoundArrayResolver;\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 * What `run` receives, when that differs from what a CALLER may pass.\n *\n * They part company for item and list, whose call type mixes in\n * {@link CallOutputOptions} and {@link PaginatedCallInput}. Those are the\n * framework's, peeled off before `run`, so folding them into one parameter\n * told a consumer reading `Parameters<typeof plugin.run>[0]` that `run` gets\n * a flag the runtime always removes.\n *\n * Defaults to `TInput`, since raw's caller and `run` see the same object.\n */\n TRunInput = TInput,\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 /** True for a `declareOptionalMethod` stand-in: dependents bind `undefined` if\n * no real plugin satisfies it, and `PluginSurface` types the binding\n * `| undefined`. */\n optional?: boolean;\n /** Present on a `declareDefault` wrapper: this entry is the DEFAULT provider\n * for its id (preempted by any explicit provider). Its value is the wrapped\n * plugin, so two defaults for one id dedup (same source) or conflict\n * (different source). */\n defaultSource?: AnyLeafPlugin;\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 /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\n /** Validates `input` before `run` and drives the authoring `input` type. */\n inputSchema?: z.ZodType;\n /** When true, skip the runtime validation/parse of `input`: `run` receives the\n * raw input untouched — no coercion, stripping, or cloning — even if\n * `inputSchema` is set (the schema stays for registry / CLI / MCP projection).\n * For raw methods that own their own validation and must not have their input\n * transformed, e.g. `fetch` passing a `RequestInit` bag through unchanged. */\n skipInputValidation?: boolean;\n /** When true, the materializer skips validating/stripping `run`'s output\n * against `meta.outputSchema` (the schema stays for projection). The output\n * partner of {@link MethodPlugin.skipInputValidation}. */\n skipOutputValidation?: boolean;\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 /** Declarative pre-`run` annotator: the boundary invokes it before\n * `onMethodStart` with the (pre-validation) `input`, and merges its returned\n * `Annotations` into the call's bag. Runs synchronously and receives only\n * `input` — the per-method sibling of the run bag's mid-`run` `annotate`,\n * which is where fields needing imports or async work are written. For\n * telemetry fields knowable before the method's own work; never passed to\n * `run`. */\n annotator?: MethodAnnotator;\n /**\n * Phantom, never present at runtime. `TInput` types the CALL and `TRunInput`\n * types `run`, and once they differ `run` alone cannot tell a reader which is\n * which: an interface is structural, so a parameter that appears nowhere in\n * the body is not inferable. `ExportSurface` recovers the call type from\n * here. Optional and `undefined`-valued, so no implementation writes it.\n */\n readonly __callInput?: TInput;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: (bag: MethodRunBag<any, TRunInput, 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 * Phantom carrier for the CALL input.\n *\n * `TInput` and `TRunInput` differ for item and list, and `run` types the\n * latter. An interface is structural, so a parameter appearing nowhere in the\n * body is not inferable, and without this `ExportSurface` would recover the\n * run input and offer callers the wrong shape. Never present at runtime.\n * @internal\n */\n readonly [CALL_INPUT]?: TInput;\n}\n\n/** Phantom-only key (see `MethodPlugin`); never set at runtime. */\ndeclare const POSITIONAL_NAMES: unique symbol;\n\n/** Phantom-only key (see `MethodPlugin`); never set at runtime. */\ndeclare const CALL_INPUT: 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 * Output controls a method's public caller may pass, the sibling of\n * {@link PaginatedCallInput}: caller-side only, peeled before `run`, and never\n * part of a plugin's declared input, so `run` never sees it.\n *\n * Item and list only, and raw's absence is a decision rather than a gap: raw\n * reserves NOTHING in the caller's call object. That object is entirely the\n * author's, and raw is the mode most likely to forward it verbatim into a\n * request, so a framework key shadowing a domain one there is the worst version\n * of a collision the framework should not create. A `skipOutputDataValidation`\n * passed to a raw method is domain input that happens to share the name: not\n * read, not stripped, and it does not skip.\n *\n * Raw still validates. The author's `skipOutputValidation` field is the only\n * opt-out it honors, which is why that field keeps its name across every mode.\n */\nexport type CallOutputOptions = { skipOutputDataValidation?: boolean };\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/**\n * A response whose only own key is `data`. Gates the item overload of\n * `defineMethod` the way `StrictPage` gates list-standard: `run` returns the\n * `{ data }` envelope itself, and an envelope with extra keys is rejected (a\n * future variant may accept metadata alongside `data`).\n */\nexport type StrictItem<TResponse> = { data: unknown } & {\n [K in Exclude<keyof TResponse, \"data\">]?: never;\n};\n\n/** Data type sourced from an item envelope. */\nexport type DataOf<TResponse> = TResponse extends { data: infer TData }\n ? TData\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 skipInputValidation?: boolean;\n output?: OutputConfig;\n positional?: readonly string[];\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n annotator?: MethodAnnotator;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: any) => unknown;\n dispose?: DisposeFn;\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, state })` computes the value from imports and\n * `setup` state, re-running live on each read. An optional `setup` runs once\n * eagerly at createSdk (dependencies first, like a method's `setup`) to build\n * that state. An imported/surfaced property yields 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 /** True for a `declareOptionalProperty` stand-in: an optional reference. If no real\n * property satisfies it, dependents bind `undefined` rather than the build\n * failing on a missing dependency. */\n optional?: boolean;\n /** Present on a `declareDefault` wrapper: this entry is the DEFAULT provider\n * for its id (preempted by any explicit provider). Its value is the wrapped\n * plugin, so two defaults for one id dedup (same source) or conflict\n * (different source). */\n defaultSource?: AnyLeafPlugin;\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 /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\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: {\n imports: Record<string, unknown>;\n state: unknown;\n callContext?: CallContext;\n }) => TValue;\n /** Descriptive metadata for the registry / CLI / MCP / docs (carry-only). */\n meta?: LeafMeta;\n /** Templated registry members for this property's dynamic sub-surface (e.g. a\n * proxy). Carry-only: normalized at define time, folded into the registry. */\n dynamicMembers?: readonly NormalizedDynamicMember[];\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 state: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * The authoring type for a hook's `wrap`: a map whose keys are the method\n * bindings among the hook's `imports` (you can only wrap a method you import)\n * and whose values are contract-preserving wraps. `next` and `input` take the\n * target's input and the wrap must return the target's output, so a wrap that\n * changes the public signature, or that targets a non-imported / non-method\n * binding, does not compile. `state` is the hook's `setup` result (one bag\n * shape across run/observe/wrap; `next` is the only variant).\n */\nexport type MiddlewareMap<TImports, TState = unknown> = {\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 state: TState;\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 * wrap's `imports` is built from, and how a wrap target\n * binding resolves to a method id. */\n importBindings: readonly ImportBinding[];\n exports: TExports;\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>;\n\n/**\n * A patch over an already-defined method's descriptive fields. It carries no\n * `run`: it names an existing method by id (`target`) and, after that method\n * materializes, merges its `meta` (the same public {@link LeafMetaFields} an\n * author sets on `defineMethod`) onto the method's entry, so the surface\n * registry / CLI / MCP / docs project the patched values. For surface-specific\n * tweaks a base method should not carry (e.g. a CLI that deprecates `fetch`\n * while the SDK does not, or a host that hides a method via `packages`).\n *\n * Distinct from a *replacement* (`addPlugin(..., { override: true })`), which\n * swaps the whole implementation and forces re-declaring `run`. An override\n * inherits the target's implementation untouched and only patches meta.\n */\nexport interface MethodOverridePlugin {\n pluginType: \"method-override\";\n name: string;\n id: string;\n /** The id of the method whose meta is patched (its bare name if the method is\n * namespace-less). */\n target: string;\n imports: readonly AnyPlugin[];\n importBindings: readonly ImportBinding[];\n meta?: LeafMeta;\n}\n\n/**\n * A method-lifecycle hook leaf (`defineHook`). `observe` contributes\n * fire-and-forget observers (`onMethodStart` / `onMethodEnd`) that the method\n * boundary fires around every method; they run defensively (an observer error\n * never breaks the observed call). `setup` runs once and owns the hook's state\n * (e.g. a telemetry queue), delivered to the observers.\n * Each observer bag mirrors a method's: `{ imports, input, state }` — `input` is\n * the lifecycle context, and there is no `next` (observers don't participate in\n * the call). The module-model replacement for a legacy plugin that contributed\n * `context.hooks`.\n */\nexport interface HookPlugin<TName extends string = string> {\n pluginType: \"hook\";\n name: TName;\n namespace?: string;\n id: string;\n imports: readonly AnyPlugin[];\n importBindings: readonly ImportBinding[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup?: (bag: { imports: any }) => unknown;\n /** `setup`'s dual: releases what setup acquired. Run by `disposeSdk` in\n * reverse dependency order. */\n dispose?: DisposeFn;\n /** Contract-preserving wraps around imported methods (the middleware onion,\n * folded dependents-outermost in topological order). Keyed by the target's\n * binding among this hook's `imports`. */\n wrap?: Record<string, MiddlewareFn>;\n observe?: {\n onMethodStart?: (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n input: OnMethodStartContext;\n state: unknown;\n }) => void;\n onMethodEnd?: (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n input: OnMethodEndContext;\n state: unknown;\n }) => void;\n };\n /** Composable pre-run annotator: returns `Annotations` merged into the call's\n * bag before `onMethodStart`. Coexists with other hooks' annotators. */\n annotator?: HookAnnotator;\n}\n\nexport type AnyPlugin =\n | AnyLeafPlugin\n | AnyAggregatePlugin\n | AnyLegacyPlugin\n | HookPlugin\n | MethodOverridePlugin;\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 hook\n * (whose `imports` the wrap receives, built live at call time). */\nexport interface MiddlewareWrap {\n run: MiddlewareFn;\n owner: HookPlugin;\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 /** The import-facing twin of `value`: the same boundary, called with the\n * internal-call sentinel so surface-only concerns (the deprecation signal)\n * don't fire when a sibling plugin delegates. `buildImports` and\n * `resolvePlugin` bind this; the surface and registry bind `value`. Absent\n * on legacy graph entries (they bind `value`). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n internalValue?: (input: any) => any;\n /** Produce the import-facing twin for a given call context: with a context,\n * the twin mints a fresh child per invocation (callee inherits `callId`, its\n * origin, and sits one level deeper); without one it is parent-less — the\n * surface-origin `internalValue` by default, or a framework-internal root when\n * `frameworkOrigin` is set (kitcore's own build-time passes request it, so\n * their delegated calls can be dropped from telemetry). `buildImports` binds\n * this. Absent on legacy graph entries. */\n bindInternal?: (opts: {\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) => (...args: any[]) => any;\n chain: MiddlewareWrap[];\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n inputSchema?: z.ZodType;\n /** When true, the method owns its input validation and the boundary passes it\n * through unparsed; carried so the controller skips its final `safeParse` too\n * (it still uses `inputSchema` to plan/prompt parameters). */\n skipInputValidation?: boolean;\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 /** Re-derives the value per read. Receives the live per-call `CallContext`\n * when installed on a method's `imports` bag with a threaded context, and\n * nothing on a surface / build-time read. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getValue?: (callContext?: CallContext) => any;\n /** Carried from the descriptor for the registry / CLI / MCP / docs. */\n meta?: LeafMeta;\n /** Carried from the descriptor: templated registry members for this\n * property's dynamic sub-surface (folded into the registry by getRegistry). */\n dynamicMembers?: readonly NormalizedDynamicMember[];\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 /** Teardown callbacks recorded at materialization, in build order\n * (dependencies first); `disposeSdk` walks them in reverse. */\n disposers?: SdkDisposer[];\n /** The first `disposeSdk` call's settled result; later calls return it\n * (idempotent, first input wins). */\n disposed?: Promise<void>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\n/** One leaf's recorded teardown: built at materialization (closing over the\n * leaf's imports + setup state), run by `disposeSdk`. */\nexport interface SdkDisposer {\n id: string;\n dispose: (input?: unknown) => void | Promise<void>;\n}\n\n/** The teardown callback a leaf declares beside `setup`, releasing what setup\n * acquired. `input` is whatever the caller passed to `disposeSdk` (untyped:\n * the framework does not bless a shape; each dispose narrows what it reads). */\nexport type DisposeFn = (bag: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n imports: any;\n state: unknown;\n input?: unknown;\n}) => void | Promise<void>;\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 SDK surface a plugin contributes, derived from its descriptor: a\n * method's callable or a property's value under its name, or an aggregate's\n * export bindings. No `SdkInternals` — this is the plugin's own slice, not a\n * whole SDK. The inference replacement for a hand-written\n * `<Name>PluginProvides` interface:\n *\n * export type ListAppsPluginProvides = PluginSurface<typeof listAppsPlugin>;\n *\n * \"Surface\", not \"Provides\": `PluginProvides` is the legacy function-plugin\n * bag and `ProvidesOf` is the completeness ledger's phantom ids — both\n * different concepts.\n */\nexport type PluginSurface<P extends AnyPlugin> =\n P extends MethodPlugin<\n infer TName,\n infer TInput,\n infer TOutput,\n infer TPositional\n >\n ? P extends { optional: true }\n ? { [K in TName]: SurfaceCall<TInput, TOutput, TPositional> | undefined }\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 : never;\n\n/**\n * The framework-owned access an SDK carries beyond its string surface.\n *\n * Both keys, because the value has both. `[CONTEXT]` is what materialization\n * writes and what `getContext` reads, so declaring it is the type telling the\n * truth. `context` is the legacy string key, kept for back-compat and narrowing\n * away later.\n *\n * The symbol used to be omitted so it would not reach a consumer's emitted\n * declarations. It is exported from the package root, so it is nameable there,\n * and hiding it cost more than it saved: `ControllerSdk` had to check the\n * legacy string key as a stand-in for the real one.\n */\nexport interface SdkContextCarrier {\n readonly [CONTEXT]: SdkContext;\n}\n\nexport type SdkInternals = {\n context: SdkContext;\n} & SdkContextCarrier;\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> = [P] extends [AnyPlugin]\n ? // A model plugin adds its PluginSurface; a kind with no typed surface\n // (hook, method-override, legacy descriptor) resolves to never there and\n // adds nothing. The tuple wrappers keep never from distributing.\n [PluginSurface<P>] extends [never]\n ? Record<never, never>\n : PluginSurface<P>\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/**\n * The id a stand-in declares, carried separately from the requires ledger.\n *\n * `declareProperty` requires its own id, so the ledger alone would do. A\n * `declareOptionalProperty` requires NOTHING, which is the point of it, so its\n * ledger is empty and the id has nowhere else to live. Reading the id off the\n * ledger meant an optional stand-in handed a by-reference provider `never`,\n * and a `never` in that position stopped `CompletenessOf` reporting anything\n * for the whole graph.\n *\n * A carrier of its own keeps the two facts apart: what a stand-in NEEDS, and\n * what it NAMES.\n */\nexport interface StandInId<TId extends string = never> {\n /** @internal */\n readonly [DECLARES]?: TId;\n}\n\n/** Phantom-only key (see `StandInId`); never set at runtime. */\ndeclare const DECLARES: unique symbol;\n\n/** The id a stand-in names (reads the phantom carrier). */\nexport type DeclaredIdOf<P> = P extends { readonly [DECLARES]?: infer R }\n ? Extract<R, string>\n : never;\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/**\n * The runtime-input channel for `createSdk`. `configuration` maps plugin ids to\n * immutable values; each entry materializes as a static value property under\n * that id, satisfying a `declareProperty` / `declareOptionalProperty` stand-in exactly\n * as a registered provider would (DI value injection). Strict at build time:\n * an id must resolve to a property stand-in reachable from the root, so\n * unknown ids, non-property targets, and collisions with a registered real\n * provider all throw. kitcore keeps the map untyped; a head's factory is the\n * typed wrapper (`createMySdk(options)` passes\n * `{ configuration: { \"my/config\": options } }`).\n */\nexport interface CreateSdkOptions {\n configuration?: Record<string, unknown>;\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 {\n OnMethodStartContext,\n OnMethodEndContext,\n} from \"../utils/build-hooks\";\nimport type { CallContext } from \"../utils/call-context\";\nimport type { PaginatedSdkResult, SdkPage } from \"../types/pagination\";\nimport type { ResponseMeta } from \"../types/output-validation\";\nimport type {\n FormattedItem,\n PromptConfig,\n ResolverPromptConfig,\n} from \"../utils/schema-utils\";\nimport { logDeprecation } from \"../utils/logging\";\nimport { makeId, parseId } from \"./shared\";\nimport { LEAF_META_KEYS } from \"./types\";\nimport type {\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyMethodPlugin,\n AnyPlugin,\n AggregatePlugin,\n ArrayExports,\n DefineMethodConfig,\n Formatter,\n ImportsInput,\n ExportsInput,\n ImportBinding,\n ImportsOf,\n ItemOf,\n DynamicMember,\n LeafMeta,\n LeafMetaFields,\n OverridableMetaFields,\n MethodOverridePlugin,\n NormalizedDynamicMember,\n HookPlugin,\n HookAnnotator,\n MethodPlugin,\n MethodAnnotator,\n MethodRunBag,\n MiddlewareMap,\n PageFetchInput,\n PaginatedCallInput,\n ItemRunInput,\n ListRunInput,\n CallOutputOptions,\n PropertyPlugin,\n Resolver,\n ResolverRef,\n ResolverRequirement,\n ListItemsResult,\n ResolverType,\n Field,\n DisposeFn,\n DynamicResolver,\n StaticResolver,\n ConstantResolver,\n InfoResolver,\n ObjectResolver,\n AdditionalKeys,\n ArrayResolver,\n StrictItem,\n DataOf,\n StrictPage,\n PluginSummary,\n StandInId,\n StaticList,\n LiteralString,\n IdOf,\n LastSegment,\n LeafSummary,\n LeafRequires,\n LeafProvides,\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, optional?: boolean): 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(optional ? { binding, id, optional } : { 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 if (plugin.pluginType === \"hook\") {\n // A hook contributes behavior, not an importable value: it materializes\n // no `context.plugins` entry, so binding it would break `buildImports`.\n // Keep it in the plugin list only (reachability + topological ordering,\n // e.g. a hook importing another to wrap AROUND it).\n } else {\n // A `declareOptionalProperty` stand-in marks its binding optional so an\n // unsatisfied dependency resolves to `undefined` instead of throwing.\n add(plugin.name, plugin.id, (plugin as { optional?: boolean }).optional);\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/** Render a dynamic-member path to its registry name: literals as-is, params as\n * `{param}`, joined with `.` (e.g. `apps.{appKey}.{actionType}.{actionKey}`). */\nfunction formatDynamicMemberName(\n path: readonly (string | { param: string })[],\n): string {\n return path\n .map((seg) => (typeof seg === \"string\" ? seg : `{${seg.param}}`))\n .join(\".\");\n}\n\n/** Normalize authored dynamic members: derive each registry name, capture the\n * literal root segment (validated against the surface later), and fold the\n * hoisted fields into a `PluginMeta` (with the projection-only `inputSchema`). */\nfunction collectDynamicMembers(\n members: readonly DynamicMember[] | undefined,\n): readonly NormalizedDynamicMember[] | undefined {\n if (!members?.length) return undefined;\n return members.map((member) => {\n const root = member.path[0];\n if (typeof root !== \"string\") {\n throw new Error(\n \"defineProperty: a dynamicMember path must start with a literal \" +\n \"segment (the owning binding), not a { param }.\",\n );\n }\n const leaf = collectLeafMeta(member) ?? {};\n return {\n name: formatDynamicMemberName(member.path),\n rootBinding: root,\n meta: member.inputSchema\n ? { ...leaf, inputSchema: member.inputSchema }\n : leaf,\n };\n });\n}\n\n/**\n * Reject a LIST stand-in from the ref form, at the REF rather than at `run`.\n * Without this the mismatch surfaces as a run-return type error, which sends\n * the reader to the wrong file. The key is the message: a missing required\n * property names itself in the error.\n *\n * A `PaginatedSdkResult` is a decorated thenable the framework builds, so no\n * hand-written `run` returns one. That makes it a fact about the ref, not a\n * guess.\n *\n * ITEM is deliberately absent. An item surface is `Promise<{ data }>`, which is\n * also just an ordinary async method returning an object with a `data` field,\n * and rejecting the second to catch the first turned a valid raw provider into\n * a compile error with advice that did not apply. An item stand-in implemented\n * by reference now fails on the run return instead, which is a worse message\n * for a real mistake but does not refuse correct code.\n */\ntype RefFormRawOnly<TOutput> =\n TOutput extends PaginatedSdkResult<unknown>\n ? {\n \"defineMethod(ref, config) provides raw output only; define a list provider from scratch\": never;\n }\n : unknown;\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 `{ data: T }`, surfaced as `Promise<{ data: T }>`), or `list`\n * (`run` 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 /** Skip the runtime parse of `input`; `run` gets it untouched (the schema\n * stays for projection). For raw methods that validate their own input, like\n * `fetch`. See {@link MethodPlugin.skipInputValidation}. */\n skipInputValidation?: boolean;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n annotator?: MethodAnnotator;\n output?: \"raw\" | { type: \"raw\" };\n positional?: TPositional;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\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 a strict `{ data }` envelope, symmetric with list's\n// strict `SdkPage`; the framework passes it through.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TResponse extends StrictItem<TResponse>,\n TData = DataOf<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 annotator?: MethodAnnotator;\n output: \"item\" | { type: \"item\" };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & CallOutputOptions,\n Promise<{ data: TData; meta?: ResponseMeta }>,\n readonly [],\n ItemRunInput<TInput>\n> &\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 annotator?: MethodAnnotator;\n output:\n | \"list\"\n | { type: \"list\"; adaptPage?: undefined; defaultPageSize?: number };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & PaginatedCallInput & CallOutputOptions,\n PaginatedSdkResult<TItem>,\n readonly [],\n ListRunInput<TInput>\n> &\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 annotator?: MethodAnnotator;\n output: {\n type: \"list\";\n adaptPage: (response: TResponse) => SdkPage<TItem>;\n defaultPageSize?: number;\n };\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, TInput & PageFetchInput, TState>,\n ) => TResponse | Promise<TResponse>;\n } & LeafMetaFields,\n): MethodPlugin<\n TName,\n TInput & PaginatedCallInput & CallOutputOptions,\n PaginatedSdkResult<TItem>,\n readonly [],\n ListRunInput<TInput>\n> &\n LeafSummary<TNamespace, TName, TImports>;\n// ref form (raw output): provide a `declareMethod` stand-in BY REFERENCE. `run`\n// is typed against the declared `TInput` / `TOutput`, and id / name / namespace\n// come from the ref (no string respelled). Raw only, because an item or list\n// stand-in is\n// defined from scratch via the output-moded overloads above, since its `run`\n// return differs from the surfaced output. Mirrors `defineProperty(ref, { value })`.\nexport function defineMethod<\n const TName extends string,\n TInput,\n TOutput,\n const TId extends string,\n const TImports extends ImportsInput = readonly [],\n TState = undefined,\n>(\n ref: MethodPlugin<TName, TInput, TOutput> &\n StandInId<TId> &\n RefFormRawOnly<TOutput>,\n config: {\n imports?: TImports & StaticList<TImports>;\n inputSchema?: z.ZodType<TInput>;\n skipInputValidation?: boolean;\n resolvers?: Record<string, Resolver>;\n formatter?: Formatter;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n // NoInfer on both, so the REF states the input and output. Inferred from\n // here too, a provider's own `run` widened them, which let the raw-only\n // guard read a shape the ref never declared.\n run: (\n bag: MethodRunBag<ImportsOf<TImports>, NoInfer<TInput>, TState>,\n ) => NoInfer<TOutput>;\n } & LeafMetaFields,\n): MethodPlugin<TName, TInput, TOutput> &\n PluginSummary<LeafRequires<TId, TImports>, LeafProvides<TId, TImports>>;\nexport function defineMethod(\n configOrRef: DefineMethodConfig | MethodPlugin,\n refConfig?: Omit<DefineMethodConfig, \"name\" | \"namespace\">,\n // Only the run slot moves off its default. The item and list overloads narrow\n // `run`'s input away from the call input, and a parameter position is\n // contravariant, so `never` is the one input every overload's `run` accepts.\n): MethodPlugin<string, unknown, unknown, readonly [], never> {\n // Ref form, `defineMethod(ref, { run, … })`: the ONLY difference is where\n // the identity comes from, so borrow it off the stand-in and fall through to\n // the one build below. A second literal here would be a copy to keep in step,\n // and the copy is what silently drops a field the next time one is added.\n const config: DefineMethodConfig =\n refConfig === undefined\n ? (configOrRef as DefineMethodConfig)\n : {\n ...refConfig,\n name: (configOrRef as MethodPlugin).name,\n namespace: (configOrRef as MethodPlugin).namespace,\n };\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 skipInputValidation: config.skipInputValidation,\n skipOutputValidation: config.skipOutputValidation,\n meta: collectLeafMeta(config),\n resolvers: config.resolvers,\n formatter: config.formatter,\n annotator: config.annotator,\n output: config.output,\n positional: config.positional,\n setup: config.setup as MethodPlugin[\"setup\"],\n dispose: config.dispose,\n run: config.run as MethodPlugin[\"run\"],\n };\n}\n\n/** The runtime half of {@link OverridableMetaFields}, since a JavaScript caller\n * never sees the type.\n *\n * An allow-list for the same reason the type is one: a field added to\n * `LeafMetaFields` later must not become patchable because nobody remembered to\n * deny it. Anything off this list changes what runs, what input is accepted, or\n * what safety gate fires, so refusing the call beats dropping the field\n * silently. */\nconst OVERRIDABLE = [\n \"description\",\n \"categories\",\n \"itemType\",\n \"returnType\",\n \"packages\",\n \"experimental\",\n \"deprecation\",\n \"supportsJsonOutput\",\n] as const;\n\nfunction assertOverridable(target: string, fields: object): void {\n const offered = Object.keys(fields).filter(\n (key) => !(OVERRIDABLE as readonly string[]).includes(key),\n );\n if (offered.length === 0) return;\n throw new Error(\n `defineOverride(\"${target}\"): cannot override ${offered.join(\", \")}. ` +\n `An override changes how a surface presents a method, never what it does. ` +\n `The method's declared type is fixed at \\`defineMethod\\` and nothing ` +\n `re-checks it afterwards, so patching behavior here would let a call fail ` +\n `against a contract its own return type says it satisfies. ` +\n `Overridable: ${OVERRIDABLE.join(\", \")}.`,\n );\n}\n\n/** Build the override plugin. Shared by the ref form and the deprecated\n * string-target form, so the two cannot drift on shape or on the guard. */\nfunction buildOverride(\n target: string,\n namespace: string | undefined,\n fields: OverridableMetaFields,\n): MethodOverridePlugin {\n assertOverridable(target, fields);\n return {\n pluginType: \"method-override\",\n name: `override:${target}`,\n id: namespace ? `${namespace}/override:${target}` : `override:${target}`,\n target,\n imports: [],\n importBindings: [],\n meta: collectLeafMeta(fields),\n };\n}\n\n/**\n * Patch how a surface PRESENTS an already-defined method, by reference. Pass\n * the method (or its `declareMethod` stand-in) and any of\n * {@link OverridableMetaFields}. After the SDK materializes, those fields merge\n * onto the target's entry, so the registry / CLI / MCP / docs project the\n * patched values. The target's `run`, resolvers, and declared type are\n * untouched, which is the whole point: see {@link OverridableMetaFields} for\n * the fields that are refused and why.\n *\n * Use it for a tweak one surface wants and the base method should not carry, a\n * CLI deprecating `fetch` while the SDK does not. Include it in an aggregate's\n * `imports` to apply it during `createSdk`, or `addPlugin(sdk, override)` to\n * apply it to a built SDK.\n *\n * Taking the reference rather than an id string is the same choice\n * `defineMethod(ref, ...)` and `defineProperty(ref, ...)` make. No id is\n * respelled, so a rename cannot leave a silent no-op behind, and the name does\n * not restate what the reference already says. `declareMethod` gives you a\n * stand-in when you want to patch a method without importing it.\n *\n * `namespace` names the OVERRIDE, not the target, so two surfaces can each\n * patch the same method in one graph without colliding.\n */\nexport function defineOverride(\n ref: AnyMethodPlugin,\n config: { namespace?: string } & OverridableMetaFields = {},\n): MethodOverridePlugin {\n const { namespace, ...fields } = config;\n return buildOverride(ref.id, namespace, fields);\n}\n\n/**\n * @deprecated Use {@link defineOverride}, which takes the method itself instead\n * of its id spelled out again.\n */\nexport function defineMethodOverride<const TTarget extends string>(\n config: { target: TTarget; namespace?: string } & OverridableMetaFields,\n): MethodOverridePlugin {\n logDeprecation(\n \"defineMethodOverride({ target }) is deprecated. Use defineOverride(method, { ... }), which takes the method or its declareMethod stand-in.\",\n );\n const { target, namespace, ...fields } = config;\n return buildOverride(target, namespace, fields);\n}\n\n/**\n * Refuse an empty absolute path, which the type also rejects.\n *\n * The walk resolves a path with `getAtPath`, which traverses zero segments and\n * hands back the resolved root. That object is not `undefined`, so an empty\n * path reads as already satisfied and the resolver runs before the prerequisite\n * its author meant to declare. Failing open on a gate is worse than not having\n * one, so this refuses rather than ignores.\n *\n * Here as well as in the type, because a JavaScript caller never sees the type.\n */\nfunction assertRequirementPaths(\n requirements: readonly ResolverRequirement[] | undefined,\n): void {\n if (!requirements) return;\n for (const requirement of requirements) {\n if (typeof requirement !== \"string\" && requirement.length === 0) {\n throw new Error(\n \"defineResolver: a requireParameters path must name at least one \" +\n \"segment. An empty path names no parameter, and the engine would \" +\n \"read it as already satisfied.\",\n );\n }\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 ResolverRequirement[];\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. Required: a dynamic resolver IS a candidate-lister;\n * use `type: \"static\"` for a free-text field. */\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 /** Check a chosen/typed value before the engine accepts it. Async with\n * `imports` so it can verify against the source — never against a loaded\n * page (the pick can come from a page the engine no longer holds). Return\n * true to accept or a message to re-ask with; a throw is a lookup failure\n * (retry/cancel), not a rejection. */\n validate?: (bag: {\n imports: ImportsOf<TImports>;\n value: unknown;\n input: TInput;\n /** The value `getContext` returned, if any. */\n context?: TContext;\n }) => Promise<true | string> | true | string;\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 ResolverRequirement[];\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 ResolverRequirement[];\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 ResolverRequirement[];\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 /** Open-ended entries whose keys aren't known up front (a `z.record`). */\n additionalKeys?: AdditionalKeys;\n}): ObjectResolver;\n// array: a homogeneous list resolved through `items`.\nexport function defineResolver(config: {\n type: \"array\";\n requireParameters?: readonly ResolverRequirement[];\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 ResolverRequirement[];\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 additionalKeys?: AdditionalKeys;\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n validate?: (bag: any) => Promise<true | string> | true | string;\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 assertRequirementPaths(config.requireParameters);\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 additionalKeys: config.additionalKeys,\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 validate: config.validate as DynamicResolver[\"validate\"],\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 StandInId<TId> {\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 StandInId<TId>;\n}\n\n/**\n * Declare an OPTIONAL stand-in for a method registered elsewhere: the method twin\n * of `declareOptionalProperty`. Unlike `declareMethod`, an unsatisfied optional\n * reference is NOT a missing dependency; the binding is typed\n * `((input) => output) | undefined`, so the consumer must handle the absent case\n * (`imports.track?.(...)`). Use it to reference a foreign method userland may or\n * may not import, without claiming its slot.\n */\nexport function declareOptionalMethod<\n const TId extends string,\n TInput = unknown,\n TOutput = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): MethodPlugin<LastSegment<TId>, TInput, TOutput> & {\n optional: true;\n} & PluginSummary<never, never> &\n StandInId<TId> {\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 optional: true,\n imports: [],\n importBindings: [],\n run: () => {\n throw new Error(\n `Plugin \"${id}\" is an optional stand-in (declareOptionalMethod) with no ` +\n `implementation. Its binding is \\`undefined\\` unless a real plugin is ` +\n `registered under this id.`,\n );\n },\n // Requires nothing (phantom carrier `<never, never>`): a consumer that\n // imports it still passes `createSdk`'s completeness check unprovided. The\n // `optional: true` literal drives `PluginSurface` to type the binding\n // `| undefined`.\n } as unknown as MethodPlugin<LastSegment<TId>, TInput, TOutput> & {\n optional: true;\n } & PluginSummary<never, never> &\n StandInId<TId>;\n}\n\ntype DefinePropertyConfig = {\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 dispose?: DisposeFn;\n value?: unknown;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get?: (bag: any) => unknown;\n dynamicMembers?: readonly DynamicMember[];\n} & LeafMetaFields;\n\n/**\n * Define a property leaf. Either a static `value` or a computed `get`, which\n * re-runs live on each read; an optional `setup` runs once at `createSdk`\n * (dependencies first, like a method's `setup`) to build the state `get` reads.\n * `createSdk`, a dependent's `imports`, or an aggregate's re-export binds it\n * 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 dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n get: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n /** The live per-call context when the property is read from a method's\n * `imports` bag — every method call has one, at any depth. Undefined only\n * where no call is in flight: the property bound onto the SDK object\n * itself, and reads from a `setup`-time imports bag. A context-aware\n * property reads its `callId` off this; because its value is then specific\n * to the reading call, callers must not cache it across calls. */\n callContext?: CallContext;\n }) => TValue;\n /** Templated registry members for this property's dynamic sub-surface (e.g.\n * a proxy): each a bodyless declaration keyed by `path` instead of `name`. */\n dynamicMembers?: readonly DynamicMember[];\n } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> & LeafSummary<TNamespace, TName, TImports>;\n/**\n * Provide a value for a declared property BY REFERENCE: pass the\n * `declareProperty` / `declareOptionalProperty` stand-in instead of respelling\n * its `name` / `namespace`, and `value` is typed against the declaration. The\n * result is a real property that satisfies the stand-in (or overrides its\n * default) by id. The refactor-safe, no-string alternative to matching ids by\n * hand (and the in-graph replacement for `createSdk`'s `configuration` channel).\n */\nexport function defineProperty<\n const TName extends string,\n TValue,\n const TId extends string,\n>(\n ref: PropertyPlugin<TName, TValue> & StandInId<TId>,\n // NoInfer so the REF states the value type. Inferring from both sites let\n // `value: undefined` widen `TValue` until the two agreed, and a consumer\n // reading the declared shape then compiled and crashed.\n config: { value: NoInfer<TValue> } & LeafMetaFields,\n): PropertyPlugin<TName, TValue> & PluginSummary<never, TId>;\nexport function defineProperty(\n config: DefinePropertyConfig | PropertyPlugin,\n refConfig?: { value: unknown } & LeafMetaFields,\n): PropertyPlugin {\n // Ref form, `defineProperty(ref, { value })`: as in `defineMethod`, the only\n // difference is that the identity comes off the stand-in, so borrow it and\n // fall through to the one build below rather than keeping a second literal in\n // step. A value-only config leaves the rest absent, which is what it means.\n const cfg: DefinePropertyConfig =\n refConfig === undefined\n ? (config as DefinePropertyConfig)\n : {\n ...refConfig,\n name: (config as PropertyPlugin).name,\n namespace: (config as PropertyPlugin).namespace,\n };\n const deps = normalizeImports(cfg.imports);\n return {\n pluginType: \"property\",\n name: cfg.name,\n namespace: cfg.namespace,\n id: makeId(cfg.name, cfg.namespace),\n imports: deps.plugins,\n importBindings: deps.bindings,\n setup: cfg.setup as PropertyPlugin[\"setup\"],\n dispose: cfg.dispose,\n value: cfg.value,\n get: cfg.get as PropertyPlugin[\"get\"],\n meta: collectLeafMeta(cfg),\n dynamicMembers: collectDynamicMembers(cfg.dynamicMembers),\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> &\n PluginSummary<TId, never> &\n StandInId<TId> {\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 StandInId<TId>;\n}\n\n/**\n * Declare an OPTIONAL stand-in for a property registered elsewhere. Unlike\n * `declareProperty`, a `declareOptionalProperty` left unsatisfied is NOT a missing\n * dependency: dependents bind `undefined` instead of the build failing. The\n * binding type is therefore `TValue | undefined`, so a consumer must handle the\n * absent case (typically `{ ...DEFAULTS, ...imports.config }`).\n *\n * This lets a plugin own its own defaults and treat a provider as override-only:\n * it builds standalone (no provider registered -> `undefined` -> defaults), and\n * a registered provider layers on top. Used for the SDK's static config\n * (defaults live with each consumer; `createZapierSdk` registers an override)\n * and for framework capabilities a method can run without (e.g. hooks).\n */\nexport function declareOptionalProperty<\n const TId extends string,\n TValue = unknown,\n>(config: {\n id: LiteralString<TId>;\n}): PropertyPlugin<LastSegment<TId>, TValue | undefined> &\n PluginSummary<never, never> &\n StandInId<TId> {\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 optional: true,\n imports: [],\n importBindings: [],\n // Requires nothing (phantom carrier `<never, never>`): a consumer that\n // imports it still passes `createSdk`'s completeness check unprovided. The\n // import binding is still typed `TValue | undefined` from the descriptor.\n } as unknown as PropertyPlugin<LastSegment<TId>, TValue | undefined> &\n PluginSummary<never, never> &\n StandInId<TId>;\n}\n\n/**\n * Declare a DEFAULT provider for a dependency you own: import the capability the\n * given plugin provides, and fall back to that plugin when nothing else provides\n * its id. Kind-agnostic (the plugin supplies id, type, and kind), so no\n * method/property split.\n *\n * A default materializes a real, single node, so it works out of the box and can\n * be wrapped or replaced: an explicit provider of the same id silently preempts\n * it, and two different defaults for one id error only when nothing else provides\n * it. See the Defaults section in the kitcore README for default vs optional\n * reference.\n */\nexport function declareDefault<P extends AnyLeafPlugin>({\n plugin,\n}: {\n plugin: P;\n}): P {\n // `defaultSource` marks this as a default and points at the wrapped plugin, so\n // the materializer can dedup two defaults with the same source and flag two\n // with different sources.\n return { ...plugin, defaultSource: plugin } as P;\n}\n\n/**\n * Define a method-lifecycle hook: a leaf whose `observe` contributes\n * fire-and-forget observers (`onMethodStart` / `onMethodEnd`) the method\n * boundary fires around every method, and whose `wrap` contributes\n * contract-preserving middleware around imported methods. This is how a\n * MODULE plugin provides cross-cutting behavior (the module-model successor\n * to a legacy plugin writing `context.hooks` and to `definePlugin`'s\n * deleted `middleware` map).\n *\n * `setup` runs once and owns the hook's state (e.g. a telemetry queue),\n * delivered to the observers. Each observer's bag\n * mirrors a method's `run` bag minus `next`: `{ imports, input, state }`, where\n * `input` is the lifecycle context (`{ methodName, args, depth, ... }`). The\n * boundary runs observers defensively, so an observer error never breaks the\n * observed call.\n */\nexport function defineHook<\n const TImports extends ImportsInput = readonly [],\n TState = undefined,\n>(config: {\n name: string;\n namespace?: string;\n imports?: TImports & StaticList<TImports>;\n setup?: (bag: { imports: ImportsOf<TImports> }) => TState;\n dispose?: (bag: {\n imports: ImportsOf<TImports>;\n state: TState;\n input?: unknown;\n }) => void | Promise<void>;\n /** Contract-preserving wraps around imported methods, keyed by the target's\n * binding among `imports` (the middleware onion: dependents-outermost in\n * topological order). One bag shape with `run`/`observe`; `next` is the\n * only variant. */\n wrap?: MiddlewareMap<ImportsOf<TImports>, TState>;\n observe?: {\n onMethodStart?: (bag: {\n imports: ImportsOf<TImports>;\n input: OnMethodStartContext;\n state: TState;\n }) => void;\n onMethodEnd?: (bag: {\n imports: ImportsOf<TImports>;\n input: OnMethodEndContext;\n state: TState;\n }) => void;\n };\n /** Cross-cutting pre-run annotation. The boundary composes hook annotators\n * right-additively (a later hook's fields win on collision) ahead of the\n * method's own `annotator`, invokes them best-effort for the outermost\n * surface-origin call only, and merges their returned `Annotations` into the\n * call's bag. Synchronous and import-less; fields needing imports or async\n * work are written mid-`run` via the run bag's `annotate`. Returns a value\n * (unlike `observe`) and never reaches `run`. */\n annotator?: HookAnnotator<TState>;\n}): HookPlugin {\n const deps = normalizeImports(config.imports);\n return {\n pluginType: \"hook\",\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 HookPlugin[\"setup\"],\n dispose: config.dispose as HookPlugin[\"dispose\"],\n wrap: config.wrap as HookPlugin[\"wrap\"],\n observe: config.observe as HookPlugin[\"observe\"],\n annotator: config.annotator as HookPlugin[\"annotator\"],\n };\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 * Function form — the legacy function-plugin identity wrapper: it returns the\n * function unchanged but constrains its return to `PluginProvides` and\n * preserves the narrow inferred shape, so callers derive `*PluginProvides` via\n * `ReturnType<typeof plugin>`. Such a plugin runs through the legacy bridge\n * (`fromFunctionPlugin` / `createPluginStack`), deprecated with it.\n *\n * @deprecated Author plugins with `defineMethod` / `defineProperty` /\n * object-form `definePlugin` instead. This form logs a runtime deprecation and\n * will be removed in a release after the warning ships.\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/**\n * Define a plugin module: an aggregate that re-exports child plugins.\n * `exports` mirrors `imports`: an array where a leaf binds under its own name\n * (`[greet]` binds \"greet\"), a module spreads its bindings, and\n * `selectExports(dep, { hi: \"greet\" })` subsets/renames. It is optional, so an\n * imports-only module can omit it. Re-exporting implies a dependency on the\n * child. To wrap imported methods, export a `defineHook` with `wrap`.\n */\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}): 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 },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): ((sdk: any) => PluginProvides) | AggregatePlugin {\n if (typeof fnOrConfig === \"function\") {\n logDeprecation(\n \"definePlugin(fn) (the function form) is deprecated. Author plugins with defineMethod/defineProperty/definePlugin({ ... }) instead.\",\n );\n return fnOrConfig;\n }\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 // A re-export synthetic (`selectExports` / `omitExports`) is flattened by\n // `normalizeExports` into bare bindings, which drops its own `imports:\n // [source]`. That edge is how `omitExports` keeps an omitted (unbound) leaf\n // materialized + addressable by id, so preserve every exported aggregate's\n // imports as extra reachability edges here (bindings unaffected).\n imports: [...deps.plugins, ...exportedAggregateImports(config.exports)],\n importBindings: deps.bindings,\n exports: normalizeExports(config.exports),\n };\n}\n\n/** The extra graph edges an `exports` array contributes beyond its bare\n * bindings: each exported aggregate's own `imports` (e.g. a `selectExports` /\n * `omitExports` synthetic's `imports: [source]`), so a re-export whose source\n * carries unbound-but-materialized leaves keeps them reachable. */\nfunction exportedAggregateImports(\n exports: ExportsInput | undefined,\n): readonly AnyPlugin[] {\n if (!exports) return [];\n const out: AnyPlugin[] = [];\n for (const element of exports) {\n if (element.pluginType === \"aggregate\") out.push(...element.imports);\n }\n return out;\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\n/**\n * Re-export all of a module's exports EXCEPT the named ones, the denylist\n * complement to {@link selectExports}'s allowlist (think TS `Omit` vs `Pick`).\n * The argument is a list of SOURCE export names to drop (not resulting\n * bindings), so there is no key-semantics ambiguity. An unknown name throws.\n *\n * The omitted leaves stay in the graph (the synthetic aggregate still `imports`\n * the source, so it materializes) and remain addressable by id — they are just\n * not surfaced under a binding. That lets a head replace an export's binding\n * with its own plugin while still depending on the original by id.\n */\nexport function omitExports<\n TExports extends Record<string, AnyLeafPlugin>,\n const TOmit extends readonly (keyof TExports & string)[],\n>(\n source: AggregatePlugin<string, TExports>,\n omit: TOmit,\n): AggregatePlugin<string, Omit<TExports, TOmit[number]>> {\n const omitSet = new Set<string>(omit);\n for (const name of omit) {\n if (!(name in source.exports)) {\n throw new Error(`omitExports: \"${source.id}\" has no export \"${name}\".`);\n }\n }\n const kept: Record<string, AnyLeafPlugin> = {};\n for (const [binding, child] of Object.entries(source.exports)) {\n if (!omitSet.has(binding)) kept[binding] = child;\n }\n return {\n pluginType: \"aggregate\",\n name: makeId(`omit`, source.name, \"aggregate\"),\n id: `${source.id}#omit:${selectSeq++}`,\n imports: [source],\n importBindings: [],\n exports: kept,\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 { logDeprecation } from \"../utils/logging\";\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 *\n * @deprecated The module model replaces this exit; it logs a runtime\n * deprecation and will be removed in a release after this warning ships.\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 logDeprecation(\n \"fromFunctionPlugin() is deprecated. Author plugins with defineMethod/definePlugin instead.\",\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 *\n * @deprecated Build directly with `createSdk(root, { configuration })`\n * instead; it logs a runtime deprecation and will be removed in a release\n * after this warning ships.\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 logDeprecation(\n \"defineLegacyMerge() is deprecated. Build directly with createSdk(root, { configuration }) instead.\",\n );\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 { declareOptionalProperty, defineMethod } from \"./define\";\nimport { getCachedRegistry } from \"./registry-support\";\nimport type { PropertyPlugin, SdkContext } from \"./types\";\nimport { CORE_OPTIONS_ID, type CoreOptions } from \"../utils/core-options\";\n\n/**\n * The optional stand-in for the framework-options bag (`kitcore/coreOptions`).\n * The method boundary resolves the same id internally (for `adaptError`); a\n * plugin that needs the options imports this ref, binding\n * `CoreOptions | undefined` (absent means kitcore's built-in behavior). Heads\n * supply the value via `createSdk`'s `configuration` or a registered property.\n */\nexport const coreOptionsPluginRef = declareOptionalProperty<\n typeof CORE_OPTIONS_ID,\n CoreOptions\n>({ id: CORE_OPTIONS_ID });\n\n/**\n * Escape hatch. A built-in privileged plugin whose value is the live\n * `SdkContext` (the raw plugin graph). Importing it (`imports.context`) lets a\n * body reach internals the model otherwise keeps 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 * use `getRegistryPlugin` for surface introspection, and `resolvePlugin` for\n * out-of-graph access to a binding. Its value is injected at materialization,\n * 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 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. A thin\n * shim over the shared `getCachedRegistry`, the same path the free\n * `getRegistry(sdk)` takes, so a surfaced call and an off-surface call return\n * the identical memoized object. Surfacing is optional, since controllers reach\n * the registry through `getRegistry(sdk)` whether or not a head re-exports this.\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 getCachedRegistry(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, so\n * no adaptation is needed. Non-methods / no resolvers → undefined.\n */\nexport function normalizeResolvers(\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 normalizeResolvers}. 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 * Fold a property entry's templated dynamic members into the registry `meta`\n * map, keyed by each member's derived name (`apps.{appKey}`). These have no\n * static binding; `buildRegistry` still projects them because their root segment\n * resolves to a real member on the surface. Fails loud if that root is not a\n * surfaced binding (a typo'd or dangling path).\n */\nexport function foldDynamicMembers(\n entry: PluginEntry,\n surfaceBindings: ReadonlySet<string>,\n meta: Record<string, PluginMeta>,\n): void {\n if (entry.pluginType !== \"property\" || !entry.dynamicMembers) return;\n for (const member of entry.dynamicMembers) {\n if (!surfaceBindings.has(member.rootBinding)) {\n throw new Error(\n `dynamicMember \"${member.name}\": its root \"${member.rootBinding}\" is ` +\n `not a surfaced member. A dynamic member's path must start with a ` +\n `real binding.`,\n );\n }\n meta[member.name] = member.meta;\n }\n}\n\n/** The per-binding registry inputs projected off the live surface. */\nexport interface SurfaceProjection {\n meta: Record<string, PluginMeta>;\n formatters: Record<string, BoundFormatter>;\n resolvers: Record<string, Record<string, BoundResolver>>;\n positional: Record<string, readonly string[]>;\n skipInputValidation: Record<string, boolean>;\n}\n\n/**\n * Collect the registry projection off the live surface: one meta / formatter /\n * bound-resolver / positional entry per `context.surface` binding (aggregates\n * and non-surfaced internals excluded), plus dynamic-member folding. Shared by\n * the pure module-model `getRegistry` (`buildSurfaceRegistry`) and the legacy\n * bridge's synthesized `getRegistry` (which overlays `context.meta` after).\n * `formatterSdk` is what a legacy formatter adapter captures to call through\n * at render time, so pass it fully built.\n */\nexport function collectSurfaceProjection(\n context: SdkContext,\n formatterSdk: unknown,\n): SurfaceProjection {\n const meta: Record<string, PluginMeta> = {};\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 entries[binding] = entry;\n const m = pluginEntryMeta(entry);\n if (m) meta[binding] = m;\n }\n const surfaceBindings = new Set(Object.keys(context.surface));\n for (const entry of Object.values(entries)) {\n foldDynamicMembers(entry, surfaceBindings, meta);\n }\n const formatters: Record<string, BoundFormatter> = {};\n const resolvers: Record<string, Record<string, BoundResolver>> = {};\n const positional: Record<string, readonly string[]> = {};\n const skipInputValidation: Record<string, boolean> = {};\n for (const [binding, entry] of Object.entries(entries)) {\n const f = normalizeFormatter(entry, formatterSdk);\n if (f) formatters[binding] = f;\n const r = normalizeResolvers(entry);\n if (r) resolvers[binding] = r;\n const p = methodPositional(entry);\n if (p) positional[binding] = p;\n if (entry.pluginType === \"method\" && entry.skipInputValidation)\n skipInputValidation[binding] = true;\n }\n return { meta, formatters, resolvers, positional, skipInputValidation };\n}\n\n/**\n * Where a context keeps its memoized registries, one per package filter.\n *\n * ON THE CONTEXT, not in a module-level `WeakMap`, because a process can hold\n * two physical copies of kitcore. A head bundles one (tsup `noExternal`) while\n * a host can also load `@zapier/kitcore` directly. Both copies recover the same\n * `SdkContext` through `Symbol.for(\"kitcore.context\")`, but a module-level map\n * exists once per copy, so a mutation invalidated through one copy left the\n * other serving a stale registry. Warm both readers, `addPlugin` through one,\n * and the other keeps reporting a surface without the added method.\n *\n * `Symbol.for` for the same reason `CONTEXT` uses it: the two copies have to\n * name the same slot. A symbol key also stays out of `Object.keys`, so it does\n * not join the context's string-keyed surface.\n *\n * The map dies with the context, which dies with the SDK, so this holds nothing\n * longer than the `WeakMap` did.\n *\n * Keyed on the filter, because a filtered read is not a one-off: the MCP server\n * calls `getRegistry({ package: \"mcp\" })` inside its request handlers, so\n * skipping the cache there would rebuild the whole projection per request. The\n * map is bounded by the number of distinct filters a host actually uses, which\n * is one or two.\n */\nconst REGISTRY_CACHE: unique symbol = Symbol.for(\"kitcore.registryCache\");\n\ntype CachingContext = SdkContext & {\n [REGISTRY_CACHE]?: Map<string, RegistryResult>;\n};\n\n/**\n * Freeze the containers before a memoized registry is shared.\n *\n * Every reader holds the same object now, so an in-place `sort` or `splice` on\n * `functions` would reorder the registry for everything else in the process,\n * including the CLI's command generator and MCP's tool list. Before the memo\n * each caller got a private copy and that was harmless, so the hazard is new\n * and worth failing loudly on rather than documenting alone.\n *\n * Every container, including the `functions` array each category carries. The\n * asymmetry is what makes a half-done freeze worse than none: the same sort one\n * level up throws, so an author learns the rule there and gets no warning when\n * they reach for a category's own list.\n *\n * The containers only. Entries are left alone deliberately: they carry zod\n * schemas, and freezing library objects invites breakage for a mutation nobody\n * has a reason to make.\n */\nfunction freezeContainers(registry: RegistryResult): RegistryResult {\n Object.freeze(registry.functions);\n for (const category of registry.categories) {\n Object.freeze(category.functions);\n Object.freeze(category);\n }\n Object.freeze(registry.categories);\n return Object.freeze(registry);\n}\n\n/**\n * The single memoized source of truth behind every registry read. The result is\n * shared by every reader, so it is frozen: see {@link freezeContainers}.\n */\nexport function getCachedRegistry(\n context: SdkContext,\n packageFilter?: string,\n): RegistryResult {\n // `buildRegistry` treats an empty filter as no filter, so both collapse to\n // one key rather than caching the same projection twice.\n const key = packageFilter ?? \"\";\n const caching = context as CachingContext;\n let byFilter = caching[REGISTRY_CACHE];\n if (!byFilter) {\n byFilter = new Map();\n caching[REGISTRY_CACHE] = byFilter;\n }\n let registry = byFilter.get(key);\n if (!registry) {\n registry = freezeContainers(buildSurfaceRegistry(context, packageFilter));\n byFilter.set(key, registry);\n }\n return registry;\n}\n\n/** Drop every memoized registry for a context after its surface mutates\n * (post-seal `addPlugin`), so the next read reflects the change. Clears all\n * filters at once: one added method can appear in any of them.\n *\n * Every kitcore copy in the process reads the same slot, so one call clears the\n * cache for all of them. */\nexport function invalidateRegistryCache(context: SdkContext): void {\n delete (context as CachingContext)[REGISTRY_CACHE];\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 // Resolve a live-getter property to its value so a proxy root (e.g. `apps`)\n // is present for `buildRegistry`'s inclusion filter and its dynamic members\n // survive. Built BEFORE the projection so a legacy formatter adapter\n // captures a complete sdk.\n const surface: Record<string, unknown> = {};\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] =\n entry.pluginType === \"property\" && entry.getValue\n ? entry.getValue()\n : entry.value;\n }\n const projection = collectSurfaceProjection(context, surface);\n // Layer the legacy bridge's registry of record on top, exactly as its own\n // synthesized `getRegistry` does. `context.meta` is written only by the\n // legacy pass, so this is a no-op for a pure module-model SDK, and without it\n // the free `getRegistry(sdk)` and a bridged SDK's surfaced `getRegistry()`\n // return different registries: templated entries like `apps.{appKey}` have no\n // static binding, so the surface projection cannot see them.\n Object.assign(projection.meta, context.meta);\n return buildRegistry({\n sdk: surface,\n ...projection,\n packageFilter,\n });\n}\n","import type { z } from \"zod\";\nimport type { SdkPage } from \"../types/pagination\";\nimport type { OutputDataValidationReport } from \"../types/output-validation\";\nimport {\n createCoreError,\n CoreErrorCode,\n type AdaptError,\n} from \"../types/errors\";\n\n/**\n * Output validation: when a method declares an `outputSchema`, the materializer\n * validates and strips `run`'s output against it. An author opts out per method\n * with `skipOutputValidation`, a caller opts out for ONE call with the reserved\n * {@link SKIP_OUTPUT_DATA_VALIDATION} key, and a head opts IN to reporting what the\n * strip removed with the `includeOutputValidationDroppedPaths` core option.\n *\n * Item methods return `{ data }`; the item schema validates `data`. List methods\n * return a page of items; the same item schema validates each item (see the\n * list core in the materializer). Both paths share {@link diffDroppedPaths} and\n * the strip-only assumption below.\n */\n\n/** True for a plain JSON object we recurse into: not an array, not null. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The paths present in `raw` but absent from `parsed`: the keys a strip-parse\n * removed. Behavior matches connectors' `diffDroppedKeys`, so the same stripped\n * response reports the same paths in either ecosystem.\n *\n * Strip-only assumption: a Zod object parse preserves values and only drops\n * unknown keys, so a key missing from `parsed` was stripped. Comparing key\n * PRESENCE rather than values means a field the schema merely re-valued\n * (coercion, `.catch()`, a value-level `.transform()`) keeps its key in both and\n * is correctly not flagged. The accepted edges: a `.default()` that ADDS a key\n * appears only in `parsed`, so it is never mislabeled as dropped, while a\n * key-RENAMING transform could surface the old key as dropped.\n *\n * Paths are relative to `data`, dot-notated for object keys. Keys dropped from\n * array elements collapse under a single `[]` segment and are unioned across\n * elements: `items[].name`, never `items[0].name` / `items[1].name` / … A\n * validated output is overwhelmingly a homogeneous list, so the per-index form\n * is just noise; the tradeoff is that a key dropped from only some elements\n * still surfaces once.\n */\nexport function diffDroppedPaths(\n raw: unknown,\n parsed: unknown,\n prefix = \"\",\n): string[] {\n const paths: string[] = [];\n walkDroppedPaths(raw, parsed, prefix, paths);\n return paths;\n}\n\nfunction walkDroppedPaths(\n raw: unknown,\n parsed: unknown,\n prefix: string,\n out: string[],\n): void {\n if (Array.isArray(raw) && Array.isArray(parsed)) {\n // Collapse every element under one `[]` segment, unioning the dropped keys,\n // so a homogeneous list reports each dropped key once. Bounded by the\n // shorter array so a parse that drops elements never walks past the end of\n // `parsed` and reports its whole tail as dropped.\n const seen = new Set<string>();\n const length = Math.min(raw.length, parsed.length);\n for (let index = 0; index < length; index++) {\n const elementPaths: string[] = [];\n walkDroppedPaths(raw[index], parsed[index], `${prefix}[]`, elementPaths);\n for (const path of elementPaths) {\n if (seen.has(path)) continue;\n seen.add(path);\n out.push(path);\n }\n }\n return;\n }\n\n if (isRecord(raw) && isRecord(parsed)) {\n for (const key of Object.keys(raw)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (!(key in parsed)) {\n // Record the dropped key itself; don't descend into a subtree that no\n // longer exists in `parsed`.\n out.push(path);\n continue;\n }\n walkDroppedPaths(raw[key], parsed[key], path, out);\n }\n return;\n }\n\n // Primitives, or a shape mismatch (object vs array vs primitive): no\n // key-level drop to report here.\n}\n\n/**\n * The reserved call-object key a caller uses to bypass output validation for\n * ONE invocation: a sibling of a tool's `input`, like `cursor` / `pageSize`,\n * never inside it. Named once here so every surface that grows the control later\n * (a CLI flag, an MCP field) spells it the same way.\n *\n * Reserved on item and list only. Raw claims no key in the caller's object; see\n * {@link CallOutputOptions}.\n */\nexport const SKIP_OUTPUT_DATA_VALIDATION = \"skipOutputDataValidation\" as const;\n\n/**\n * Whether this call asked to bypass output validation. A literal `true` only:\n * a control that weakens validation must take nothing looser, so a stray `1` or\n * `\"true\"` arriving from a CLI or a wire means \"don't skip\".\n */\nexport function readSkipOutputDataValidation(options: unknown): boolean {\n return isRecord(options) && options[SKIP_OUTPUT_DATA_VALIDATION] === true;\n}\n\n/** One call's output-validation config: the schema lives in the descriptor's\n * `meta`, the author opt-out is a first-class plugin field, the caller opt-out\n * rides the call object, and the dropped-path report is a head's core option\n * (so it is read per call, not per method). */\nexport interface OutputPolicy {\n outputSchema?: z.ZodSchema;\n skipOutputValidation?: boolean;\n /** This one call asked to skip. Can only ever skip: an author who opted out\n * stays opted out, and a caller can never force validation back on. */\n skippedByCaller?: boolean;\n /** Attach `meta.outputDataValidation.droppedPaths` describing what the strip\n * removed. When false, the diff is never computed. */\n includeOutputValidationDroppedPaths?: boolean;\n /** Names the method in a validation failure, so the message says which one. */\n methodName?: string;\n /** The head's error factory, so an output failure brands like every other\n * framework error instead of escaping as a bare `ZodError`. */\n adaptError?: AdaptError;\n}\n\n/**\n * The schema the framework will parse against, or `undefined` when it will not.\n * An author opt-out wins outright and a caller can only ever subtract, never\n * force validation onto a plugin whose author disabled it.\n *\n * Returns the schema rather than a boolean so that \"we validate\" and \"we have\n * something to validate with\" are one fact the caller narrows on, instead of a\n * boolean plus a non-null assertion on the schema at every use.\n */\nfunction resolveValidatingSchema(\n policy: OutputPolicy,\n): z.ZodSchema | undefined {\n if (policy.skipOutputValidation || policy.skippedByCaller) return undefined;\n return policy.outputSchema;\n}\n\n/**\n * Whether to attach a report with nothing notable in it. A method reports only\n * when the caller's flag CHANGED something. On a plugin\n * the author already opted out of, that flag is a no-op, and saying otherwise\n * would claim a bypass that never happened.\n */\nfunction shouldReport(policy: OutputPolicy): boolean {\n return (\n policy.skippedByCaller === true &&\n policy.outputSchema !== undefined &&\n !policy.skipOutputValidation\n );\n}\n\n/**\n * Parse a value against the output schema, throwing a framework error that says\n * OUTPUT validation and names the method. Zod's own issue text reads \"Invalid\n * input: …\" whatever it validates, so without this framing a response-shape\n * mismatch is indistinguishable from a rejected argument. Mirrors connectors,\n * which wraps the same failure for the same reason, and routes through\n * `createCoreError` so a head's `adaptError` can brand it.\n *\n * `locator` names the position inside the response for a list (`data[3]`), which\n * validates item by item; omitted for an item method's single envelope. `hint`\n * names a likely cause the issue list cannot show on its own.\n *\n * The message names BOTH escapes, because the two audiences cannot use each\n * other's. An author corrects the schema or opts the method out; a caller of a\n * published SDK can do neither, and the per-call bypass is the only thing left\n * to them. That bypass is deliberately undocumented elsewhere: it is a way out\n * of a bad moment, not a feature to reach for, so this failure is where a\n * caller should first hear about it.\n */\nfunction parseOutput(\n schema: z.ZodSchema,\n value: unknown,\n policy: OutputPolicy,\n {\n locator,\n hint,\n callerCanSkip = true,\n }: { locator?: string; hint?: string; callerCanSkip?: boolean } = {},\n): unknown {\n const result = schema.safeParse(value);\n if (result.success) return result.data;\n\n const issues = result.error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"data\";\n return `${path}: ${issue.message}`;\n });\n const subject = policy.methodName ? ` for \"${policy.methodName}\"` : \"\";\n const at = locator ? ` at ${locator}` : \"\";\n\n throw createCoreError(\n {\n code: CoreErrorCode.Validation,\n message:\n `Output validation failed${subject}${at}:\\n ${issues.join(\"\\n \")}\\n\\n` +\n (hint ? `${hint}\\n\\n` : \"\") +\n `The response does not match the method's \\`outputSchema\\`. Correct the ` +\n `schema, or set \\`skipOutputValidation: true\\` on the method to pass the ` +\n `response through unvalidated.` +\n (callerCanSkip\n ? ` A caller who cannot change the method can pass ` +\n `\\`skipOutputDataValidation: true\\` with the input to bypass this one call.`\n : ``),\n details: { zodErrors: result.error.issues, output: value },\n },\n policy.adaptError,\n );\n}\n\n/**\n * Validate + strip an item method's `{ data }` envelope against its\n * `outputSchema`, returning the validated envelope. With\n * `includeOutputValidationDroppedPaths`, stripped paths land in\n * `meta.outputDataValidation.droppedPaths` (additive: existing `meta` is preserved).\n * Parsing is a no-op when there is no `outputSchema`, when the author opted out,\n * when this call opted out, or when the result is not a `{ data }` envelope.\n */\nexport function applyItemOutputPolicy(\n result: unknown,\n policy: OutputPolicy,\n): unknown {\n const schema = resolveValidatingSchema(policy);\n const report = shouldReport(policy);\n if (!schema && !report) return result;\n if (!isRecord(result) || !(\"data\" in result)) return result;\n\n if (!schema) {\n return {\n ...result,\n meta: withOutputValidation(result.meta, { skipped: true }),\n };\n }\n\n const data = parseOutput(schema, result.data, policy);\n const validation = buildValidatedReport({\n policy,\n before: result.data,\n after: data,\n });\n const next: Record<string, unknown> = { ...result, data };\n if (validation) next.meta = withOutputValidation(result.meta, validation);\n return next;\n}\n\n/**\n * Validate a raw method's whole return against its `outputSchema`, handing back\n * the ORIGINAL value untouched.\n *\n * Raw has no envelope, so the payload the schema describes IS the return value.\n * That keeps `outputSchema` meaning one thing in every mode (the payload: the\n * whole return here, `data` for an item, each element for a list) instead of\n * being silently inert in one of them. It also makes a forgotten `output:\n * \"item\"` announce itself, since a returned `{ data }` envelope cannot match a\n * schema describing what is inside it.\n *\n * Check, never replace. Raw's contract is that the framework does not shape the\n * result, and `parse` returns a stripped clone, which would swap out the\n * caller's object and break a method handing back a live one. So extras\n * survive, and there are no dropped paths to report, which raw could not report\n * anyway, having no `meta` to carry.\n *\n * One exception, in the caller: a raw method returning a PROMISE gets a new\n * promise, because the check has to await the value before it can parse it. So\n * a decorated thenable loses its decoration, a `PaginatedSdkResult` losing\n * `pages()`. The schema is not what costs it: `createRawFunction` re-wraps any\n * thenable result to fire `onMethodEnd`, so the decoration is already gone.\n * Nothing in this repo returns one from a raw method.\n */\nexport function applyRawOutputPolicy(\n result: unknown,\n policy: OutputPolicy,\n): unknown {\n const schema = resolveValidatingSchema(policy);\n if (!schema) return result;\n // Catching the mistake is not the same as explaining it. A method that meant\n // to be an item reports \"data: expected string, received undefined\" and\n // nothing points at the missing output mode, so say it where we can see it.\n const looksLikeEnvelope = isRecord(result) && \"data\" in result;\n // The parsed value is deliberately discarded: this is the check, not the\n // shaping.\n parseOutput(schema, result, policy, {\n hint: looksLikeEnvelope\n ? 'This returned a `{ data }` envelope, and with no `output` mode the schema is matched against the WHOLE return. Did you mean `output: \"item\"` (or `\"list\"`)?'\n : undefined,\n // Raw reserves nothing in the caller's call object, so there is no per-call\n // skip to point at. Offering one would be advice that does nothing.\n callerCanSkip: false,\n });\n return result;\n}\n\n/**\n * Merge a report into an existing (possibly absent) meta, under the current key\n * and the deprecated one.\n *\n * `outputValidation` shipped in 0.12.0 and is written for one more release, so\n * a consumer reading it does not silently start seeing `undefined`. It keeps\n * its old emission rule exactly: present only when the strip actually removed\n * something, never on a skip, which the old code could not report at all.\n */\nfunction withOutputValidation(\n existing: unknown,\n outputDataValidation: OutputDataValidationReport,\n): Record<string, unknown> {\n const base = isRecord(existing) ? existing : {};\n const deprecated =\n outputDataValidation.skipped === false && outputDataValidation.droppedPaths\n ? {\n outputValidation: { droppedPaths: outputDataValidation.droppedPaths },\n }\n : {};\n return { ...base, outputDataValidation, ...deprecated };\n}\n\n/**\n * The report to attach after a successful parse, or `undefined` when there is\n * nothing worth saying.\n *\n * Item mode and list mode share this so that the two cannot describe the same\n * outcome differently, and so the rule that the diff is never computed unless\n * the head asked for it has one home rather than two.\n */\nfunction buildValidatedReport({\n policy,\n before,\n after,\n}: {\n policy: OutputPolicy;\n before: unknown;\n after: unknown;\n}): OutputDataValidationReport | undefined {\n // Gated on the head's option alone, which keeps that option's promise that\n // off means no diff is computed.\n const droppedPaths = policy.includeOutputValidationDroppedPaths\n ? diffDroppedPaths(before, after)\n : [];\n // Reached only after a real parse, so a caller's skip is already ruled out\n // and dropped paths are the only thing left worth reporting. That is why\n // there is no `{ skipped: false, droppedPaths: null }` branch here: see\n // {@link OutputDataValidationReport} for why the type carries that arm.\n if (droppedPaths.length === 0) return undefined;\n return {\n skipped: false,\n droppedPaths,\n instruction:\n \"Some fields were removed from `data` by output validation. To receive \" +\n `the raw, unvalidated result instead, set \\`${SKIP_OUTPUT_DATA_VALIDATION}\\`.`,\n };\n}\n\n/**\n * Validate + strip each item of a list page against the item `outputSchema`,\n * returning a new page. With `includeOutputValidationDroppedPaths`, paths\n * stripped from any item land in `page.meta.outputDataValidation.droppedPaths`, set\n * only when something was dropped. Parsing is a no-op when there is no\n * `outputSchema`, when the author opted out, or when this call opted out. This\n * is item mode's sibling: the item schema describes one element, so the whole\n * list conforms element by element.\n *\n * A page's `data` IS the array, so its paths carry the `[]` element segment and\n * are unioned across items (`[].secret`, once, however many items dropped it).\n * That is the same collapse {@link diffDroppedPaths} applies to an array nested\n * inside an item.\n */\nexport function applyListOutputPolicy<T>(\n page: SdkPage<T>,\n policy: OutputPolicy,\n): SdkPage<T> {\n const schema = resolveValidatingSchema(policy);\n const report = shouldReport(policy);\n if (!schema && !report) return page;\n\n if (!schema) {\n return {\n ...page,\n meta: withOutputValidation(page.meta, { skipped: true }),\n };\n }\n\n const data = page.data.map(\n (item, index) =>\n parseOutput(schema, item, policy, { locator: `data[${index}]` }) as T,\n );\n // The arrays go in whole: the array branch of the walk is what collapses\n // elements under `[]` and unions the keys across them.\n const validation = buildValidatedReport({\n policy,\n before: page.data,\n after: data,\n });\n const next: SdkPage<T> = { ...page, data };\n if (validation)\n next.meta = withOutputValidation(\n page.meta,\n validation,\n ) as SdkPage<T>[\"meta\"];\n return next;\n}\n","import { buildHooks } from \"../utils/build-hooks\";\nimport type { MethodHooks } from \"../utils/build-hooks\";\nimport {\n applyPluginToSdk,\n checkRootKeyCollisions,\n splitPluginContribution,\n} from \"../utils/plugin-utils\";\nimport {\n createFunction,\n createPaginatedFunction,\n createRawFunction,\n INTERNAL_CALL,\n resolveCoreOptions,\n} from \"../utils/function-utils\";\nimport {\n childCallContext,\n rootCallContext,\n type Annotations,\n type CallContext,\n} from \"../utils/call-context\";\nimport {\n applyItemOutputPolicy,\n applyListOutputPolicy,\n applyRawOutputPolicy,\n readSkipOutputDataValidation,\n type OutputPolicy,\n} from \"../utils/output-policy\";\nimport {\n stripFrameworkOnlyOptions,\n withheldFromRun,\n ITEM_FRAMEWORK_OPTIONS,\n LIST_FRAMEWORK_OPTIONS,\n} from \"../utils/call-options\";\nimport type { RegistryResult } from \"../registry\";\nimport type { PluginMeta, Plugin, PluginProvides } from \"../types/plugin\";\nimport { legacyGraphEntry } from \"./legacy\";\nimport { CONTEXT, parseId } from \"./shared\";\nimport { CORE_OPTIONS_ID } from \"../utils/core-options\";\nimport { normalizeStability } from \"../utils/stability\";\nimport { runIsolatedObserver } from \"../utils/method-scope\";\n\nimport { getCachedRegistry, invalidateRegistryCache } from \"./registry-support\";\nimport type {\n AddedSurface,\n AggregateEntry,\n AggregatePlugin,\n AggregateSdkOf,\n AnyAggregatePlugin,\n AnyLeafPlugin,\n AnyMethodPlugin,\n AnyPropertyPlugin,\n AnyPlugin,\n BoundAdditionalKeys,\n BoundField,\n BoundFormatter,\n BoundResolver,\n CompletenessOf,\n CreateSdkOptions,\n DisposeFn,\n Field,\n Formatter,\n ImportBinding,\n ResolverRef,\n MethodSdkOf,\n PropertySdkOf,\n LegacyMergePlugin,\n LegacyPlugin,\n MethodEntry,\n MethodOverridePlugin,\n NormalizedOutput,\n Resolver,\n OutputConfig,\n PluginEntry,\n PropertyEntry,\n ExportSurface,\n SdkContext,\n SdkInternals,\n} from \"./types\";\n\n/** Configuration ids the framework itself consumes (the boundary resolves\n * them internally), so injection never requires a declaring plugin. */\nconst FRAMEWORK_CONFIGURATION_IDS: ReadonlySet<string> = new Set([\n CORE_OPTIONS_ID,\n]);\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\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// The context key lives in `shared` so `types` can name it without importing\n// this module. Re-exported here because that is where consumers reach it.\nexport { CONTEXT } from \"./shared\";\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/**\n * A property that declares `dynamicMembers` must have a value from the moment\n * the SDK is built.\n *\n * The registry decides whether to report `apps.{appKey}` by asking whether\n * `sdk.apps` is a live object, which is the right question: nothing under a\n * null root is callable. But the answer is memoized, and only `addPlugin`\n * drops that memo, because only `addPlugin` changes the surface. A property\n * whose value arrives later is not a surface change, so a read taken during\n * that window is the answer every later read gets.\n *\n * Rather than caching a moving answer or advertising members a caller cannot\n * invoke, the combination is unsupported and says so here. Build the root in\n * `setup` and return it from `get`, which is what a proxy root already does.\n *\n * Checked at BUILD, not at read. A read-time throw would fire inside the very\n * window this rules out, which is the wrong place to learn the rule.\n */\nfunction assertDynamicMemberRoot(entry: PropertyEntry): void {\n if (!entry.dynamicMembers?.length) return;\n const value = entry.getValue ? entry.getValue() : entry.value;\n if (typeof value === \"object\" && value !== null) return;\n throw new Error(\n `Property \"${entry.name}\" declares dynamicMembers, so its value must be an ` +\n `object when the SDK is built; got ${value === null ? \"null\" : typeof value}. ` +\n `Build the root in \\`setup\\` and return it from \\`get\\`, so members like ` +\n `\"${entry.dynamicMembers[0].name}\" are reportable from the first registry read.`,\n );\n}\n\n/**\n * Read an SDK's registry from outside its surface, so a head need not re-export\n * `getRegistryPlugin` for a controller to introspect it. Module-model SDKs go\n * through the shared, memoized {@link getCachedRegistry} (context-keyed, so this\n * and a surfaced `getRegistry()` return the same object). A pure-legacy\n * stack-built SDK has no `[CONTEXT]` graph; for those the only path is a\n * surfaced `getRegistry()`, so fall back to it when present. Each package\n * filter is memoized separately.\n */\nexport function getRegistry(\n sdk: unknown,\n packageFilter?: string,\n): RegistryResult {\n // Guard before the property read: `createController` accepts any object, so a\n // nullish sdk reaches here and would otherwise throw a bare TypeError about a\n // symbol nobody outside kitcore has heard of.\n // A callable counts: an SDK can be a function with methods hung off it, and\n // it may carry a context or a surfaced accessor like any other.\n if ((typeof sdk !== \"object\" && typeof sdk !== \"function\") || sdk === null)\n throw createNoRegistryError();\n const context = getContext(sdk);\n // A context with a surface map is the registry source, empty map included: an\n // imports-only root legitimately surfaces nothing, and its registry is empty\n // rather than unavailable. Legacy-bridged SDKs record their root keys here\n // too, so they read the same way. Only something with no surface at all (a\n // stack-built SDK, or a test double exposing plugins off-context) falls\n // through to a surfaced `getRegistry()`.\n if (context?.surface) return getCachedRegistry(context, packageFilter);\n const surfaced = (sdk as { getRegistry?: unknown }).getRegistry;\n if (typeof surfaced === \"function\") {\n return surfaced.call(\n sdk,\n packageFilter ? { package: packageFilter } : undefined,\n ) as RegistryResult;\n }\n throw createNoRegistryError();\n}\n\nfunction createNoRegistryError(): Error {\n return new Error(\n \"getRegistry: sdk has no kitcore context and no surfaced getRegistry().\",\n );\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 const ak = resolver.additionalKeys;\n if (ak) {\n if (!isResolverRef(ak.values)) out.push(ak.values);\n if (ak.keys && !isResolverRef(ak.keys)) out.push(ak.keys);\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/** True for a `declareDefault` wrapper: a real plugin marked as the DEFAULT\n * provider for its id, preempted by any explicit provider of the same id. */\nfunction isDefault(plugin: AnyPlugin): boolean {\n return (\n (plugin.pluginType === \"method\" || plugin.pluginType === \"property\") &&\n (plugin as { defaultSource?: unknown }).defaultSource !== undefined\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 *\n * `configuration` entries substitute BEFORE the missing-dependency check, so an\n * injected value satisfies a required stand-in the same way a registered\n * provider would (see {@link CreateSdkOptions}).\n */\nfunction collectPlugins(\n root: AnyPlugin,\n materialized: ReadonlySet<string> = new Set(),\n configuration?: Record<string, unknown>,\n): Map<string, AnyPlugin> {\n // Resolution rank: an explicit provider (2) beats a `declareDefault` provider\n // (1) beats a stand-in (0). Higher rank wins; two explicit is a duplicate.\n const rank = (plugin: AnyPlugin): number =>\n isStandIn(plugin) ? 0 : isDefault(plugin) ? 1 : 2;\n\n // Phase 1: collect every candidate reachable from the root, IGNORING\n // preemption, so both a default and the explicit provider that preempts it\n // are seen. An id already in the live graph (incremental addPlugin) is a\n // boundary: it is materialized, so it satisfies a stand-in and is not\n // re-collected.\n const allNodes: AnyPlugin[] = [];\n const seen = new Set<AnyPlugin>();\n const collect = (plugin: AnyPlugin): void => {\n if (materialized.has(plugin.id) || seen.has(plugin)) return;\n seen.add(plugin);\n allNodes.push(plugin);\n for (const edge of edgesOf(plugin)) collect(edge);\n };\n collect(root);\n\n const childrenOf = new Map<AnyPlugin, AnyPlugin[]>();\n const candidatesById = new Map<string, AnyPlugin[]>();\n for (const node of allNodes) {\n childrenOf.set(\n node,\n edgesOf(node).filter((edge) => seen.has(edge)),\n );\n const candidates = candidatesById.get(node.id);\n if (candidates) candidates.push(node);\n else candidatesById.set(node.id, [node]);\n }\n\n // Phase 2: prune to the live set by greatest fixpoint. A node stays live\n // unless it is unreachable through live winners, or a strictly higher-rank\n // candidate for its id is reachable (preemption). Both rules only shrink\n // `live`, so this converges. Resolving preemption BEFORE committing a subtree\n // is what drops a preempted default's private dependencies: once a default\n // loses its id, the deps only it reached become unreachable and fall out too.\n // A dependency shared with a still-live plugin stays reachable by that path.\n const live = new Set<AnyPlugin>(allNodes);\n for (;;) {\n // Reachability through live winners: descend only through live nodes.\n const reachable = new Set<AnyPlugin>();\n if (live.has(root)) reachable.add(root);\n const queue: AnyPlugin[] = reachable.has(root) ? [root] : [];\n while (queue.length) {\n const node = queue.pop() as AnyPlugin;\n for (const child of childrenOf.get(node) ?? []) {\n if (reachable.has(child)) continue;\n reachable.add(child);\n // Only descend past a node that is itself a live winner.\n if (live.has(child)) queue.push(child);\n }\n }\n let changed = false;\n for (const node of live) {\n if (!reachable.has(node)) {\n live.delete(node);\n changed = true;\n }\n }\n // Preemption: within an id, a strictly higher-rank live candidate drops the\n // lower-rank ones.\n for (const candidates of candidatesById.values()) {\n let maxRank = -1;\n for (const candidate of candidates) {\n if (live.has(candidate)) maxRank = Math.max(maxRank, rank(candidate));\n }\n if (maxRank < 0) continue;\n for (const candidate of candidates) {\n if (live.has(candidate) && rank(candidate) < maxRank) {\n live.delete(candidate);\n changed = true;\n }\n }\n }\n if (!changed) break;\n }\n\n // Build the id -> winner map from the live set. Remaining live candidates for\n // an id all share the max rank (lower ranks were preempted), so any tie is a\n // same-rank clash: two explicit is a duplicate; two defaults dedup by source\n // or conflict; multiple stand-ins are just repeated references.\n const byId = new Map<string, AnyPlugin>();\n // Ids where two DIFFERENT defaults collided. Fatal only if a default is still\n // the winner at the end (an explicit provider or configuration settles it).\n const conflictedDefaults = new Set<string>();\n const isOptional = (plugin: AnyPlugin): boolean =>\n \"optional\" in plugin &&\n (plugin as { optional?: boolean }).optional === true;\n for (const [id, candidates] of candidatesById) {\n const liveCandidates = candidates.filter((candidate) =>\n live.has(candidate),\n );\n // Prefer a required (non-optional) candidate: a required reference must win\n // the \"is this satisfied?\" question, so an unprovided id fails regardless of\n // import order. Real providers (rank > 0) are never optional, so this only\n // settles ties among stand-ins.\n const winner =\n liveCandidates.find((candidate) => !isOptional(candidate)) ??\n liveCandidates[0];\n if (!winner) continue;\n if (liveCandidates.length > 1) {\n const winnerRank = rank(winner);\n if (winnerRank === 2) {\n throw new Error(\n `createSdk: duplicate plugin id \"${id}\". Two different ` +\n `plugins registered under the same id.`,\n );\n }\n if (winnerRank === 1) {\n const sources = new Set(\n liveCandidates.map(\n (candidate) =>\n (candidate as { defaultSource?: unknown }).defaultSource,\n ),\n );\n if (sources.size > 1) conflictedDefaults.add(id);\n }\n }\n byId.set(id, winner);\n }\n\n if (configuration) {\n for (const [id, value] of Object.entries(configuration)) {\n const existing = byId.get(id);\n if (!existing) {\n // A framework-consumed id (the method boundary resolves it internally,\n // no plugin declares it) is always known: synthesize the value\n // property directly.\n if (FRAMEWORK_CONFIGURATION_IDS.has(id)) {\n const { name, namespace } = parseId(id);\n byId.set(id, {\n pluginType: \"property\",\n name,\n namespace,\n id,\n imports: [],\n importBindings: [],\n value,\n });\n continue;\n }\n throw new Error(\n `createSdk: configuration id \"${id}\" matches no plugin in the ` +\n `graph. An injected value must satisfy a property stand-in ` +\n `reachable from the root.`,\n );\n }\n if (existing.pluginType !== \"property\") {\n throw new Error(\n `createSdk: configuration id \"${id}\" resolves to a ` +\n `\"${existing.pluginType}\" plugin; only property values can be ` +\n `injected.`,\n );\n }\n if (!isStandIn(existing)) {\n throw new Error(\n `createSdk: configuration id \"${id}\" collides with a registered ` +\n `provider. A property is either injected or provided by a ` +\n `plugin, not both.`,\n );\n }\n byId.set(id, {\n pluginType: \"property\",\n name: existing.name,\n namespace: existing.namespace,\n id,\n imports: [],\n importBindings: [],\n value,\n });\n }\n }\n\n for (const [id, plugin] of byId) {\n if (isStandIn(plugin)) {\n // A `declareOptionalProperty` stand-in left unsatisfied is not an error: it stays\n // in the graph (so topological order is consistent) but materializes no\n // entry, and dependents bind `undefined` (see buildImports).\n if (\"optional\" in plugin && plugin.optional) continue;\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\n for (const id of conflictedDefaults) {\n const winner = byId.get(id);\n if (winner && isDefault(winner)) {\n throw new Error(\n `createSdk: conflicting defaults for \"${id}\". Two different plugins ` +\n `were declared as defaults for the same id and nothing else ` +\n `provides it. Register an explicit (non-default) plugin for this ` +\n `id to choose the winner, or give the implementations distinct ids ` +\n `if they are meant to coexist.`,\n );\n }\n }\n return byId;\n}\n\n/**\n * Which twin `bindValue` binds: the surface callable or a method's internal\n * twin. Distinct from `CallOrigin` (whether a call's root is user work or\n * framework machinery) even though both happen to spell `\"surface\" | \"internal\"`\n * — an import always binds the internal twin yet can still be surface-origin.\n */\ntype BindMode = \"surface\" | \"internal\";\n\ntype InternalMethodCallable = (...args: unknown[]) => unknown;\n\ninterface BindInternalTwinOptions {\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n withContext: (context: CallContext) => InternalMethodCallable;\n internalValue: InternalMethodCallable;\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,\n key,\n entry,\n bindMode = \"surface\",\n ctx,\n frameworkOrigin = false,\n}: {\n target: Record<string, unknown>;\n key: string;\n entry: PluginEntry;\n bindMode?: BindMode;\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n}): void {\n if (entry.pluginType === \"property\" && entry.getValue) {\n // A threaded per-call context flows into the property's getter so a\n // context-aware property (one whose value is derived per call) reads the\n // live callId. Method calls always have a context, at any depth — the\n // boundary resolves one before `run`. The two binds without one are the ones\n // with no call in flight: the SDK object's own property (bound once here) and\n // a `setup`-time imports bag. Those get the bare value.\n const getValue = entry.getValue;\n Object.defineProperty(target, key, {\n get: ctx ? () => getValue(ctx) : getValue,\n enumerable: true,\n configurable: true,\n });\n } else {\n // Import-facing bindings take the internal twin (surface-only concerns\n // like the deprecation signal stay quiet on delegation). With a call\n // context threaded (a per-invocation import bag), the twin carries a child\n // context so the callee sees the right nesting depth and correlation id;\n // without one (build-time binding) it is a parent-less internal call.\n // `frameworkOrigin` marks that parent-less root as framework-internal (so a\n // head can drop its telemetry); the default parent-less twin stays\n // surface-origin so a runtime delegation proxy keeps emitting.\n // Legacy graph entries have no twin and fall back to the one value.\n const value =\n bindMode === \"internal\" && entry.pluginType === \"method\"\n ? (entry.bindInternal?.({ ctx, frameworkOrigin }) ??\n entry.internalValue ??\n entry.value)\n : (entry as MethodEntry | PropertyEntry).value;\n Object.defineProperty(target, key, {\n 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,\n importBindings,\n ctx,\n frameworkOrigin = false,\n}: {\n plugins: Record<string, PluginEntry>;\n importBindings: readonly ImportBinding[];\n ctx?: CallContext;\n frameworkOrigin?: boolean;\n}): Record<string, unknown> {\n const imports: Record<string, unknown> = {};\n for (const { binding, id, optional } of importBindings) {\n const entry = plugins[id];\n if (!entry && optional) {\n // An unsatisfied `declareOptionalProperty` dependency: bind the name as\n // `undefined` so the consumer can fall back to its own defaults.\n Object.defineProperty(imports, binding, {\n value: undefined,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n continue;\n }\n bindValue({\n target: imports,\n key: binding,\n entry,\n bindMode: \"internal\",\n ctx,\n frameworkOrigin,\n });\n }\n return imports;\n}\n\n/**\n * The shared origin rule for a method's import-facing twin, so the positional\n * and single-input projections don't each re-encode it. A threaded `ctx` mints\n * a fresh child per call (callee inherits `callId`/origin, one level deeper); a\n * parent-less twin is the surface-origin `internalValue`, or a fresh\n * framework-internal root only when `frameworkOrigin` is set (kitcore's own\n * build-time passes request that so their calls can be dropped from telemetry).\n * `withContext` adapts the twin's call convention (positional pack vs single\n * input) to the chosen context.\n */\nfunction bindInternalTwin({\n ctx,\n frameworkOrigin,\n withContext,\n internalValue,\n}: BindInternalTwinOptions) {\n if (ctx) {\n return (...args: unknown[]) => withContext(childCallContext(ctx))(...args);\n }\n if (frameworkOrigin) {\n return (...args: unknown[]) =>\n withContext(rootCallContext({ callOrigin: \"internal\" }))(...args);\n }\n return internalValue;\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, states);\n assembleHooks(descriptors, context, states);\n applyMethodOverrides(descriptors, context);\n return context.plugins;\n}\n\n/**\n * Merge one method-override's meta patch onto its target method entry. Fails\n * loud if the target is absent or is not a method: an override must run after\n * its target materializes (the pass order guarantees that within a build;\n * `addPlugin` applies it against the already-live graph).\n */\nfunction applyMethodOverride(\n context: SdkContext,\n override: MethodOverridePlugin,\n): void {\n const entry = context.plugins[override.target];\n if (!entry) {\n throw new Error(\n `defineMethodOverride: no method \"${override.target}\" to override. ` +\n `Include the target method in the SDK build.`,\n );\n }\n if (entry.pluginType !== \"method\") {\n throw new Error(\n `defineMethodOverride: \"${override.target}\" is a ${entry.pluginType}, ` +\n `not a method; only methods can be overridden.`,\n );\n }\n entry.meta = { ...entry.meta, ...override.meta };\n}\n\n/**\n * Final pass: apply every method-override in the graph. Runs after all method\n * entries exist (module or legacy-projected) so each override merges its public\n * meta fields onto the target entry that the surface registry then projects.\n */\nfunction applyMethodOverrides(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n): void {\n for (const descriptor of descriptors.values()) {\n if (descriptor.pluginType !== \"method-override\") continue;\n applyMethodOverride(context, descriptor);\n }\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 // Resolver imports are framework-internal: an SDK method a resolver calls\n // is machinery, not user work, so its root is internal-origin (dropped\n // from telemetry) rather than a surface-origin emitting root.\n const imports = buildImports({\n plugins,\n importBindings: resolver.importBindings,\n frameworkOrigin: true,\n });\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 if (resolver.additionalKeys) {\n const ak = resolver.additionalKeys;\n const boundAk: BoundAdditionalKeys = {\n values: isResolverRef(ak.values)\n ? ak.values\n : bindResolver(ak.values, plugins),\n minEntries: ak.minEntries,\n maxEntries: ak.maxEntries,\n keyValueType: ak.keyValueType,\n valueValueType: ak.valueValueType,\n };\n if (ak.keys)\n boundAk.keys = isResolverRef(ak.keys)\n ? ak.keys\n : bindResolver(ak.keys, plugins);\n bound.additionalKeys = boundAk;\n }\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 case \"dynamic\": {\n // See the object case: resolver imports are internal-origin.\n const imports = buildImports({\n plugins,\n importBindings: resolver.importBindings,\n frameworkOrigin: true,\n });\n const {\n getContext,\n listItems,\n validate,\n tryResolveWithoutPrompt,\n tryResolveFromSearch,\n } = resolver;\n const bound: BoundResolver = {\n type: \"dynamic\",\n requireParameters: resolver.requireParameters,\n inputType: resolver.inputType,\n placeholder: resolver.placeholder,\n prompt: resolver.prompt,\n listItems: ({ input, context, search, cursor }) =>\n listItems({ imports, input, context, search, cursor }),\n };\n if (getContext)\n bound.getContext = ({ input }) => getContext({ imports, input });\n if (validate) {\n bound.validate = ({ value, input, context }) =>\n validate({ imports, value, input, context });\n }\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 default: {\n // Exhaustiveness: adding a resolver kind without a bind branch fails to\n // compile here (and throws for a hostile untyped descriptor).\n const unhandled: never = resolver;\n throw new Error(\n `unhandled resolver kind: ${(unhandled as { type: string }).type}`,\n );\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 // Formatter imports are framework-internal (see bindResolver): an SDK method\n // a formatter calls is machinery, so its root is internal-origin.\n const imports = buildImports({\n plugins,\n importBindings: formatter.importBindings,\n frameworkOrigin: true,\n });\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 // Record the legacy root keys on the surface, the same way `addPlugin`'s\n // legacy branch does. Without it a bridged SDK has an EMPTY surface map,\n // and any surface-driven reader either sees nothing or, once a module\n // plugin is added later, sees only the module half. A legacy method\n // surfaces under its own name (binding === id).\n for (const name of Object.keys(rootKeys)) context.surface[name] = name;\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 // The SAME memoized read the free `getRegistry(sdk)` takes, so a bridged\n // SDK has one registry rather than two that merely agree. They used to\n // differ in everything but content: this one rebuilt per call, so it was\n // unfrozen, a fresh object each time, and it re-paid the whole projection\n // on every MCP request. `buildSurfaceRegistry` layers `context.meta` and\n // builds its own surface from live getters, which is the only thing this\n // needed `this` for.\n function getRegistry(options?: { package?: string }): RegistryResult {\n return getCachedRegistry(context, options?.package);\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), with list adding\n * the page 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 // A stand-in that survived collection is an unsatisfied optional method\n // (`declareOptionalMethod`): materialize no entry, so dependents bind\n // `undefined` rather than a throwing callable. A required stand-in never\n // reaches here (it is either replaced by its provider or already errored).\n if (isStandIn(descriptor)) 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 skipInputValidation: descriptor.skipInputValidation,\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, ctx?: CallContext): unknown => {\n // The boundary always resolves a context before the fold reaches here;\n // the fallback keeps the run bag's `callContext` non-optional for any\n // parent-less path that might call the core directly.\n const callContext = ctx ?? rootCallContext();\n return descriptor.run({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n ctx: callContext,\n }),\n state: states.get(id),\n input,\n callContext,\n annotate: (metadata: Annotations) => {\n Object.assign(callContext.annotations, metadata);\n },\n });\n };\n // Fold the middleware chain around a core, reading `entry.chain` live. The\n // call context is captured in the closure — the middleware chain stays\n // single-argument (`next(input)`), so `ctx` reaches the run bag and each\n // wrap's imports without threading through every `next` call.\n const fold =\n (coreFn: (input: unknown, ctx?: CallContext) => unknown) =>\n (input: unknown, ctx?: CallContext): unknown => {\n let next: (input: unknown) => unknown = (i) => coreFn(i, ctx);\n for (const wrap of entry.chain) {\n const inner = next;\n next = (i: unknown) =>\n wrap.run({\n imports: buildImports({\n plugins,\n importBindings: wrap.owner.importBindings,\n ctx,\n }),\n next: inner,\n input: i,\n // Overwritten by the chain item's own closure with the owning\n // hook's setup state.\n state: undefined,\n });\n }\n return next(input);\n };\n const sdk = { context };\n\n // Hand the boundary a thin per-method pre-run annotator:\n // `(input) => annotations` it invokes synchronously before `onMethodStart`.\n // It receives only `input` — fields needing imports or async work are\n // written mid-`run` via the run bag's `annotate`. Absent when the method\n // declares no `annotator`.\n const methodAnnotator = descriptor.annotator;\n const boundAnnotator = methodAnnotator\n ? (input: unknown) => methodAnnotator({ input })\n : undefined;\n\n // Built per call, not once: the schema and author opt-out are static, but\n // the caller's opt-out rides this call's options and the core options (the\n // dropped-path report, the head's error factory) resolve live at invocation\n // time like every other core option.\n const outputPolicy = (callOptions: unknown): OutputPolicy => {\n const core = resolveCoreOptions(context);\n return {\n outputSchema: descriptor.meta?.outputSchema,\n skipOutputValidation: descriptor.skipOutputValidation,\n skippedByCaller: readSkipOutputDataValidation(callOptions),\n includeOutputValidationDroppedPaths:\n core?.includeOutputValidationDroppedPaths,\n methodName: descriptor.name,\n adaptError: core?.adaptError,\n };\n };\n\n // How this method's boundary treats the framework's call parameters: what\n // it reads out of the caller's object, and what it hands to `run`. Both\n // depend on the mode, and the item mode reads far less than the list one.\n const frameworkOptions =\n out.type === \"list\" ? LIST_FRAMEWORK_OPTIONS : ITEM_FRAMEWORK_OPTIONS;\n // A fact about the mode, so it is worked out once here rather than per\n // page, and with no reading of the plugin's schema.\n const withheld = withheldFromRun(frameworkOptions);\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((input: unknown, ctx?: CallContext) =>\n callRun(stripFrameworkOnlyOptions(input, withheld), ctx),\n ) as (o?: unknown, ctx?: CallContext) => Promise<unknown>,\n {\n sdk,\n schema: descriptor.inputSchema,\n name: descriptor.name,\n frameworkOptions,\n defaultPageSize: out.defaultPageSize,\n adaptPage: out.adaptPage,\n annotator: boundAnnotator,\n // Validate + strip each item against the item `outputSchema`\n // (item mode's sibling); dropped paths surface as `[].x` in the page's\n // `meta`, unioned across items.\n finalizePage: (page, callOptions) =>\n applyListOutputPolicy(page, outputPolicy(callOptions)),\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n } else if (out.type === \"item\") {\n // `run` returns the `{ data }` envelope itself (enforced by the item\n // overload's typing, like list's strict page); the async core inside the\n // fold guarantees a dependent's middleware sees a Promise of that\n // envelope as `next`'s result. The `name` option gives the boundary's\n // hook payload the method name (the folded core is anonymous).\n // The policy reads the caller's skip off the RAW input, before the\n // framework's own parameters are stripped on their way to `run`.\n const itemCore = async (\n input: unknown,\n ctx?: CallContext,\n ): Promise<unknown> =>\n applyItemOutputPolicy(\n await callRun(stripFrameworkOnlyOptions(input, withheld), ctx),\n outputPolicy(input),\n );\n entry.value = createFunction(\n fold(itemCore) as (o?: unknown, ctx?: CallContext) => Promise<unknown>,\n {\n sdk,\n schema: descriptor.inputSchema,\n name: descriptor.name,\n frameworkOptions,\n annotator: boundAnnotator,\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n } else {\n // raw: the boundary supplies the method lifecycle (scope + hook firing)\n // and error-branded validation, but no envelope and no rethrow\n // normalization: the surface is whatever `run` returns, the original\n // error propagates, and a synchronous `run` stays synchronous.\n // `skipInputValidation` passes the raw input through untouched (no parse\n // → no coercion/strip/clone) while keeping `inputSchema` for projection;\n // the method owns its own validation (e.g. `fetch`).\n // Validate the WHOLE return against `outputSchema`, since raw has no\n // envelope for the schema to describe a slice of. Threaded by hand rather\n // than through a boundary seam because raw promises a synchronous `run`\n // stays synchronous: awaiting unconditionally would turn every raw method\n // into a thenable.\n // Static, so decide once: raw is the default mode and the hot path\n // (`fetch`), and building a policy per call costs a second\n // `resolveCoreOptions` plus, for an async return, a microtask hop, before\n // `applyRawOutputPolicy` discovers there is nothing to check.\n const rawValidates =\n descriptor.meta?.outputSchema !== undefined &&\n !descriptor.skipOutputValidation;\n const validateRaw = (out: unknown): unknown => {\n // No call options: the author's opt-out is the only one raw honors.\n const policy = outputPolicy(undefined);\n if (isPromiseLike(out)) {\n return Promise.resolve(out).then((value) =>\n applyRawOutputPolicy(value, policy),\n );\n }\n return applyRawOutputPolicy(out, policy);\n };\n // Raw reserves NOTHING in the caller's call object: no per-call skip is\n // read, and nothing is stripped on the way to `run`. That whole object is\n // the author's, and raw is the mode most likely to forward it verbatim\n // into a request, so a framework key shadowing a domain one there is the\n // worst version of a problem the framework should not create at all. A\n // caller who passes `skipOutputDataValidation` to a raw method is passing\n // domain input that happens to share the name.\n entry.value = createRawFunction(\n (input: unknown, ctx?: CallContext) => {\n const out = fold(callRun)(input, ctx);\n return rawValidates ? validateRaw(out) : out;\n },\n {\n sdk,\n name: descriptor.name,\n schema: descriptor.skipInputValidation\n ? undefined\n : descriptor.inputSchema,\n positional: descriptor.positional,\n annotator: boundAnnotator,\n // The boundary reads the deprecation LIVE off the entry, so a\n // deprecation merged after build (defineMethodOverride, addPlugin)\n // fires too. Same for the stability level, normalized from the\n // entry meta (declared level or legacy `experimental` boolean).\n getDeprecation: () => entry.meta?.deprecation,\n getStability: () =>\n entry.meta ? normalizeStability(entry.meta) : undefined,\n },\n ) as MethodEntry[\"value\"];\n }\n // The import-facing twin: the SAME boundary called with a marker in its\n // second argument slot, so surface-only concerns (the deprecation signal)\n // don't fire when a sibling plugin delegates. The marker is either the\n // `INTERNAL_CALL` sentinel (a parent-less internal call — build-time\n // binding or `resolvePlugin`) or a child `CallContext` minted from the\n // caller's context (a per-invocation delegation, so the callee inherits the\n // `callId` and sits one level deeper). One boundary, thin bindings — no\n // duplicated wrapper stack, and the marker never leaves this writer/reader\n // pair (both created here, by this kitcore copy).\n const canonicalValue = entry.value as (\n input: unknown,\n internal?: typeof INTERNAL_CALL | CallContext,\n ) => unknown;\n // `bindInternal` produces the twin `buildImports` binds; its origin rule\n // lives once in `bindInternalTwin`. The two projections differ only in call\n // convention. Positional projection (see Output): the surface and imports\n // take ordered args; pack them into the canonical `{ input }` before the\n // mode value runs, so validation, middleware, and `run` stay canonical. Set\n // only provided args so trailing optionals (e.g. `fetch(url)`) stay absent.\n if (descriptor.positional) {\n const names = descriptor.positional;\n const pack = (args: unknown[]): Record<string, unknown> => {\n const packed: Record<string, unknown> = {};\n names.forEach((name, i) => {\n if (i < args.length) packed[name] = args[i];\n });\n return packed;\n };\n const internalValue = (...args: unknown[]) =>\n canonicalValue(pack(args), INTERNAL_CALL);\n entry.value = (...args: unknown[]) => canonicalValue(pack(args));\n entry.internalValue = internalValue;\n entry.bindInternal = (opts) =>\n bindInternalTwin({\n ...opts,\n withContext: (context) => {\n return (...args: unknown[]) => canonicalValue(pack(args), context);\n },\n internalValue,\n });\n entry.positional = names;\n } else {\n const internalValue = (input: unknown) =>\n canonicalValue(input, INTERNAL_CALL);\n entry.internalValue = internalValue;\n entry.bindInternal = (opts) =>\n bindInternalTwin({\n ...opts,\n withContext: (context) => (input: unknown) =>\n canonicalValue(input, context),\n internalValue,\n });\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 // overrides only patch meta in the final pass. A stand-in that survived\n // collection is an unsatisfied `declareOptionalProperty`: materialize no entry, so\n // dependents bind `undefined`.\n if (\n !descriptor ||\n descriptor.pluginType === \"aggregate\" ||\n descriptor.pluginType === \"legacy\" ||\n descriptor.pluginType === \"method-override\" ||\n isStandIn(descriptor)\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 // Record teardown in build order (dependencies first); `disposeSdk` walks\n // the list in reverse so dependents release before their dependencies.\n const recordDisposer = (): void => {\n const dispose = (descriptor as { dispose?: DisposeFn }).dispose;\n if (!dispose) return;\n context.disposers?.push({\n id,\n // Teardown is framework-internal: an SDK method a `dispose` calls runs\n // on an internal-origin root (dropped from telemetry).\n dispose: (input?: unknown) =>\n dispose({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n frameworkOrigin: true,\n }),\n state: states.get(id),\n input,\n }),\n });\n };\n if (descriptor.pluginType === \"hook\") {\n // A hook has no surfaced entry; run its `setup` once for the state that\n // `assembleHooks` closes over when composing observers into context.hooks.\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n }),\n })\n : undefined,\n );\n recordDisposer();\n building.delete(id);\n built.add(id);\n return;\n }\n if (descriptor.pluginType === \"method\") {\n states.set(\n id,\n descriptor.setup\n ? descriptor.setup({\n imports: buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n }),\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({\n plugins,\n importBindings: descriptor.importBindings,\n }),\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 dynamicMembers: descriptor.dynamicMembers,\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: (callContext?: CallContext) =>\n get({\n imports: buildImports({\n plugins,\n importBindings,\n ctx: callContext,\n }),\n state: states.get(id),\n callContext,\n }),\n meta: descriptor.meta,\n dynamicMembers: descriptor.dynamicMembers,\n };\n } else {\n plugins[id] = {\n pluginType: \"property\",\n name: descriptor.name,\n value: descriptor.value,\n meta: descriptor.meta,\n dynamicMembers: descriptor.dynamicMembers,\n };\n }\n assertDynamicMemberRoot(plugins[id] as PropertyEntry);\n }\n recordDisposer();\n building.delete(id);\n built.add(id);\n };\n for (const id of descriptors.keys()) ensureBuilt(id);\n}\n\n/**\n * Resolve a plugin's materialized value against a built SDK: a method's\n * callable or a property's value (the same thing an importer receives), NOT\n * the plugin descriptor. For head infrastructure that builds the SDK and\n * needs one of its own internals; consumers use the SDK surface, and in-graph\n * code keeps using `imports`. Read-only against the built graph; nothing\n * materializes. A missing required ref throws; an unsatisfied optional ref\n * resolves `undefined` (matching import behavior); a live `get` property\n * re-reads per call (a read-time snapshot — hold the function, not the value,\n * for liveness). Aggregate refs are not one-ref-one-binding and are\n * unsupported.\n */\nexport function resolvePlugin<TRef extends AnyLeafPlugin>(\n sdk: unknown,\n ref: TRef,\n): ExportSurface<TRef> {\n const entry = getContext(sdk).plugins[ref.id];\n if (!entry) {\n if ((ref as { optional?: boolean }).optional) {\n return undefined as ExportSurface<TRef>;\n }\n throw new Error(\n `resolvePlugin: plugin \"${ref.id}\" is not materialized on the SDK.`,\n );\n }\n // Same binding semantics as buildImports: a method's callable or a\n // property's value — including the internal twin, so out-of-graph\n // infrastructure delegating through resolvePlugin doesn't trip\n // surface-only concerns (deprecation) any more than an importer would. The\n // twin is internal-origin (CLI/MCP infra delegation is machinery, not user\n // work, so it stays out of telemetry); user commands reach methods through\n // the SDK surface (`entry.value`), which emits.\n if (entry.pluginType === \"property\" && entry.getValue) {\n return entry.getValue() as ExportSurface<TRef>;\n }\n if (entry.pluginType === \"method\" && entry.internalValue) {\n return (entry.bindInternal?.({ frameworkOrigin: true }) ??\n entry.internalValue) as ExportSurface<TRef>;\n }\n return (entry as MethodEntry | PropertyEntry).value as ExportSurface<TRef>;\n}\n\n/**\n * Thrown by {@link disposeSdk} when one or more dispose callbacks failed.\n * Every dispose was still attempted; `errors` holds the failures in teardown\n * order.\n */\nexport class CoreDisposeError extends Error {\n readonly name: string = \"CoreDisposeError\";\n readonly errors: unknown[];\n constructor(errors: unknown[]) {\n super(`disposeSdk: ${errors.length} dispose callback(s) failed.`);\n this.errors = errors;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Tear down a built SDK: run every recorded `dispose` (a leaf's `setup` dual)\n * in reverse build order, so dependents release before their dependencies.\n * Each dispose is awaited and run defensively; all are attempted even after a\n * failure, then the failures reject together as {@link CoreDisposeError}.\n * Idempotent: the first call's `input` wins and later calls return the same\n * settled result. A top-level function like `addPlugin`, reaching internals\n * through the `CONTEXT` symbol, so anyone holding the sdk can call it.\n */\nexport function disposeSdk(sdk: unknown, input?: unknown): Promise<void> {\n const context = getContext(sdk);\n if (context.disposed) return context.disposed;\n const disposers = context.disposers ?? [];\n context.disposed = (async () => {\n const errors: unknown[] = [];\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n await disposers[i].dispose(input);\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0) throw new CoreDisposeError(errors);\n })();\n return context.disposed;\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({ target: exports, key: binding, entry: plugins[child.id] });\n }\n plugins[id] = { pluginType: \"aggregate\", name: descriptor.name, exports };\n }\n}\n\n/**\n * Pass 4: assemble wrap chains. Walk hooks in topological order (dependencies\n * first), so a wrapping hook that depends on another sorts after it. Appending\n * in this order leaves each target's chain innermost-first, which the pass-1\n * fold turns into dependents-outermost at call time (retry depends on auth, so\n * retry(auth(core))). A target must be a direct dependency that resolves to a\n * method; the wrap receives the hook's `setup` state alongside the fold's\n * `{ imports, next, input }`.\n */\nfunction assembleMiddleware(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\n): void {\n const plugins = context.plugins;\n for (const id of topoOrder(descriptors)) {\n const descriptor = descriptors.get(id);\n if (!descriptor || descriptor.pluginType !== \"hook\" || !descriptor.wrap) {\n continue;\n }\n for (const [targetBinding, fn] of Object.entries(descriptor.wrap)) {\n const edge = descriptor.importBindings.find(\n (b) => b.binding === targetBinding,\n );\n if (!edge) {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `is not a direct dependency. A wrap target must be a ` +\n `declared import of the wrapping hook.`,\n );\n }\n const target = plugins[edge.id];\n if (!target || target.pluginType !== \"method\") {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `does not resolve to a method.`,\n );\n }\n // A list method's wrap would sit around the page fetcher, not the public\n // PaginatedSdkResult, so it would see raw pages instead of the iterator\n // (see Pass 1). Reject until that contract is settled, rather than\n // silently giving surprising semantics.\n if (target.output?.type === \"list\") {\n throw new Error(\n `createSdk: wrap target \"${targetBinding}\" in hook \"${id}\" ` +\n `resolves to a list-output method, which does not support ` +\n `wrapping yet.`,\n );\n }\n target.chain.push({\n run: (bag) => fn({ ...bag, state: states.get(id) }),\n owner: descriptor,\n });\n }\n }\n}\n\n/**\n * Pass 5: compose module-model hook observers and annotators into the ambient\n * hook registry (`context.hooks`) the method boundary fires. Each `defineHook`'s\n * `observe` fns and its `annotator` are adapted to the boundary's `MethodHooks`\n * shape (the lifecycle context becomes the observer's `input`, alongside its\n * `imports` and `setup` state) and folded in with `buildHooks`, on top of any\n * legacy-contributed hooks. Both run defensively: a thrown observer/annotator\n * error is swallowed so it never breaks the observed call. Walk in topological\n * order so a hook that depends on another composes after it (right-additive,\n * matching legacy ordering).\n */\nfunction assembleHooks(\n descriptors: Map<string, AnyPlugin>,\n context: SdkContext,\n states: Map<string, unknown>,\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 !== \"hook\" ||\n (!descriptor.observe && !descriptor.annotator)\n ) {\n continue;\n }\n const { observe, annotator } = descriptor;\n const state = states.get(id);\n const contributed: MethodHooks = {};\n if (observe?.onMethodStart || observe?.onMethodEnd) {\n // Hook imports are framework-internal: an SDK method an observer calls is\n // machinery, so its root is internal-origin (belt-and-suspenders with the\n // `runIsolatedObserver` hook suppression below). Only observers receive\n // imports; the annotator runs synchronously with `input` only.\n const imports = buildImports({\n plugins,\n importBindings: descriptor.importBindings,\n frameworkOrigin: true,\n });\n // `runIsolatedObserver` gives each observer both protections: defensive\n // execution (an observer error never breaks the observed call) and hook\n // suppression for any SDK method the observer itself calls (no\n // hook -> observer -> method -> hook recursion).\n if (observe.onMethodStart) {\n const onStart = observe.onMethodStart;\n contributed.onMethodStart = (input) => {\n runIsolatedObserver(() => onStart({ imports, input, state }));\n };\n }\n if (observe.onMethodEnd) {\n const onEnd = observe.onMethodEnd;\n contributed.onMethodEnd = (input) => {\n runIsolatedObserver(() => onEnd({ imports, input, state }));\n };\n }\n }\n // The annotator is a pre-run mapper, not a void observer: it returns\n // Annotations the boundary merges before onMethodStart, so it runs plainly\n // (not through `runIsolatedObserver`) with its own best-effort guard so one\n // throwing annotator neither breaks the call nor suppresses the others.\n if (annotator) {\n const annotatorFn = annotator;\n contributed.annotator = ({ methodName, input }) => {\n try {\n return annotatorFn({ methodName, input, state });\n } catch {\n // Annotation inference must never break the call.\n return {};\n }\n };\n }\n context.hooks = buildHooks(context.hooks, contributed);\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. `options.configuration`\n * injects runtime values by plugin id (see {@link CreateSdkOptions}).\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 options?: CreateSdkOptions,\n): MethodSdkOf<P>;\nexport function createSdk<P extends AnyPropertyPlugin>(\n root: P & CompletenessOf<P>,\n options?: CreateSdkOptions,\n): PropertySdkOf<P>;\nexport function createSdk<P extends AnyAggregatePlugin>(\n root: P & CompletenessOf<P>,\n options?: CreateSdkOptions,\n): AggregateSdkOf<P>;\nexport function createSdk<TSurface>(\n root: LegacyPlugin<TSurface>,\n options?: CreateSdkOptions,\n): TSurface & SdkInternals;\nexport function createSdk<\n TProvides extends PluginProvides,\n TPlugin extends AnyPlugin,\n>(\n root: LegacyMergePlugin<TProvides, TPlugin>,\n options?: CreateSdkOptions,\n): TProvides & {\n getRegistry: (options?: { package?: string }) => RegistryResult;\n} & AddedSurface<TPlugin> &\n SdkInternals;\nexport function createSdk(\n root: AnyPlugin | LegacyMergePlugin,\n options?: CreateSdkOptions,\n): Record<string, unknown> {\n const context: SdkContext = {\n plugins: {},\n meta: {},\n hooks: {},\n surface: {},\n disposers: [],\n };\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(\n collectPlugins(collectRoot, undefined, options?.configuration),\n context,\n );\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({\n target: pluginSurface,\n key: plugin.name,\n entry: plugins[plugin.id],\n });\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(\n collectPlugins(root, undefined, options?.configuration),\n context,\n );\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({ target: sdk, key: root.name, entry: 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. A hook surfaces nothing (it has no entry or callable).\n const surfaceKeys =\n plugin.pluginType === \"aggregate\"\n ? Object.keys((plugin as AggregatePlugin).exports)\n : plugin.pluginType === \"hook\"\n ? []\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 // A hook is done here: materialize already appended its wraps to the live\n // chains and composed its observers; there is no entry to surface.\n if (plugin.pluginType === \"hook\") return;\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({ target: sdk, key: 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 const record = sdk as unknown as Record<string, unknown>;\n // A pure-legacy stack-built SDK (createPluginStack().toSdk()) has no\n // `[CONTEXT]` graph, hence every guard below.\n const context = getContext(record);\n try {\n if (typeof plugin === \"function\") {\n const contribution = applyPluginToSdk(\n record,\n plugin as Plugin<unknown, PluginProvides>,\n options ?? {},\n );\n // Mirror addModelPlugin: keep context.plugins/context.surface\n // authoritative for the legacy path too. applyPluginToSdk only writes\n // sdk + context.meta, so without this a surface-driven reader\n // (getRegistryPlugin) would miss a legacy method added after build. The\n // contribution's keys are already collision-checked against the sdk by\n // mergeContribution.\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 } else if ((plugin as AnyPlugin).pluginType === \"method-override\") {\n // An override surfaces nothing; it patches an existing entry's meta\n // against the live graph (no delta to materialize, no root key to bind).\n applyMethodOverride(context, plugin as MethodOverridePlugin);\n } else {\n addModelPlugin(record, plugin as AnyPlugin, options ?? {});\n }\n } finally {\n // Drop the memoized registry AFTER the surface changes, not before. Before\n // would leave the window open for a read during this call to re-cache a\n // half-updated surface; after, such a read sees the old registry, which is\n // stale but coherent, and this clears it either way. In a `finally` so a\n // throw partway through cannot leave an entry describing a surface that was\n // only partly mutated.\n if (context) invalidateRegistryCache(context);\n }\n}\n","import { z } from \"zod\";\nimport type {\n FunctionRegistryEntry,\n RegistryResult,\n} from \"../../types/registry\";\nimport { getRegistry } from \"../materialize\";\nimport { CoreCancelledSignal } from \"../../types/signals\";\nimport { canonicalInputSchema } from \"../../utils/schema-utils\";\nimport { planParameters } from \"./plan\";\nimport type { EngineContext } from \"./engine\";\nimport { firstPage, toChoice } from \"./questions\";\nimport { start as engineStart, step as engineStep } from \"./walk\";\nimport type {\n ControllerChoice,\n ControllerParameterDescription,\n ControllerMethodDescription,\n ControllerMethodSummary,\n Controller,\n} from \"./types\";\nimport type { SdkInternals } from \"../types\";\n\n/**\n * What the driver needs of a built SDK: one of two ways to reach a registry.\n *\n * The registry is read with the free {@link getRegistry}, which finds it on the\n * SDK's context and falls back to a surfaced `getRegistry()` for a legacy\n * stack-built SDK. So demanding the surfaced method alone is wrong: a bare tool\n * SDK does not surface one, and it cannot always add `getRegistryPlugin`\n * either, because a head bundling its own kitcore copy would collide with it on\n * the shared `kitcore/getRegistry` id.\n *\n * A union, because those really are two different shapes. `SdkInternals` is\n * what every `createSdk` result carries, and the structural branch is the\n * legacy one. Anything else can never back a controller, and saying so here\n * beats an internal registry error on the caller's first `listMethods()`.\n *\n * The context branch is `SdkInternals`, which declares the `[CONTEXT]` symbol\n * materialization actually writes. So this checks the real thing rather than a\n * correlated one.\n */\nexport type ControllerSdk =\n | SdkInternals\n | { getRegistry: (options?: { package?: string }) => RegistryResult };\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 // Read per-field hints from the canonical variant so they match the planned\n // parameters and the generated docs; a raw union has no top-level properties.\n const inputProperties = toJsonSchema(canonicalInputSchema(entry.inputSchema))\n ?.properties as Record<string, Record<string, unknown>> | undefined;\n const parameters: Record<string, ControllerParameterDescription> = {};\n for (const spec of planParameters(entry).parameters) {\n const dynamic =\n spec.resolver?.type === \"dynamic\" ? spec.resolver : undefined;\n parameters[spec.name] = {\n required: spec.required,\n dynamic: Boolean(dynamic),\n ...(dynamic?.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 the registry\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 = getRegistry(sdk).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 // A method that owns its input validation (`skipInputValidation`, e.g.\n // fetch) must not be re-validated by the controller's final `safeParse`;\n // drop the schema so `finalize` returns the resolved input untouched.\n // Planning still reads `entry.inputSchema` directly, so parameters are\n // unaffected.\n schema: entry.skipInputValidation ? undefined : 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: getRegistry(sdk).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 const dynamic =\n spec?.resolver?.type === \"dynamic\" ? spec.resolver : undefined;\n if (!dynamic) 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 dynamic.getContext?.({ input });\n const page = await firstPage(\n dynamic.listItems({ input, context, search, cursor }),\n );\n const config = dynamic.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): value is CoreSignal {\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\n/**\n * Cross-package-safe check for {@link CoreCancelledSignal}. Keys on the\n * signal brand + `code` rather than `instanceof`, so it recognizes a\n * cancel signal raised by a different copy of kitcore (e.g. one bundled\n * into a head vs. one installed standalone).\n */\nexport function isCoreCancelledSignal(\n value: unknown,\n): value is CoreCancelledSignal {\n return isCoreSignal(value) && value.code === \"CANCELLED\";\n}\n","import { z } from \"zod\";\nimport type { FunctionRegistryEntry } from \"../../types/registry\";\nimport { objectShapeOf, unwrapSchema } from \"../../utils/schema-utils\";\nimport type { BoundResolver, ResolverRequirement } 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 /** The field's display label (an object field's `label`, e.g. the title an\n * upstream API supplies); questions use it over the raw key when present. */\n label?: string;\n valueType?: string;\n staticChoices?: ControllerChoice[];\n resolver?: BoundResolver;\n requires: readonly ResolverRequirement[];\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/** 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 // A record is an open-keyed object; coerce a typed answer as JSON like a\n // plain object rather than leaving it a string that fails validation.\n if (inner instanceof z.ZodRecord) 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/** Order specs so each parameter's `requires` precede it, with the SCAN ORDER\n * of `specs` dominating: each step places the first spec (in `specs` order)\n * that is ready, rescanning from the top after every placement. Dependencies\n * only defer a parameter; they never promote a later one past an earlier one\n * that is (or becomes) ready — a queue-based sort would instead emit\n * dependency-distance \"waves\" (asking `connection` before `action` on\n * runAction). Members of a dependency cycle (which shouldn't exist) never\n * become ready; they are appended at the end, between themselves in scan\n * order. */\nfunction topoOrder(specs: Leaf[]): Leaf[] {\n const byName = new Map(specs.map((s) => [s.name, s]));\n const placed = new Set<string>();\n const ordered: Leaf[] = [];\n // An absolute path orders top-level params only when it names one, i.e. a\n // single segment. A deeper path (`[\"input\", \"owner\"]`) points at a field that\n // resolves during the walk, well after this sort, so it cannot constrain the\n // top-level order and is ignored here rather than deadlocking it.\n const topLevelNameOf = (r: Leaf[\"requires\"][number]): string | undefined =>\n typeof r === \"string\"\n ? r\n : r.length === 1 && typeof r[0] === \"string\"\n ? r[0]\n : undefined;\n const isReady = (spec: Leaf): boolean =>\n spec.requires.every((r) => {\n const name = topLevelNameOf(r);\n return name === undefined || !byName.has(name) || placed.has(name);\n });\n for (;;) {\n const next = specs.find((s) => !placed.has(s.name) && isReady(s));\n if (!next) break;\n ordered.push(next);\n placed.add(next.name);\n }\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 = objectShapeOf(entry.inputSchema);\n const resolvers = entry.resolvers ?? {};\n // Off-schema bound CONSTANTS join the plan: a pinned value with no public\n // parameter (e.g. `actionType: \"read\"` on trigger methods). They settle in\n // the walk (satisfying dependents' `requireParameters`) and the final\n // schema parse strips them from the output. Other off-schema resolver kinds\n // stay out: they would prompt for a value the schema then discards.\n const names = shape\n ? [\n ...Object.keys(shape),\n ...Object.keys(resolvers).filter(\n (name) => !(name in shape) && resolvers[name].type === \"constant\",\n ),\n ]\n : Object.keys(resolvers);\n\n const specs: Leaf[] = names.map((name) => {\n const field = shape?.[name];\n const { inner, required } = field\n ? unwrapSchema(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 // Scan priority: off-schema constants, then required parameters, then\n // optionals — declaration order within each group, mirroring the walk's\n // required-first rule inside objects. A consumer answers what the method\n // needs before being offered what it doesn't. The constants go first\n // because they auto-settle without a question, and scanning them last\n // would defer every parameter that requires one (`action` requiring the\n // pinned `actionType`) past unrelated optionals.\n const declared = shape ? specs.filter((s) => s.name in shape) : specs;\n const scan = [\n ...(shape ? specs.filter((s) => !(s.name in shape)) : []),\n ...declared.filter((s) => s.required),\n ...declared.filter((s) => !s.required),\n ];\n return { parameters: topoOrder(scan) };\n}\n","import type { z } from \"zod\";\nimport type { SdkPage } from \"../../types/pagination\";\nimport type {\n BoundField,\n BoundObjectResolver,\n BoundResolver,\n Field,\n ResolverRef,\n} from \"../types\";\nimport type { Leaf } from \"./plan\";\nimport type {\n ControllerPagination,\n ControllerListingPage,\n ControllerListingPosition,\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), next/previous page moves, retry of a failed fetch,\n * `object` resolvers (static `properties`, dynamic `getProperties`, `{ ref }`\n * into `definitions`, nesting), `array` resolvers (min/max, the add/done\n * `collection` decision, items of any kind), and open-keyed record resolvers\n * (`object` with `additionalKeys`: a static/constant key prompt, min/max\n * entries, values resolved as ordinary leaves).\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\nexport function 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\n/** Own-property write that can never reach the prototype chain: a plain\n * `node[key] = v` with `key` of `__proto__` reassigns the prototype (or is\n * swallowed by the accessor) instead of creating an own entry, and\n * `constructor`/`prototype` shadow inherited members. `defineProperty` always\n * writes an own data property, so the tree write is safe for any key. (A record\n * key naming a prototype member is separately rejected upstream to keep it out\n * of the emitted value, a different concern than this write.) */\nfunction defineOwn(\n node: Record<string, unknown>,\n key: string,\n value: unknown,\n): void {\n Object.defineProperty(node, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n\nexport function 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 // Read the own property only (a plain `node[seg]` would surface the\n // prototype for a `__proto__` segment); create a fresh container otherwise.\n const existing = Object.prototype.hasOwnProperty.call(node, seg)\n ? node[seg]\n : undefined;\n if (existing != null && typeof existing === \"object\") {\n node = existing as Record<string, unknown>;\n } else {\n const child: Record<string, unknown> = {};\n defineOwn(node, seg, child);\n node = child;\n }\n }\n defineOwn(node, path[path.length - 1] as string, value);\n}\n\nconst SAFE_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** A path's key: the `settled` set's identity token AND its human-readable form\n * in messages — one format, so it never needs a lossy display twin. Unambiguous\n * (distinct paths never collide) yet readable, shaped like a JS accessor: a\n * plain-identifier segment joins with `.`, a number is `[n]`, anything else (a\n * record key with a `.`, an empty or special string) is bracketed as its\n * JSON-quoted form. So `[\"inputs\",\"a.b.js\"]`-style aliasing can't arise: bare\n * segments are `.`-delimited identifiers and bracketed ones are self-delimiting\n * JSON strings. `inputs.channel`, `records[0].name`, `files[\"a.b.js\"]`. */\nexport const pathToKey = (path: ControllerPath): string => {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else if (SAFE_SEGMENT.test(segment))\n out += out === \"\" ? segment : `.${segment}`;\n else out += `[${JSON.stringify(segment)}]`;\n }\n return out;\n};\n\n/** Whether the engine is done with the position at `path`. */\nexport function isSettled(\n state: ControllerState,\n path: ControllerPath,\n): boolean {\n return state.settled.includes(pathToKey(path));\n}\n\n/** Record a key in the settled set (idempotent): a path's key, or an\n * out-of-tree marker like the optionals gate's. */\nexport function remember(state: ControllerState, k: string): void {\n if (!state.settled.includes(k)) state.settled.push(k);\n}\n\n/** Mark the position at `path` done (idempotent). */\nexport function settle(state: ControllerState, path: ControllerPath): void {\n remember(state, pathToKey(path));\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. */\nexport function 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). Dispatched on `valueType`, so a scalar leaf never parses its answer as\n * JSON; only `object`/`array` leaves do. A parse that fails keeps the raw string\n * so the final `safeParse` reports a real message rather than swallowing it. */\nexport function 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 if (leaf.valueType === \"object\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return raw;\n }\n }\n return raw;\n }\n if (leaf.valueType === \"array\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return raw;\n }\n }\n // A non-JSON free-text array answer stays a string so final validation\n // fails loudly. A text-CLI convention like comma-splitting belongs to the\n // host that owns its input format, not this host-agnostic engine.\n return raw;\n }\n return raw;\n}\n\n/** Run the resolver's `validate` against a chosen/typed value. Returns an\n * error message when invalid, or null when valid / no validator. Recomputes\n * `getContext` so `validate` sees the same `context` the prompt did. May\n * throw (a fetching validate can fail); the caller turns that into a `failed`\n * result rather than a rejection. */\nexport async function validationError(\n leaf: Leaf,\n value: unknown,\n state: ControllerState,\n): Promise<string | null> {\n if (leaf.resolver?.type !== \"dynamic\") return null;\n const validate = leaf.resolver.validate;\n if (!validate) return null;\n const context = await resolveContext(leaf, state.resolved);\n const verdict = await validate({\n value,\n input: mergeInput(state.resolved, leaf.extraInput),\n context,\n });\n if (verdict === true) return null;\n return typeof verdict === \"string\" ? verdict : `${leaf.name}: invalid value`;\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 label: field.label,\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: BoundObjectResolver,\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 resolver kinds the walk settles WITHOUT asking (see `advance`'s\n * auto-settle branches): a constant pins its value, an info leaf is\n * display-only. The single source of truth the gates consult, so gate\n * triggering/counting can't drift from what `advance` actually asks. */\nexport function autoSettles(resolver: BoundResolver): boolean {\n return resolver.type === \"constant\" || resolver.type === \"info\";\n}\n\n/** Merge a leaf's ref-supplied `input` over the running input. */\nexport function 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). */\nexport async 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), array items\n * (numeric segments → the array's item resolver), and record entries (a string\n * segment that isn't a fixed field but sits under an `additionalKeys` object →\n * the record's value resolver, symmetric to the array-item case). Resolving a\n * record value here is what lets its answer flow through the normal leaf path\n * (refine, validate, coerce) rather than a bespoke record-value handler. */\nexport async 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 = boundLeaf(\n \"\",\n leaf.resolver.items,\n leaf.resolver.definitions,\n leaf.resolver.itemValueType,\n );\n } else {\n const parent = leaf;\n const found = children.find((c) => c.name === seg);\n if (found) {\n leaf = found;\n } else if (\n parent?.resolver?.type === \"object\" &&\n parent.resolver.additionalKeys\n ) {\n const ak = parent.resolver.additionalKeys;\n leaf = boundLeaf(\n String(seg),\n ak.values,\n parent.resolver.definitions,\n ak.valueValueType,\n );\n } else {\n return undefined;\n }\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/** Turn a bound resolver (or a `{ ref }` into `definitions`) into a {@link Leaf}\n * for an array item or a record entry's key/value. `valueType` carries the\n * element/entry value type so a free-text answer coerces (number/boolean) like a\n * top-level or object field, rather than staying a string and failing final\n * validation. */\nfunction boundLeaf(\n name: string,\n resolverOrRef: BoundResolver | ResolverRef,\n definitions: Record<string, BoundResolver> | undefined,\n valueType: string | undefined,\n): Leaf {\n if (isRef(resolverOrRef)) {\n return {\n name,\n required: true,\n resolver: definitions?.[resolverOrRef.ref],\n extraInput: resolverOrRef.input,\n valueType,\n requires: [],\n };\n }\n return {\n name,\n required: true,\n resolver: resolverOrRef,\n valueType,\n requires: [],\n };\n}\n\n/** The record (open-keyed object) at `path`: its entry bounds and the leaves its\n * keys and values resolve through. `keys` defaults to a free-text string prompt\n * when the resolver leaves it unset. */\nexport async function recordInfoAt(\n ctx: EngineContext,\n path: ControllerPath,\n resolved: Record<string, unknown>,\n): Promise<{\n min: number;\n max: number;\n keyLeaf: Leaf;\n valueLeaf: Leaf;\n fixedKeys: string[];\n}> {\n const leaf = await leafAt(ctx, path, resolved);\n const resolver = leaf?.resolver;\n if (resolver?.type !== \"object\" || !resolver.additionalKeys) {\n throw new Error(\n `expected an object resolver with additionalKeys at \"${pathToKey(path)}\"`,\n );\n }\n // `getProperties` builds a dynamic fixed-field set that only `childrenAt`\n // (author I/O) knows; combined with open keys the entry count couldn't be\n // taken from static knowledge. Disallow the combo so `fixedKeys` (static\n // `properties`) is the complete fixed set and the record loop needs no\n // per-pass fetch. Static `properties` + open keys is fine.\n if (resolver.getProperties) {\n throw new Error(\n `object resolver at \"${pathToKey(path)}\" cannot combine getProperties with additionalKeys`,\n );\n }\n const ak = resolver.additionalKeys;\n const defs = resolver.definitions;\n const keyLeaf: Leaf = ak.keys\n ? boundLeaf(\"key\", ak.keys, defs, ak.keyValueType ?? \"string\")\n : {\n name: \"key\",\n required: true,\n resolver: { type: \"static\", inputType: \"text\" },\n valueType: \"string\",\n requires: [],\n };\n const valueLeaf = boundLeaf(\"value\", ak.values, defs, ak.valueValueType);\n // A record key is the open, user-supplied name of an entry, collected as a\n // free-text prompt (it can't be a leaf in the value tree). So it must be\n // `static`: a `dynamic` key has no coherent \"pick the key\" flow, and a\n // `constant` (or `info`) key can't yield the distinct keys an open record\n // needs. Values, by contrast, resolve as normal leaves and may be `dynamic`;\n // composite (object/array) values are deferred (multi-step completion isn't\n // wired yet).\n if (keyLeaf.resolver && keyLeaf.resolver.type !== \"static\") {\n throw new Error(\n `record key resolver at \"${pathToKey(path)}\" must be a static free-text prompt, not \"${keyLeaf.resolver.type}\"`,\n );\n }\n if (\n valueLeaf.resolver?.type === \"object\" ||\n valueLeaf.resolver?.type === \"array\"\n ) {\n throw new Error(\n `record value resolver at \"${pathToKey(path)}\" must be a single value, not \"${valueLeaf.resolver.type}\"`,\n );\n }\n return {\n min: ak.minEntries ?? 0,\n max: ak.maxEntries ?? Infinity,\n keyLeaf,\n valueLeaf,\n fixedKeys: Object.keys(resolver.properties ?? {}),\n };\n}\n\n/** The array at `path`: its bounds and the item leaf (named after the array). */\nexport async 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 \"${pathToKey(path)}\"`);\n }\n return {\n min: resolver.minItems ?? 0,\n max: resolver.maxItems ?? Infinity,\n item: boundLeaf(\n String(path[path.length - 1]),\n resolver.items,\n resolver.definitions,\n resolver.itemValueType,\n ),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Fetch machinery (pre-fetch context + listing pages for dynamic resolvers). */\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. */\nexport async function resolveContext(\n leaf: Leaf,\n input: Record<string, unknown>,\n): Promise<unknown> {\n if (leaf.resolver?.type !== \"dynamic\") return undefined;\n return leaf.resolver.getContext?.({\n input: mergeInput(input, leaf.extraInput),\n });\n}\n\n/** The position a listing starts from: page one of a fresh generation, no\n * cursor, no trail. */\nexport function firstPagePosition(\n opts: { search?: string; generation?: number } = {},\n): ControllerListingPosition {\n return {\n ...(opts.search !== undefined ? { search: opts.search } : {}),\n pageCursor: null,\n previousCursors: [],\n generation: opts.generation ?? 0,\n };\n}\n\n/** Fetch exactly the page a {@link ControllerListingPosition} names. The\n * items go to the question being built; only `toPagination`'s coordinates enter\n * the state — pages accumulate host-side, never here.\n *\n * Search-mode with no term is search-first: the catalog behind a search\n * resolver is unbounded, so no fetch happens until the user provides a term.\n * The guard lives here so every path that renders from a position (initial\n * ask, page moves, retry, the rejected-pick re-ask) keeps the invariant. */\nexport async function fetchListing(\n leaf: Leaf,\n input: Record<string, unknown>,\n position: ControllerListingPosition,\n context?: unknown,\n): Promise<ControllerListingPage> {\n if (\n leaf.resolver?.type === \"dynamic\" &&\n leaf.resolver.inputType === \"search\" &&\n position.search === undefined\n ) {\n return { position, items: [] };\n }\n const page = await firstPage(\n leaf.resolver?.type === \"dynamic\"\n ? leaf.resolver.listItems({\n input: mergeInput(input, leaf.extraInput),\n context,\n search: position.search,\n cursor: position.pageCursor ?? undefined,\n })\n : undefined,\n );\n return {\n position,\n items: page.data,\n ...(page.nextCursor != null ? { nextCursor: page.nextCursor } : {}),\n };\n}\n\n/** The coordinates the state keeps from a fetched page (the items ride the\n * question instead). */\nexport function toPagination(\n page: ControllerListingPage,\n): ControllerPagination {\n return {\n position: page.position,\n ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),\n };\n}\n","import type {\n PromptConfig,\n PromptConfigChoice,\n DeprecatedPromptConfigChoice,\n} from \"../../utils/schema-utils\";\nimport type { Leaf } from \"./plan\";\nimport {\n fetchListing,\n firstPagePosition,\n mergeInput,\n resolveContext,\n toPagination,\n} from \"./engine\";\nimport type {\n ControllerAffordance,\n ControllerChoice,\n ControllerError,\n ControllerPagination,\n ControllerListingPage,\n ControllerQuestion,\n ControllerResult,\n ControllerState,\n ControllerPath,\n} from \"./types\";\n\nexport { firstPage } from \"./engine\";\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/* 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 nextPage: {\n action: \"next_page\",\n description: \"Fetch the next page of options\",\n },\n previousPage: {\n action: \"previous_page\",\n description: \"Return to the previous page of options\",\n },\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/** A shared affordance with a context-specific description. The gates all offer\n * `add`/`done` but word them differently (add an entry vs configure fields), so\n * the map stays the single source of the action identifiers and only the\n * wording is overridden — no gate re-spells the action string inline. */\nfunction affordance(\n base: ControllerAffordance,\n description: string,\n): ControllerAffordance {\n return { ...base, description };\n}\n\nfunction selectActions(\n leaf: Leaf,\n page: ControllerListingPage,\n multiple: boolean,\n): ControllerAffordance[] {\n const searchMode =\n leaf.resolver?.type === \"dynamic\" && leaf.resolver.inputType === \"search\";\n // Search-first with nothing listed yet: `search` IS the primary move, and\n // `choose` (an empty choice set) is omitted rather than offered as a menu\n // entry with nothing behind it.\n if (\n searchMode &&\n page.position.search === undefined &&\n page.items.length === 0\n ) {\n const actions: ControllerAffordance[] = multiple\n ? [AFFORDANCE.search]\n : [AFFORDANCE.search, AFFORDANCE.custom];\n if (!leaf.required) actions.push(AFFORDANCE.skip);\n return actions;\n }\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 (searchMode) actions.push(AFFORDANCE.search);\n if (page.nextCursor) actions.push(AFFORDANCE.nextPage);\n if (page.position.previousCursors.length > 0)\n actions.push(AFFORDANCE.previousPage);\n if (!leaf.required) actions.push(AFFORDANCE.skip);\n return actions;\n}\n\n/** A labeled field (an object field carrying its upstream title) renders as\n * \"Channel (required):\" / \"Channel (optional):\"; a bare parameter (no label)\n * returns undefined so the caller falls back to its own default. */\nfunction labeledMessage(leaf: Leaf): string | undefined {\n if (!leaf.label) return undefined;\n return `${leaf.label} (${leaf.required ? \"required\" : \"optional\"}):`;\n}\n\n/** Render a dynamic select question from one fetched page (choices via the\n * resolver's `prompt`, run over that page's items only). */\nexport function selectQuestion(\n leaf: Leaf,\n path: ControllerPath,\n input: Record<string, unknown>,\n page: ControllerListingPage,\n context?: unknown,\n): ControllerQuestion {\n const resolver =\n leaf.resolver?.type === \"dynamic\" ? leaf.resolver : undefined;\n const config: PromptConfig | undefined = resolver?.prompt?.({\n items: page.items,\n input: mergeInput(input, leaf.extraInput),\n context,\n });\n const multiple = config?.type === \"checkbox\";\n return {\n type: \"select\",\n path,\n // A labeled field's title beats the resolver's message: per-field\n // resolvers are shared across fields (one choices-fetcher for every\n // field), so only the leaf knows which field is being asked.\n message: labeledMessage(leaf) ?? config?.message ?? `Select ${leaf.name}:`,\n choices: (config?.choices ?? []).map(toChoice),\n ...(multiple ? { multiple: true } : {}),\n ...(config?.notes?.length ? { notes: config.notes } : {}),\n ...(page.position.search !== undefined\n ? { search: page.position.search }\n : {}),\n ...(resolver?.placeholder ? { placeholder: resolver.placeholder } : {}),\n page: {\n generation: page.position.generation,\n index: page.position.previousCursors.length,\n },\n actions: selectActions(leaf, page, 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 failed\n * position is kept in `state.pagination` so `retry` replays it. */\nexport function 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 path: state.current ?? [],\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 the pagination coordinates to\n * carry forward. */\nexport async function buildQuestion(\n leaf: Leaf,\n path: ControllerPath,\n input: Record<string, unknown>,\n): Promise<{\n question: ControllerQuestion;\n pagination?: ControllerPagination;\n}> {\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\n // prompt. (Search-mode fetches nothing yet: `fetchListing` is search-first\n // and returns the empty page until a term exists, so the host leads with a\n // term prompt. Bounded selects list eagerly so the host can type-to-filter\n // the loaded choices locally.)\n if (resolver?.type === \"dynamic\") {\n const context = await resolveContext(leaf, input);\n const page = await fetchListing(leaf, input, firstPagePosition(), context);\n return {\n question: selectQuestion(leaf, path, input, page, context),\n pagination: toPagination(page),\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 path,\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; every other kind\n // was handled above or auto-settles in the walk). `search` is an affordance,\n // not a text-input subtype, so it maps to plain text here.\n const textSource = resolver?.type === \"static\" ? resolver : undefined;\n const inputType =\n textSource?.inputType && textSource.inputType !== \"search\"\n ? textSource.inputType\n : \"text\";\n const actions: ControllerAffordance[] = [AFFORDANCE.custom];\n if (optional) actions.push(AFFORDANCE.skip);\n return {\n question: {\n type: \"input\",\n path,\n // The optional marker makes Enter-to-pass discoverable on a bare\n // parameter; a labeled field carries its marker via labeledMessage.\n message:\n labeledMessage(leaf) ??\n `Enter ${leaf.name}${optional ? \" (optional)\" : \"\"}:`,\n inputType,\n placeholder: textSource?.placeholder,\n actions,\n },\n };\n}\n\n/** The array's add/done question (the `array_items` gate). `done` is offered\n * once the count is within range (the decision is only reached at\n * `min ≤ count < max`). */\nexport function arrayItemsQuestion(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 path: t.path,\n message: `Add ${t.path[t.path.length - 1]}[${t.count}]?`,\n container: \"array\",\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/** A record's add-another-entry decision (the `record_entries` gate). `add`\n * collects one more key/value entry; `done` (offered once `count ≥ min`)\n * finishes the record. */\nexport function recordEntriesQuestion(t: {\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n}): ControllerQuestion {\n const actions: ControllerAffordance[] = [\n affordance(AFFORDANCE.add, \"Add another entry\"),\n ];\n if (t.count >= t.min) {\n actions.push(affordance(AFFORDANCE.done, \"Finish the entries\"));\n }\n return {\n type: \"collection\",\n path: t.path,\n message: `Add another ${t.path[t.path.length - 1]} entry? (${t.count} so far)`,\n container: \"record\",\n count: t.count,\n min: t.min,\n ...(Number.isFinite(t.max) ? { max: t.max } : {}),\n actions,\n };\n}\n\n/** The `object_optional` gate: one \"provide this optional object at all?\" ask,\n * fired BEFORE the object's fields are fetched so declining costs no I/O. Same\n * question type and add/done actions as the collection loops, worded for the\n * whole-object decision. */\nexport function objectOptionalQuestion(\n path: ControllerPath,\n): ControllerQuestion {\n return {\n type: \"collection\",\n path,\n message: `Add ${path[path.length - 1]}?`,\n container: \"object\",\n actions: [\n affordance(AFFORDANCE.add, \"Provide values for these fields\"),\n affordance(AFFORDANCE.done, \"Skip these fields\"),\n ],\n };\n}\n\n/** The `object_optional_properties` gate: the one bulk ask over an object's\n * remaining optional fields. Required fields were asked individually; the\n * optionals are offered as a batch (`add` walks them, `done` finishes the\n * object). */\nexport function objectOptionalPropertiesQuestion(\n path: ControllerPath,\n pending: Leaf[],\n): ControllerQuestion {\n return {\n type: \"collection\",\n path,\n // The prompt and its context ride separately so a host renders the info\n // line above the confirm without composing any text of its own.\n message: \"Would you like to configure optional fields?\",\n description: `There are ${pending.length} optional field(s) available.`,\n container: \"object\",\n // The gated fields' projection, so a smart host can show WHAT `add` would\n // walk (or render a form section) instead of a blind yes/no.\n fields: pending.map((leaf) => ({\n key: leaf.name,\n ...(leaf.label ? { label: leaf.label } : {}),\n ...(leaf.valueType ? { valueType: leaf.valueType } : {}),\n })),\n actions: [\n affordance(AFFORDANCE.add, \"Configure the optional fields\"),\n affordance(AFFORDANCE.done, \"Skip the optional fields\"),\n ],\n };\n}\n","import type { Leaf } from \"./plan\";\nimport {\n arrayInfoAt,\n autoSettles,\n childrenAt,\n clone,\n coerce,\n fetchListing,\n firstPagePosition,\n getAtPath,\n isSettled,\n leafAt,\n mergeInput,\n pathToKey,\n recordInfoAt,\n remember,\n resolveContext,\n setAtPath,\n settle,\n toPagination,\n validationError,\n type EngineContext,\n} from \"./engine\";\nimport {\n buildQuestion,\n arrayItemsQuestion,\n failedResult,\n objectOptionalQuestion,\n objectOptionalPropertiesQuestion,\n recordEntriesQuestion,\n selectQuestion,\n} from \"./questions\";\nimport type {\n ControllerAction,\n ControllerIssue,\n ControllerPagination,\n ControllerListingPosition,\n ControllerResult,\n ControllerState,\n ControllerPath,\n} from \"./types\";\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, an array's add/done\n * decision, or an optional object's opt-in gate. */\ntype Target =\n | { type: \"leaf\"; path: ControllerPath; leaf: Leaf }\n | {\n type: \"array_items\";\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n }\n | { type: \"object_optional\"; path: ControllerPath; leaf: Leaf }\n | {\n type: \"object_optional_properties\";\n path: ControllerPath;\n pending: Leaf[];\n }\n // A record's add/done decision (open-keyed object entries).\n | {\n type: \"record_entries\";\n path: ControllerPath;\n count: number;\n min: number;\n max: number;\n }\n // Force one more record entry (below `minEntries`): ask its key directly.\n | { type: \"record_key\"; path: ControllerPath; leaf: Leaf };\n\n/** The settled-set key that records \"the optionals gate for the object at\n * `path` was accepted\" (so it isn't re-asked). `?` can't appear in a field\n * key, so the marker can't collide with a real child path. */\nconst optionalsMarker = (path: ControllerPath): string =>\n `${pathToKey(path)}?optionals`;\n\n/** Keys a user must never set as a record entry: they name prototype members,\n * so emitting them into the resolved value would let a downstream consumer that\n * merges via `[[Set]]` (`Object.assign`, a naive `for..in`) pollute a prototype.\n * Rejected at the record-key boundary, the only user-supplied key source.\n * `setAtPath`'s own-property writes separately keep the resolution tree safe. */\nconst UNSAFE_RECORD_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\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). A\n // settled item is already complete — e.g. its optionals gate was declined —\n // so descending into it would re-offer the same question forever.\n if (len > 0 && (itemType === \"object\" || itemType === \"array\")) {\n const itemPath = [...path, len - 1];\n if (!isSettled(state, itemPath)) {\n const inner = await findNext(ctx, state, itemPath);\n if (inner) return inner;\n }\n }\n if (len < min) return descendItem(ctx, state, path, len, item);\n if (len < max) return { type: \"array_items\", path, count: len, min, max };\n settle(state, path); // at max\n return null;\n}\n\n/** Walk the record at `path` (an object resolver's open `additionalKeys`\n * entries): force entries below `minEntries` by asking a key, offer add/done in\n * range, auto-finish at `maxEntries`. A non-interactive caller takes the\n * provided object as-is. Only complete entries are ever present here — the\n * key→value collection happens inside `step`, not across `findNext` passes. */\nasync function findInRecord(\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 object as-is (validation checks bounds)\n return null;\n }\n const { min, max, keyLeaf, fixedKeys } = await recordInfoAt(\n ctx,\n path,\n state.resolved,\n );\n const container = getAtPath(state.resolved, path) as Record<string, unknown>;\n // Count only the open entries, not any fixed `properties` sharing the object.\n // `fixedKeys` comes from static knowledge, so no per-pass field fetch.\n const fixed = new Set(fixedKeys);\n const count = Object.keys(container).filter((k) => !fixed.has(k)).length;\n if (count < min) return { type: \"record_key\", path, leaf: keyLeaf };\n if (count < max) return { type: \"record_entries\", path, count, 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 slot type, 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 slotType = seedItemSlot(state, itemPath, item);\n if (slotType === \"object\") return findNext(ctx, state, itemPath);\n if (slotType === \"array\") return findInArray(ctx, state, itemPath);\n return { type: \"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, an array decision, or an object gate. Inside an object\n * (non-root), fields are walked required-first, and the remaining optionals\n * are offered as one batch (the optionals gate) rather than field by field. */\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 const children = await childrenAt(ctx, path, state.resolved);\n const inObject = path.length > 0;\n // Required-first inside an object (stable within each group); the root\n // keeps the plan's topo order.\n const ordered = inObject\n ? [\n ...children.filter((c) => c.required),\n ...children.filter((c) => !c.required),\n ]\n : children;\n // Only fields the walk would actually ask matter to the gates: fields that\n // auto-settle (constant, info) and resolver-less optionals (interactive\n // omits them) never trigger, count toward, or hold up a gate.\n const asksUser = (c: Leaf): boolean =>\n c.resolver ? !autoSettles(c.resolver) : c.required;\n const isPendingChild = (c: Leaf): boolean =>\n container[c.name] === undefined && !isSettled(state, [...path, c.name]);\n const hasAskableRequired = children.some((c) => c.required && asksUser(c));\n for (const leaf of ordered) {\n const childPath = [...path, leaf.name];\n // Defer any child — leaf OR composite — until the siblings it requires are\n // DONE: valued, or settled without a value (a no-auth app's connection\n // auto-resolves { resolvedValue: undefined }; the dependent proceeds with\n // that key absent). A later pass revisits once the dependency lands.\n // Top-level params are already topo-ordered\n // (planParameters), but nested object/array fields are walked in\n // declaration order, so the gate must run before descending into them too,\n // not just on the leaf branch. A nested field's requirement may also name\n // a TOP-LEVEL parameter (a choices fetcher needing `app`), so the root's\n // resolved/settled state satisfies it too.\n if (\n !leaf.requires.every((r) => {\n // An absolute path names exactly one place, so there is nothing to\n // disambiguate: read it and settle-check it where it actually lives.\n // Any settled ANCESTOR counts too. Declining an optional object settles\n // the object, not the leaf inside it, so checking only the full path\n // would defer the dependent on every pass and the walk would end with\n // nothing asked. The bare branch below has always had this via its\n // container check; a path has to say it explicitly.\n if (typeof r !== \"string\") {\n if (getAtPath(state.resolved, [...r]) !== undefined) return true;\n return r.some((_, index) => isSettled(state, r.slice(0, index + 1)));\n }\n return (\n container[r] !== undefined ||\n getAtPath(state.resolved, [r]) !== undefined ||\n isSettled(state, [...path, r]) ||\n isSettled(state, [r])\n );\n })\n ) {\n continue;\n }\n // The optionals gate: once an object's required fields are ALL done, the\n // first still-askable optional field surfaces ONE batch decision instead\n // of a prompt per field. Never while a required field is pending — even\n // one deferred on unmet requires — since declining the gate would silently\n // drop its ask. Only for objects with askable required fields: an\n // all-optional object's opt-in gate already asked for this consent (and\n // required constants don't count; they settle themselves). Never inside an\n // array item: the user opted in at the array's add question, so its\n // optional fields are asked directly rather than behind a second consent.\n const inArrayItem = path.some((segment) => typeof segment === \"number\");\n if (\n inObject &&\n !inArrayItem &&\n state.interactive &&\n hasAskableRequired &&\n !leaf.required &&\n asksUser(leaf) &&\n isPendingChild(leaf) &&\n !state.settled.includes(optionalsMarker(path)) &&\n !children.some((c) => c.required && asksUser(c) && isPendingChild(c))\n ) {\n const pending = ordered.filter(\n (c) => !c.required && asksUser(c) && isPendingChild(c),\n );\n return { type: \"object_optional_properties\", path, pending };\n }\n if (leaf.resolver?.type === \"object\") {\n // Settled means the walk is done with it: the opt-in gate declined it\n // (valueless) or the optionals gate finished it (valued).\n if (isSettled(state, childPath)) continue;\n if (getAtPath(state.resolved, childPath) == null) {\n // No opt-in gate inside an array item (the same rule that suppresses\n // the optionals gate there): the item's fields are walked directly,\n // and skipping them all still omits the container (below).\n if (!leaf.required && !inArrayItem) {\n // Optional container with nothing provided: interactive asks the\n // one-time opt-in gate; headless omits it. Either way the field\n // fetch (`getProperties`) never runs for a declined container.\n if (!state.interactive) {\n settle(state, childPath);\n continue;\n }\n return { type: \"object_optional\", path: childPath, leaf };\n }\n setAtPath(state.resolved, childPath, {});\n }\n // A child object's own open-keyed entries are collected by the recursive\n // `findNext(childPath)` itself (node-level, below), not here — so an object\n // reached any other way (an array item, an object-typed record value) gets\n // them too, not just a parent's fixed child.\n const inner = await findNext(ctx, state, childPath);\n if (inner) return inner;\n // An OPTIONAL container that FINISHES the walk empty is omitted, the\n // same as declining its gate: accepting \"Add inputs?\" and then skipping\n // every field means no inputs, not `inputs: {}`. A null\n // walk result alone is not \"finished\" — every child may just be\n // deferred on unmet requires — so the omission also demands no child be\n // pending; a deferred container stays in place, unsettled, and is\n // revisited once its dependency lands.\n if (!leaf.required) {\n const value = getAtPath(state.resolved, childPath);\n if (\n value !== null &&\n typeof value === \"object\" &&\n Object.keys(value as Record<string, unknown>).length === 0\n ) {\n const grandchildren = await childrenAt(\n ctx,\n childPath,\n state.resolved,\n );\n const pending = grandchildren.some(\n (c) =>\n (value as Record<string, unknown>)[c.name] === undefined &&\n !isSettled(state, [...childPath, c.name]),\n );\n if (!pending) {\n delete container[leaf.name];\n settle(state, childPath);\n }\n }\n }\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 { type: \"leaf\", path: childPath, leaf };\n }\n // Open-keyed entries (an `additionalKeys` object) resolve after this node's\n // fixed children: force entries below min, then offer add/done. Handled at\n // the node itself, keyed off its own resolver, so it fires wherever `findNext`\n // enters an object — a parent's child, an array item, or an object-typed\n // record value — not only in the parent loop above. `leafAt` is the same\n // resolver lookup `recordInfoAt` does and returns undefined for the root, so\n // the root (never `additionalKeys`) skips it.\n //\n // Known limitation (only reachable by a shape nothing ships yet): if this\n // object also has fixed OPTIONAL properties, declining their gate settles the\n // path, so `isSettled` short-circuits the record phase. Fixing that needs the\n // object's phases (optionals vs. open entries) to settle independently.\n if (inObject && !isSettled(state, path)) {\n const self = await leafAt(ctx, path, state.resolved);\n if (self?.resolver?.type === \"object\" && self.resolver.additionalKeys) {\n const rec = await findInRecord(ctx, state, path);\n if (rec) return rec;\n }\n }\n return null;\n}\n\n/** Build the question for a leaf and set it as the outstanding one, or, when the\n * fetch throws, a `failed` result whose `retry` replays the initial first-page\n * fetch. `gate` marks a non-value question (a record key) so `step` routes the\n * answer accordingly; omitting it clears any gate for an ordinary value leaf. */\nasync function askLeaf(\n state: ControllerState,\n path: ControllerPath,\n leaf: Leaf,\n opts: { gate?: ControllerState[\"gate\"]; error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n state.current = path;\n if (opts.gate) state.gate = opts.gate;\n else delete state.gate;\n try {\n const { question, pagination } = await buildQuestion(\n leaf,\n path,\n state.resolved,\n );\n state.pagination = pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question,\n ...(opts.error ? { error: opts.error } : {}),\n },\n };\n } catch (error) {\n state.pagination = failedPagination(undefined, firstPagePosition());\n return failedResult(state, leaf.name, error);\n }\n}\n\n/** Ask for a record entry's key: an `askLeaf` under the `record_key` gate, so\n * `step` routes the answer to key-collection rather than a tree write. */\nasync function askRecordKey(\n state: ControllerState,\n path: ControllerPath,\n keyLeaf: Leaf,\n opts: { error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n return askLeaf(state, path, keyLeaf, { gate: \"record_key\", ...opts });\n}\n\n/** Auto-resolve a fresh leaf WITHOUT asking, per the mode-independent contract:\n * a constant pins its value, an info leaf resolves nothing, and a dynamic\n * resolver's `tryResolveWithoutPrompt` may settle it (a configured default, a\n * no-auth app's absent connection). Returns true when it settled the leaf, so\n * the caller advances instead of prompting. `PromptConfig.validate` is\n * intentionally NOT run here: the resolver produced the value itself, so it is\n * not a user answer to re-validate. Every fresh-leaf ask (top-level walk, added\n * array item, record value) runs this first so they honor the same gates. */\nasync function autoResolveLeaf(\n state: ControllerState,\n path: ControllerPath,\n leaf: Leaf,\n): Promise<boolean> {\n const resolver = leaf.resolver;\n if (resolver && autoSettles(resolver)) {\n if (resolver.type === \"constant\")\n setAtPath(state.resolved, path, resolver.value);\n settle(state, path);\n return true;\n }\n const auto =\n resolver?.type === \"dynamic\"\n ? await resolver.tryResolveWithoutPrompt?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n })\n : undefined;\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 it isn't re-asked.\n if (auto.resolvedValue !== undefined)\n setAtPath(state.resolved, path, auto.resolvedValue);\n settle(state, path);\n return true;\n }\n return false;\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.gate;\n delete state.pagination;\n return { state, result: finalize(ctx, state.resolved) };\n }\n if (target.type === \"array_items\") {\n state.current = target.path;\n state.gate = \"array_items\";\n delete state.pagination;\n return {\n state,\n result: { status: \"ask\", question: arrayItemsQuestion(target) },\n };\n }\n if (target.type === \"object_optional\") {\n state.current = target.path;\n state.gate = \"object_optional\";\n delete state.pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question: objectOptionalQuestion(target.path),\n },\n };\n }\n if (target.type === \"object_optional_properties\") {\n state.current = target.path;\n state.gate = \"object_optional_properties\";\n delete state.pagination;\n return {\n state,\n result: {\n status: \"ask\",\n question: objectOptionalPropertiesQuestion(\n target.path,\n target.pending,\n ),\n },\n };\n }\n if (target.type === \"record_entries\") {\n state.current = target.path;\n state.gate = \"record_entries\";\n delete state.pagination;\n return {\n state,\n result: { status: \"ask\", question: recordEntriesQuestion(target) },\n };\n }\n if (target.type === \"record_key\") {\n return askRecordKey(state, target.path, target.leaf);\n }\n const { path, leaf } = target;\n\n // Auto-settle / skip-check (both modes, any depth): a constant or info leaf,\n // or a dynamic resolver that can answer itself, settles without a question.\n if (await autoResolveLeaf(state, path, leaf)) continue;\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, then advance to the first interaction (or\n * completion). A provided parameter is the caller saying \"use exactly this\n * value\": it settles up front, whatever its resolver type, so resolution only\n * fills the holes the caller left and never runs a provided parameter's\n * resolver. Scalars would be done by presence anyway; the settle matters for\n * composites: the walk must not descend into a provided object or array (no\n * field fetch, no optionals gate, no add/done loop, no nested constant\n * injection). Constants for unprovided parameters still auto-settle inside\n * `advance`. */\nexport async function start(\n ctx: EngineContext,\n input: Record<string, unknown> = {},\n interactive = true,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const state: ControllerState = {\n method: ctx.method,\n resolved: { ...input },\n settled: [],\n interactive,\n };\n for (const [name, value] of Object.entries(input)) {\n if (value !== undefined) settle(state, [name]);\n }\n return advance(ctx, state);\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.gate;\n delete state.pagination;\n return { state, result: { status: \"cancelled\" } };\n }\n\n // Record key collection: the answer is an entry key that opens a value slot,\n // not a write at `state.current`, so handle it before the generic leaf path.\n // The value that follows is an ordinary leaf and flows through the code below.\n if (state.gate === \"record_key\") {\n return stepRecordKey(ctx, state, action);\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 // `state.current` is engine-set to a resolvable path (a leaf, an array item,\n // or a record value), so a missing leaf is a broken invariant, not host\n // input — fail loud rather than writing the raw answer straight to the tree.\n if (!leaf) {\n throw new Error(\n `no resolver for the outstanding question at \"${pathToKey(path)}\"`,\n );\n }\n\n // Stay-on-parameter actions: refine the listing and re-ask.\n if (\n action.type === \"search\" ||\n action.type === \"next_page\" ||\n action.type === \"previous_page\" ||\n action.type === \"retry\"\n ) {\n return refine(ctx, state, leaf, path, action);\n }\n\n // Container decision actions: which decision is outstanding is recorded on\n // the state (`state.gate`), never inferred from value presence or resolver\n // shape.\n if (action.type === \"add\" || action.type === \"done\") {\n const gate = state.gate;\n // A container decision without an outstanding gate is a host bug (e.g.\n // answering a leaf question with add); fail loud instead of silently\n // settling the leaf or dying inside the array machinery.\n if (!gate) {\n throw new Error(\n `action \"${action.type}\" is not supported here: no container decision is outstanding`,\n );\n }\n delete state.current;\n delete state.gate;\n delete state.pagination;\n if (action.type === \"done\") {\n // Array: finish (validation checks min). Entry gate: decline the whole\n // container, valueless, so the walk never fetches its fields. Optionals\n // gate: finish the (valued) object, skipping its remaining optionals.\n settle(state, path);\n return advance(ctx, state);\n }\n if (gate === \"object_optional\") {\n // Accepted: seed the container and let the walk descend into its fields.\n setAtPath(state.resolved, path, {});\n return advance(ctx, state);\n }\n if (gate === \"object_optional_properties\") {\n // Accepted: remember it so the walk asks the optional fields instead of\n // re-offering the gate.\n remember(state, optionalsMarker(path));\n return advance(ctx, state);\n }\n if (gate === \"record_entries\") {\n // Accepted: start a new entry by asking its key.\n const { keyLeaf } = await recordInfoAt(ctx, path, state.resolved);\n return askRecordKey(state, path, keyLeaf);\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: auto-resolve if the contract allows (a constant/auto item\n // settles silently), else ask it. Composite item: seed its slot and let the\n // walk (advance → findNext) descend into it.\n if (seedItemSlot(state, itemPath, item) === \"leaf\") {\n if (await autoResolveLeaf(state, itemPath, item))\n return advance(ctx, state);\n return askLeaf(state, itemPath, item);\n }\n return advance(ctx, state);\n }\n\n // The mirror of the gateless add/done guard: a gate question accepts only\n // add/done. A value answer here would overwrite the container with a scalar\n // (silent until the final parse rejects it); a skip would settle the\n // container by accident.\n if (state.gate) {\n throw new Error(\n `action \"${action.type}\" is not supported here: a container decision (${state.gate}) is outstanding`,\n );\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 let error: string | null;\n try {\n error = await validationError(leaf, action.value, state);\n } catch (thrown) {\n // A fetching validate failed (e.g. network), which is a lookup failure,\n // not a rejection: offer retry/cancel instead of re-asking with a\n // misleading \"invalid value\" message.\n return failedResult(state, leaf.name, thrown);\n }\n if (error) {\n // A dynamic select re-fetches its current page (`resolveContext` and the\n // fetch both hit the resolver's sources, so both degrade to failed/retry\n // rather than escaping step() as a raw throw); a plain leaf just re-asks.\n if (state.pagination && leaf.resolver?.type === \"dynamic\") {\n return renderPageAt(state, leaf, path, state.pagination.position, {\n error,\n });\n }\n return askLeaf(state, path, leaf, { error });\n }\n setAtPath(state.resolved, path, coerce(leaf, action.value)); // 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(\n `action \"${(action as ControllerAction).type}\" is not supported here`,\n );\n }\n\n delete state.current;\n delete state.pagination;\n return advance(ctx, state);\n}\n\n/** Fetch and render the page at `position` for a dynamic leaf's select, keeping\n * its coordinates on the state; on fetch failure, record the position to replay\n * and return a `failed` result. `error` decorates the rendered question (the\n * re-ask after a rejected pick). The state holds only the position, so the page\n * is re-fetched statelessly rather than rebuilt — a search-mode select keeps the\n * results and term the answer came from instead of resetting to search-first. */\nasync function renderPageAt(\n state: ControllerState,\n leaf: Leaf,\n path: ControllerPath,\n position: ControllerListingPosition,\n opts: { error?: string } = {},\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n try {\n const context = await resolveContext(leaf, state.resolved);\n const page = await fetchListing(leaf, state.resolved, position, context);\n state.pagination = toPagination(page);\n return {\n state,\n result: {\n status: \"ask\",\n question: selectQuestion(leaf, path, state.resolved, page, context),\n ...(opts.error ? { error: opts.error } : {}),\n },\n };\n } catch (error) {\n state.pagination = failedPagination(state.pagination, position);\n return failedResult(state, leaf.name, error);\n }\n}\n\n/** Handle the actions that stay on the current leaf: `search` (exact-match\n * short-circuit, else restart the listing by term under a new generation),\n * `next_page`/`previous_page` (move the one-page window along the cursor\n * trail), and `retry` (replay the failed position). */\nasync function refine(\n ctx: EngineContext,\n state: ControllerState,\n leaf: Leaf,\n path: ControllerPath,\n action:\n | { type: \"search\"; term: string }\n | { type: \"next_page\" }\n | { type: \"previous_page\" }\n | { type: \"retry\" },\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const position = positionAfter(state.pagination, action);\n if (action.type === \"search\") {\n try {\n const exact =\n leaf.resolver?.type === \"dynamic\"\n ? await leaf.resolver.tryResolveFromSearch?.({\n input: mergeInput(state.resolved, leaf.extraInput),\n search: action.term,\n })\n : undefined;\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.pagination;\n return advance(ctx, state);\n }\n } catch (error) {\n // Keep the current position; `retry` replays exactly what failed.\n state.pagination = failedPagination(state.pagination, position);\n return failedResult(state, leaf.name, error);\n }\n }\n return renderPageAt(state, leaf, path, position);\n}\n\n/** Collect a record entry's key — the one bespoke record step, since a key\n * can't be a leaf in the value tree. Validate it's a non-empty, unused key,\n * then open its value at `[...path, key]` as an ordinary leaf via `askLeaf`, so\n * the value resolves through the normal machinery (refine, validate, coerce) —\n * the same path an array item takes. A `skip` abandons the in-progress entry. */\nasync function stepRecordKey(\n ctx: EngineContext,\n state: ControllerState,\n action: ControllerAction,\n): Promise<{ state: ControllerState; result: ControllerResult }> {\n const path = state.current;\n if (!path)\n throw new Error(\"record key step called with no outstanding question\");\n const { keyLeaf, valueLeaf } = await recordInfoAt(ctx, path, state.resolved);\n\n if (action.type === \"skip\") {\n delete state.gate;\n delete state.current;\n delete state.pagination;\n return advance(ctx, state);\n }\n if (action.type !== \"custom\" && action.type !== \"choose\") {\n throw new Error(\n `action \"${action.type}\" is not supported while entering a record key`,\n );\n }\n const raw = Array.isArray(action.value) ? action.value[0] : action.value;\n const entryKey = String(coerce(keyLeaf, raw));\n if (entryKey.trim() === \"\") {\n return askRecordKey(state, path, keyLeaf, { error: \"A key is required.\" });\n }\n // Keep prototype-member names out of the resolved value entirely: it flows to\n // consumers we don't control (the SDK method, serialization, the CLI's\n // `Object.assign`), and a `[[Set]]`-based merge there would pollute a\n // prototype. (`setAtPath` keeps our own tree safe; this guards what we emit.)\n if (UNSAFE_RECORD_KEYS.has(entryKey)) {\n return askRecordKey(state, path, keyLeaf, {\n error: `\"${entryKey}\" is not an allowed key.`,\n });\n }\n const container = getAtPath(state.resolved, path) as Record<string, unknown>;\n if (Object.prototype.hasOwnProperty.call(container, entryKey)) {\n return askRecordKey(state, path, keyLeaf, {\n error: `\"${entryKey}\" is already set.`,\n });\n }\n // Hand the value to the normal leaf path; the key is now carried by the path.\n // Auto-resolve it first so a constant/auto value settles without a prompt,\n // exactly as a top-level leaf or array item would.\n const valuePath = [...path, entryKey];\n if (await autoResolveLeaf(state, valuePath, valueLeaf)) {\n return advance(ctx, state);\n }\n return askLeaf(state, valuePath, valueLeaf);\n}\n\n/** The one pagination shape every fetch failure writes: the current coordinates\n * survive (position and, when known, `nextCursor`) and `retryPosition`\n * records the fetch to replay. */\nfunction failedPagination(\n pagination: ControllerPagination | undefined,\n retryPosition: ControllerListingPosition,\n): ControllerPagination {\n return {\n position: pagination?.position ?? firstPagePosition(),\n ...(pagination?.nextCursor !== undefined\n ? { nextCursor: pagination.nextCursor }\n : {}),\n retryPosition,\n };\n}\n\n/** The position a refine action moves to: `search` restarts the listing under\n * a new generation (same-term searches still refetch); `next_page` pushes the\n * current page's cursor onto the trail; `previous_page` pops it; `retry`\n * replays the failed position if one is recorded, else the current page's\n * own. */\nfunction positionAfter(\n pagination: ControllerPagination | undefined,\n action:\n | { type: \"search\"; term: string }\n | { type: \"next_page\" }\n | { type: \"previous_page\" }\n | { type: \"retry\" },\n): ControllerListingPosition {\n const current = pagination?.position ?? firstPagePosition();\n switch (action.type) {\n case \"search\":\n return firstPagePosition({\n search: action.term,\n generation: current.generation + 1,\n });\n case \"next_page\": {\n // Without a next cursor (host raced past the last page) re-fetch the\n // current page rather than fabricating one.\n if (pagination?.nextCursor == null) return current;\n return {\n ...(current.search !== undefined ? { search: current.search } : {}),\n pageCursor: pagination.nextCursor,\n previousCursors: [...current.previousCursors, current.pageCursor],\n generation: current.generation,\n };\n }\n case \"previous_page\": {\n // With an empty trail (host answered previous_page on page one) stay put.\n if (current.previousCursors.length === 0) return current;\n return {\n ...(current.search !== undefined ? { search: current.search } : {}),\n pageCursor: current.previousCursors[current.previousCursors.length - 1],\n previousCursors: current.previousCursors.slice(0, -1),\n generation: current.generation,\n };\n }\n case \"retry\":\n return pagination?.retryPosition ?? current;\n }\n}\n","import type { Plugin } from \"../types/plugin\";\nimport type { CoreOptions } from \"./core-options\";\nimport { logDeprecation } from \"./logging\";\n\n/**\n * Register kitcore-level configuration by writing the options to\n * `context.core`; the method boundary falls back to that path when no\n * `kitcore/coreOptions` configuration value exists.\n *\n * @deprecated Inject the `CoreOptions` bag under `CORE_OPTIONS_ID` via\n * `createSdk(root, { configuration })` instead. This factory logs a runtime\n * deprecation and will be removed in a release after the warning ships.\n */\nexport function createCorePlugin(\n options: CoreOptions,\n): Plugin<object, { context: { core: CoreOptions } }> {\n logDeprecation(\n \"createCorePlugin() is deprecated. Inject the options under CORE_OPTIONS_ID via createSdk's configuration instead.\",\n );\n return () => ({\n context: {\n core: options,\n },\n });\n}\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { authorizeHttpRequestPlugin } from \"./authorize-http-request\";\nimport { dispatchHttpRequestPlugin } from \"./dispatch-http-request\";\nimport { prepareHttpRequestPlugin } from \"./prepare-http-request\";\nimport { receiveHttpResponsePlugin } from \"./receive-http-response\";\nimport type { AttemptHttpRequestInput, HttpResponse } from \"./types\";\n\n/**\n * One physical attempt: prepare, authorize, dispatch, receive.\n *\n * This exists as its own stage to give the ATTEMPT scope a seam. See\n * {@link AttemptHttpRequestInput} for why the operation and the attempt are\n * different lifecycles, and why re-issuing a request has to wrap here rather\n * than around `sendHttpRequest`.\n *\n * Do not fold this back into `sendHttpRequest` to save an indirection: doing so\n * removes the only boundary below `initializeHttpRequest`, and a retry wrap\n * would then re-initialize and mint a fresh `operationId` per attempt.\n */\nexport const attemptHttpRequestPlugin = defineMethod({\n name: \"attemptHttpRequest\",\n namespace: \"kitcore\",\n imports: [\n declareDefault({ plugin: prepareHttpRequestPlugin }),\n declareDefault({ plugin: authorizeHttpRequestPlugin }),\n declareDefault({ plugin: dispatchHttpRequestPlugin }),\n declareDefault({ plugin: receiveHttpResponsePlugin }),\n ],\n inputSchema: z.custom<AttemptHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input, imports }): Promise<HttpResponse> => {\n const { attempt } = input;\n const preparedRequest = await imports.prepareHttpRequest({\n request: input.request,\n attempt,\n });\n const authorizedRequest = await imports.authorizeHttpRequest({\n request: preparedRequest,\n attempt,\n });\n const response = await imports.dispatchHttpRequest({\n request: authorizedRequest,\n attempt,\n });\n\n return imports.receiveHttpResponse({\n request: authorizedRequest,\n response,\n attempt,\n });\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport { CoreErrorCode, createCoreError } from \"../types/errors\";\nimport type { AuthorizeHttpRequestInput, HttpRequest } from \"./types\";\n\n/**\n * Name the scheme that went unclaimed, and NOTHING else off the reference.\n *\n * A reference is opaque, so its value can be anything a caller passes,\n * including a raw credential. The scheme is the half that identifies which\n * provider was supposed to claim it, and the only half safe to put in an error\n * that will be logged.\n *\n * Parsed here rather than through `normalizeConnection` on purpose. The\n * transport treats `connection` as an opaque string and the connections module\n * owns scheme semantics, including whatever default a head assigns to a bare\n * reference. Reaching for that rule here would join two modules that are\n * independent today, and would report an interpretation where this stage should\n * report what it actually saw on the request.\n */\nfunction describeUnclaimedConnection(connection: string): string {\n const delimiterIndex = connection.indexOf(\":\");\n if (delimiterIndex === -1) {\n return 'no auth provider claimed this connection, and it carries no \"scheme:\" prefix';\n }\n return `no auth provider claimed the \"${connection.slice(0, delimiterIndex)}\" connection scheme`;\n}\n\nexport const authorizeHttpRequestPlugin = defineMethod({\n name: \"authorizeHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<AuthorizeHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpRequest> => {\n const { connection } = input.request;\n if (connection != null) {\n throw createCoreError({\n code: CoreErrorCode.Unknown,\n message: `authorizeHttpRequest: ${describeUnclaimedConnection(connection)}, so the request was not sent.`,\n });\n }\n\n return input.request;\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type {\n DispatchHttpRequestInput,\n HttpFetchInit,\n HttpRequest,\n HttpResponse,\n} from \"./types\";\n\nfunction toFetchInput(request: HttpRequest) {\n const init: Record<string, unknown> = { ...request };\n const { url } = request;\n delete init.url;\n delete init.connection;\n return { url, init: init as HttpFetchInit };\n}\n\nexport const dispatchHttpRequestPlugin = defineMethod({\n name: \"dispatchHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<DispatchHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpResponse> => {\n const { url, init } = toFetchInput(input.request);\n return fetch(url, init);\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { HttpRequest, PrepareHttpRequestInput } from \"./types\";\n\nexport const prepareHttpRequestPlugin = defineMethod({\n name: \"prepareHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<PrepareHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpRequest> => input.request,\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { HttpResponse, ReceiveHttpResponseInput } from \"./types\";\n\nexport const receiveHttpResponsePlugin = defineMethod({\n name: \"receiveHttpResponse\",\n namespace: \"kitcore\",\n inputSchema: z.custom<ReceiveHttpResponseInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpResponse> => input.response,\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type {\n HttpOperationContext,\n HttpRequest,\n InitializeHttpRequestInput,\n} from \"./types\";\n\n/**\n * Whether this body can be sent a second time.\n *\n * An ALLOWLIST, not a check for streams. The single-use set is open: a web\n * `ReadableStream` is the obvious member, but undici also takes any async\n * iterable as a body, so `fs.createReadStream(...)`, `Readable.from(...)`, and\n * an async generator are all single-use too, and none of them look alike.\n * Naming the replayable types instead closes the set, because the replayable\n * ones are exactly what `BodyInit` defines.\n *\n * The two mistakes are not equal, which is what settles the direction. Only\n * `retryHttpRequest` reads this. A wrong \"no\" costs a retry that would have\n * worked. A wrong \"yes\" resends a consumed stream, and undici throws\n * `TypeError: Response body object should not be disturbed or locked`, turning\n * a legible 503 into a type error the caller cannot act on.\n *\n * A body from another realm fails `instanceof` and comes out non-replayable.\n * That is the harmless side of the same trade.\n */\nfunction isReplayableBody(body: InitializeHttpRequestInput[\"request\"][\"body\"]) {\n // A string, and anything else primitive fetch will stringify.\n if (body == null || typeof body !== \"object\") return true;\n return (\n (typeof Blob !== \"undefined\" && body instanceof Blob) || // File extends Blob\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" &&\n body instanceof URLSearchParams) ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) // every TypedArray, plus DataView\n );\n}\n\n/**\n * The seam where a caller's `url` becomes the string every stage below sees.\n *\n * Copies only when there is something to normalize. `sendHttpRequest` promises\n * that skipping input validation keeps the caller's object identity intact, so\n * a request that already carries a string url must come out the same object.\n */\nfunction withStringUrl(request: InitializeHttpRequestInput[\"request\"]) {\n return typeof request.url === \"string\"\n ? (request as HttpRequest)\n : { ...request, url: String(request.url) };\n}\n\n/**\n * Completes the operation context: normalizes the caller's request and records\n * whether its body can be sent again. Everything below this stage reads those\n * two facts off `attempt.operation`, and neither changes across retries.\n */\nexport const initializeHttpRequestPlugin = defineMethod({\n name: \"initializeHttpRequest\",\n namespace: \"kitcore\",\n inputSchema: z.custom<InitializeHttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input }): Promise<HttpOperationContext> => {\n const request = withStringUrl(input.request);\n\n return {\n ...input.operation,\n request,\n replayable: isReplayableBody(request.body),\n };\n },\n});\n","import { declareOptionalProperty, defineHook } from \"../model\";\nimport { attemptHttpRequestPlugin } from \"./attempt-http-request\";\nimport type { HttpFetchInit, HttpRequest, HttpResponse } from \"./types\";\n\n/**\n * Options for {@link retryHttpRequestPlugin}, supplied by id like every other\n * kitcore configuration value. Absent means the defaults below.\n */\nexport interface RetryHttpRequestOptions {\n /** Total attempts including the first. Default 3. */\n maxAttempts?: number;\n /** Refuse a delay longer than this and give up instead. Default 60 seconds. */\n maxDelayMilliseconds?: number;\n /** Statuses to retry on an idempotent method. Default 429, 500, 502, 503, 504. */\n retryStatuses?: readonly number[];\n /**\n * Statuses to retry on a NON-idempotent method. Default 429 only: a rate\n * limit rejects the request before the server does any work, so it is known\n * not to have executed. A 502 or 504 carries no such promise.\n */\n nonIdempotentRetryStatuses?: readonly number[];\n /** Methods safe to resend. Default the RFC 9110 idempotent set. */\n idempotentMethods?: readonly string[];\n /**\n * Retry when an attempt THROWS (a network failure) rather than answering.\n * Default false. A thrown request may still have reached the server, and\n * turning this on silently widens what gets resent, so it is a deliberate\n * choice rather than a default.\n */\n retryOnError?: boolean;\n}\n\nexport const RETRY_HTTP_REQUEST_OPTIONS_ID = \"kitcore/retryHttpRequestOptions\";\n\nexport const retryHttpRequestOptionsPluginRef = declareOptionalProperty<\n typeof RETRY_HTTP_REQUEST_OPTIONS_ID,\n RetryHttpRequestOptions\n>({ id: RETRY_HTTP_REQUEST_OPTIONS_ID });\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_MAX_DELAY_MILLISECONDS = 60_000;\nconst DEFAULT_RETRY_STATUSES = [429, 500, 502, 503, 504] as const;\nconst DEFAULT_NON_IDEMPOTENT_RETRY_STATUSES = [429] as const;\nconst DEFAULT_IDEMPOTENT_METHODS = [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"OPTIONS\",\n \"TRACE\",\n] as const;\nconst BASE_BACKOFF_MILLISECONDS = 1_000;\n/** Randomize up to this fraction of the delay, so many clients retrying the\n * same outage do not synchronize into a second thundering herd. */\nconst JITTER_FACTOR = 0.5;\n/** `X-RateLimit-Reset` values at or above this are epoch seconds (no real\n * epoch is before 2001); below it they are delta seconds (no real window is\n * decades long). */\nconst EPOCH_THRESHOLD_SECONDS = 1_000_000_000;\n\n/**\n * `Retry-After` is either a delay in seconds or an HTTP date (RFC 9110).\n *\n * `X-RateLimit-Reset` has no single standard. Some servers send the number\n * of seconds UNTIL the window resets (@fastify/rate-limit, Envoy); others\n * send the unix time AT WHICH it resets (GitHub). The header itself does\n * not say which, but the number's size does: a wait is at most days, a\n * unix timestamp is over a billion. Getting this wrong is not cosmetic —\n * a \"resets in 30 days\" read as a unix time is a date in 1970, which\n * clamps the delay to zero and resends every remaining attempt\n * immediately, the opposite of what the server asked for.\n *\n * `X-RateLimit-Reset` only directs a 429. The header is quota telemetry —\n * when the caller's window resets — and servers attach it to every\n * response, not just failures (GitHub sends it on successes and 5xx\n * alike). Only on a 429 does the quota window coincide with when the\n * failure clears; honored on a 5xx, a long window would delay or abandon\n * a retry the backoff should handle. `Retry-After` stays status-agnostic:\n * it is an explicit instruction on any response (RFC 9110 names 503).\n */\nfunction directedDelayMilliseconds(response: HttpResponse): number | undefined {\n const retryAfter = response.headers.get(\"retry-after\");\n if (retryAfter) {\n const seconds = Number.parseInt(retryAfter, 10);\n // Clamped like the date branch below. A negative `Retry-After` is a server\n // bug, and unclamped it passes the ceiling check and resends with no wait\n // at all, which is the opposite of what the header asked for.\n if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1_000);\n const date = Date.parse(retryAfter);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n }\n if (response.status !== 429) return undefined;\n const reset = response.headers.get(\"x-ratelimit-reset\");\n if (reset) {\n const resetValue = Number.parseInt(reset, 10);\n if (!Number.isNaN(resetValue)) {\n return resetValue >= EPOCH_THRESHOLD_SECONDS\n ? Math.max(0, resetValue * 1_000 - Date.now())\n : Math.max(0, resetValue * 1_000);\n }\n }\n return undefined;\n}\n\nfunction backoffMilliseconds(attemptNumber: number): number {\n const base = BASE_BACKOFF_MILLISECONDS * 2 ** (attemptNumber - 1);\n return base + Math.random() * JITTER_FACTOR * base;\n}\n\n/** The reason a caller gave for aborting, or a stand-in when the platform's\n * signal carries none. */\nfunction abortReason(signal: HttpFetchInit[\"signal\"]): unknown {\n const reason = (signal as { reason?: unknown } | null | undefined)?.reason;\n return reason ?? new Error(\"The request was aborted.\");\n}\n\n/**\n * Wait between attempts, unless the caller cancels first.\n *\n * An abort REJECTS rather than resolving, which is what makes cancellation\n * reach the retry loop at all. A resolved wait returns to the top of the loop\n * and sends the next attempt on a signal that is already aborted: that attempt\n * fails instantly, and with `retryOnError` the loop then spins through every\n * remaining attempt at zero delay. Rejecting instead ends the operation the way\n * `fetch` itself ends an aborted one.\n */\nfunction sleep(\n milliseconds: number,\n signal: HttpFetchInit[\"signal\"],\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(finish, milliseconds);\n function finish() {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n resolve();\n }\n function cancel() {\n clearTimeout(timer);\n reject(abortReason(signal));\n }\n if (signal?.aborted) return cancel();\n signal?.addEventListener(\"abort\", cancel, { once: true });\n });\n}\n\nfunction isIdempotent(\n request: HttpRequest,\n idempotentMethods: readonly string[],\n): boolean {\n const method = (request.method ?? \"GET\").toUpperCase();\n return idempotentMethods.includes(method);\n}\n\n/**\n * Re-issue a failed attempt, opt-in by composition.\n *\n * Wraps `attemptHttpRequest` rather than `sendHttpRequest`, which is what makes\n * the retry correct rather than merely present: `initializeHttpRequest` has\n * already run, so every attempt shares one `operationId`, and this can read\n * `attempt.operation.replayable` before resending.\n *\n * Three independent gates, each answering a different question:\n *\n * replayable CAN we resend? a consumed stream body cannot go out again\n * idempotent is it SAFE? a 504 may mean the server DID process it\n * status SHOULD we? policy, configurable\n *\n * The idempotency gate is the subtle one. A 429 is DIRECTED: the server told us\n * when to return, and a rate limit rejects before doing work, so it is known not\n * to have executed and any method may be resent. A 5xx is SPECULATIVE: no\n * instruction, and the request may have succeeded with the response lost, so\n * resending a POST would double-execute it.\n *\n * Exhausting the retries RETURNS the last response rather than throwing.\n * Deciding what counts as a failure belongs to `receiveHttpResponse` and a\n * head's error mapping; this decides only whether to try again.\n *\n * Cancellation is the one exception, and it throws. A caller who aborts wants\n * the operation to stop, not to receive whichever response the last attempt\n * happened to produce, so an abort during the wait ends the loop with the\n * caller's own reason.\n */\nexport const retryHttpRequestPlugin = defineHook({\n name: \"retryHttpRequest\",\n imports: [attemptHttpRequestPlugin, retryHttpRequestOptionsPluginRef],\n wrap: {\n attemptHttpRequest: async ({ input, imports, next }) => {\n const options: RetryHttpRequestOptions =\n imports.retryHttpRequestOptions ?? {};\n const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const maxDelayMilliseconds =\n options.maxDelayMilliseconds ?? DEFAULT_MAX_DELAY_MILLISECONDS;\n const idempotentMethods =\n options.idempotentMethods ?? DEFAULT_IDEMPOTENT_METHODS;\n const statuses = isIdempotent(input.request, idempotentMethods)\n ? (options.retryStatuses ?? DEFAULT_RETRY_STATUSES)\n : (options.nonIdempotentRetryStatuses ??\n DEFAULT_NON_IDEMPOTENT_RETRY_STATUSES);\n\n for (let attemptNumber = 1; ; attemptNumber++) {\n const attempt = {\n ...input.attempt,\n attemptNumber,\n // Per-attempt scratch: a cross-stage handoff from a previous attempt\n // describes a request that is no longer in flight. `operation` rides\n // through unchanged, so the id and the caller's original request are\n // the same for every attempt.\n state: {},\n };\n\n let response: HttpResponse | undefined;\n try {\n response = await next({ ...input, attempt });\n } catch (error) {\n if (\n !options.retryOnError ||\n !canRetry(\n attemptNumber,\n maxAttempts,\n input.attempt.operation.replayable,\n )\n ) {\n throw error;\n }\n await sleep(\n Math.min(backoffMilliseconds(attemptNumber), maxDelayMilliseconds),\n attempt.signal,\n );\n continue;\n }\n\n if (\n !statuses.includes(response.status) ||\n !canRetry(\n attemptNumber,\n maxAttempts,\n input.attempt.operation.replayable,\n )\n ) {\n return response;\n }\n\n // The ceiling means two different things depending on who set the\n // delay. A server asking for longer than we are willing to wait is a\n // refusal, not an invitation to ignore it and hammer sooner. Our own\n // backoff exceeding it is nobody's refusal, so it clamps.\n //\n // Treating both as a refusal turned the ceiling into an off switch:\n // `{ maxDelayMilliseconds: 500 }` reads as \"keep the waits short\", but\n // the first backoff is 1000 to 1500ms, so the loop returned after one\n // attempt and retry did nothing at all.\n const directed = directedDelayMilliseconds(response);\n if (directed != null && directed > maxDelayMilliseconds)\n return response;\n const delay = Math.min(\n directed ?? backoffMilliseconds(attemptNumber),\n maxDelayMilliseconds,\n );\n\n // Release the response we are about to drop, after every path that can\n // still return it. An unread body keeps its socket occupied: undici can\n // pause mid-message on a large response, and the connection stays open\n // until something drains or cancels it. `receiveHttpResponse` is\n // identity by default, so nothing guarantees a read.\n //\n // Before the sleep, not after, so an abort during the backoff releases\n // it too: `sleep` rejects, and the response would otherwise be dropped\n // unread. The rejection is swallowed because a `receiveHttpResponse`\n // wrap may have consumed the body already, which locks the stream and\n // makes `cancel()` throw.\n await response.body?.cancel().catch(() => {});\n await sleep(delay, attempt.signal);\n }\n },\n },\n});\n\nfunction canRetry(\n attemptNumber: number,\n maxAttempts: number,\n replayable: boolean,\n): boolean {\n return attemptNumber < maxAttempts && replayable;\n}\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { attemptHttpRequestPlugin } from \"./attempt-http-request\";\nimport { initializeHttpRequestPlugin } from \"./initialize-http-request\";\nimport type { HttpOperationStart, HttpRequestInput } from \"./types\";\n\nfunction createOperationId() {\n return globalThis.crypto?.randomUUID?.() ?? `http-${Date.now()}`;\n}\n\n/**\n * The transport orchestrator: turn an {@link HttpRequestInput} into a native\n * `Response`. It owns the OPERATION, the things that happen once per caller\n * request, and delegates the per-attempt work to `attemptHttpRequest`:\n *\n * initialize once -> attempt (prepare, authorize, dispatch, receive)\n *\n * The split is the seam that makes re-issuing a request possible. A wrap here\n * sees the whole operation (a concurrency permit, an overall deadline); a wrap\n * on `attemptHttpRequest` sees one attempt and may run it more than once\n * (retry, an approval re-issue). Cross-cutting behavior should still wrap the\n * narrowest stage it owns.\n *\n * A caller's `url` may be a `URL`; initialize normalizes it, so every stage\n * from prepare onward receives a plain string.\n *\n * A raw method: it owns its input (the fetch-shaped `HttpRequest`), so\n * `skipInputValidation` keeps the caller's object identity intact: no parse, no\n * coercion, no clone. The `inputSchema` is projection-only (never run as a\n * validator) and exists so the registry has a shape to describe.\n *\n * An unresolved `connection` fails in the default authorize stage: no auth wrap\n * consumed it, so the request would otherwise go out unauthenticated.\n *\n * No retry by default: with nothing composed this runs exactly one attempt.\n * `retryHttpRequestPlugin` is opt-in.\n */\nexport const sendHttpRequestPlugin = defineMethod({\n name: \"sendHttpRequest\",\n namespace: \"kitcore\",\n imports: [\n declareDefault({ plugin: initializeHttpRequestPlugin }),\n declareDefault({ plugin: attemptHttpRequestPlugin }),\n ],\n inputSchema: z.custom<HttpRequestInput>(),\n skipInputValidation: true,\n run: async ({ input, imports }) => {\n const start: HttpOperationStart = {\n operationId: createOperationId(),\n signal: input.signal,\n };\n // Initialize COMPLETES the operation context rather than returning a bag of\n // its own: what it derives (the normalized request, replayability) is true\n // of the whole operation, so it belongs beside the id every stage already\n // reads.\n const operation = await imports.initializeHttpRequest({\n request: input,\n operation: start,\n });\n\n return imports.attemptHttpRequest({\n request: operation.request,\n attempt: {\n attemptNumber: 1,\n operation,\n signal: operation.signal,\n state: {},\n },\n });\n },\n});\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { sendHttpRequestPlugin } from \"./send-http-request\";\nimport type { HttpRequestInput } from \"./types\";\n\n/**\n * `fetch` — native `fetch(url, init)` ergonomics over the transport. It\n * delegates to `sendHttpRequest`, inheriting its stage pipeline and any wraps\n * composed around those stages.\n *\n * It imports the transport as a DEFAULT (`declareDefault`), so `fetchPlugin`\n * works alone: with nothing else composed, the default pipeline dispatches\n * through `globalThis.fetch`. A composed transport provider of the same id\n * preempts the default, so hello-world is just `fetchPlugin`.\n *\n * `fetch` is branch-free and never inspects `connection` — it just delegates, and\n * the default authorizer fails loud on an unresolved reference. A raw method\n * (`skipInputValidation`): the caller's `init` passes through untouched, so this\n * is global `fetch` plus the `url` / `connection` shape. Content-type inference\n * for non-standard bodies (a plain object → JSON) is a head ergonomic, not\n * kitcore-generic.\n *\n * `url` takes a `URL` as well as a string, matching global `fetch`. A `Request`\n * is the one first argument global `fetch` takes that this does not; see\n * {@link HttpRequestInput}.\n */\nexport const fetchPlugin = defineMethod({\n name: \"fetch\",\n namespace: \"kitcore\",\n imports: [declareDefault({ plugin: sendHttpRequestPlugin })],\n positional: [\"url\", \"init\"],\n inputSchema: z.custom<{\n url: string | URL;\n init?: Omit<HttpRequestInput, \"url\">;\n }>(),\n skipInputValidation: true,\n run: ({ input, imports }) => {\n const { url, init } = input;\n return imports.sendHttpRequest({ url, ...init });\n },\n});\n","import type { HttpRequest } from \"./types\";\n\n/**\n * Header names whose value is a credential.\n *\n * A fixed list rather than a pattern. A pattern over header names would either\n * miss a bespoke one or mask something harmless, and a reader cannot tell which\n * happened from the output.\n */\nconst CREDENTIAL_HEADERS = [\"authorization\", \"x-api-key\"];\n\n/**\n * Show enough of a secret to recognize it, never enough to use it.\n *\n * Recognizing matters: the usual debugging question is \"which token did it\n * send\", and an all-asterisks value cannot answer it. Four characters at each\n * end identify a token among the two or three a developer is juggling.\n *\n * A short value gets one character, because four and four of an eight\n * character secret is the secret.\n */\nfunction maskSecret(secret: string): string {\n if (secret.length > 12) {\n return `${secret.slice(0, 4)}...${secret.slice(-4)}`;\n }\n return `${secret.charAt(0)}...`;\n}\n\n/**\n * Mask a credential header's value, keeping any scheme prefix (`Bearer `,\n * `Basic `) so the reader can still see which scheme was used.\n */\nfunction maskCredentialHeader(value: string): string {\n const spaceIndex = value.indexOf(\" \");\n if (spaceIndex > 0 && spaceIndex < value.length - 1) {\n return `${value.slice(0, spaceIndex + 1)}${maskSecret(value.slice(spaceIndex + 1))}`;\n }\n return maskSecret(value);\n}\n\n/**\n * Headers with every credential value masked, as a plain object a logger can\n * print. Header names come back lowercased, because `Headers` normalizes them.\n */\nexport function redactHeaders(\n headers?: HeadersInit,\n): Record<string, string> | undefined {\n if (!headers) return headers;\n\n const normalized = new Headers(headers);\n for (const [name, value] of normalized.entries()) {\n if (CREDENTIAL_HEADERS.includes(name.toLowerCase())) {\n normalized.set(name, maskCredentialHeader(value));\n }\n }\n return Object.fromEntries(normalized);\n}\n\n/**\n * A log-safe view of a request: credential headers masked, and `connection`\n * masked with it.\n *\n * `connection` is the half a head cannot redact for itself. The transport\n * treats it as an opaque string, so its value is whatever a caller passed,\n * including a raw credential (see {@link HttpRequest}). A hook printing a\n * stage's `args` would put it on the terminal.\n *\n * The url and the body are NOT redacted. A token can ride either, in a query\n * parameter or a form field, but kitcore does not know which one, and masking\n * by guessed name would hide the wrong thing while claiming the rest is safe.\n * A head that puts credentials there has to redact them itself.\n *\n * Returns a new object. The pipeline treats `HttpOperationContext.request` as\n * read-only, and a logger must not be the thing that breaks that.\n */\nexport function redactHttpRequest(request: HttpRequest): HttpRequest {\n const redacted: HttpRequest = { ...request };\n if (request.headers) redacted.headers = redactHeaders(request.headers);\n if (request.connection != null) {\n redacted.connection = maskSecret(request.connection);\n }\n return redacted;\n}\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { DefaultConnectionSchemeInput } from \"./types\";\n\nexport const defaultConnectionSchemePlugin = defineMethod({\n name: \"defaultConnectionScheme\",\n namespace: \"kitcore\",\n inputSchema: z.custom<DefaultConnectionSchemeInput>(),\n skipInputValidation: true,\n run: (): string | undefined => undefined,\n});\n","import { z } from \"zod\";\nimport { declareDefault, defineMethod } from \"../model\";\nimport { defaultConnectionSchemePlugin } from \"./default-connection-scheme\";\nimport type { NormalizedConnection, NormalizeConnectionInput } from \"./types\";\n\nexport const normalizeConnectionPlugin = defineMethod({\n name: \"normalizeConnection\",\n namespace: \"kitcore\",\n imports: [declareDefault({ plugin: defaultConnectionSchemePlugin })],\n inputSchema: z.custom<NormalizeConnectionInput>(),\n skipInputValidation: true,\n run: ({ input, imports }): NormalizedConnection | undefined => {\n const { connection } = input;\n if (connection == null) {\n return undefined;\n }\n\n const delimiterIndex = connection.indexOf(\":\");\n if (delimiterIndex !== -1) {\n return {\n connection,\n scheme: connection.slice(0, delimiterIndex),\n value: connection.slice(delimiterIndex + 1),\n };\n }\n\n const scheme = imports.defaultConnectionScheme({ connection });\n return {\n connection,\n scheme,\n value: connection,\n };\n },\n});\n","import { z } from \"zod\";\nimport { defineMethod } from \"../model\";\nimport type { ResolveConnectionInput } from \"./types\";\n\n/**\n * SELECT which connection REFERENCE a call should use: the explicit one if the\n * caller passed it, else `undefined`. It deals only in references, never a\n * secret. Turning a reference into a credential is `authorizeHttpRequest`.\n *\n * The default is a pass-through, so this exists to be wrapped. A head adds\n * discovery or defaulting with a `defineHook` over `resolveConnection`, keyed by\n * `input.connectionType` (reading a connection id from an env var, say). Because\n * it is an ordinary method rather than an interactive prompt, a caller in plain\n * code gets the head's defaulting too, not only a caller driven by the\n * controller.\n *\n * Returning `undefined` is not an error here. Whether a missing connection is\n * fatal depends on what the caller declared it needs, which this stage cannot\n * see, so this stays policy-free.\n */\nexport const resolveConnectionPlugin = defineMethod({\n name: \"resolveConnection\",\n namespace: \"kitcore\",\n inputSchema: z.custom<ResolveConnectionInput>(),\n skipInputValidation: true,\n run: ({ input }: { input: ResolveConnectionInput }): string | undefined =>\n input.connection,\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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ACX,aAAa,eAAE,OAA+B;AAAA,EAC9C,qBAAqB;AAAA,EACrB,KAAK,CAAC,EAAE,MAAM,MACZ,MAAM;AACV,CAAC;","names":["start","import_zod","parseOrThrow","exports","import_zod","isRecord","exports","getContext","getRegistry","out","context","plugins","import_zod","import_zod","topoOrder","actions","start","step","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","start","import_zod","import_zod","import_zod","import_zod"]}